diff --git a/.flake8 b/.flake8 index 5b99098ec..a5f814528 100644 --- a/.flake8 +++ b/.flake8 @@ -6,10 +6,10 @@ # explicitly when using `ignore`. ignore = E501, W503 per-file-ignores = - */__init__.py: E402, F401 + */__init__.py: IMP100, E402, F401 # we test various import patterns tests/test_exports.py: IMP100, IMP101, IMP102 - tests/*: IMP101, IMP102, IMP102 + tests/*: IMP101, IMP102, BAN100 # backcompat with outdated import patterns stripe/api_resources/*: IMP100, E402, F401 @@ -36,4 +36,5 @@ per-file-ignores = extension = SPY = flake8_stripe:TypingImportsChecker IMP = flake8_stripe:StripeImportsChecker + BAN = flake8_stripe:BanPublicMethodsChecker paths=./flake8_stripe diff --git a/README.md b/README.md index 2211087e5..06b268bff 100644 --- a/README.md +++ b/README.md @@ -49,17 +49,18 @@ available in your [Stripe Dashboard][api-keys]. Set `stripe.api_key` to its value: ```python -import stripe -stripe.api_key = "sk_test_..." +from stripe import StripeClient + +client = StripeClient("sk_test_...") # list customers -customers = stripe.Customer.list() +customers = client.customers.list() # print the first customer's email print(customers.data[0].email) # retrieve specific Customer -customer = stripe.Customer.retrieve("cus_123456789") +customer = client.customers.retrieve("cus_123456789") # print that customer's email print(customer.email) @@ -75,40 +76,45 @@ these errors. ### Per-request Configuration -Configure individual requests with keyword arguments. For example, you can make +Configure individual requests with the `options` argument. For example, you can make requests with a specific [Stripe Version](https://stripe.com/docs/api#versioning) or as a [connected account](https://stripe.com/docs/connect/authentication#authentication-via-the-stripe-account-header): ```python -import stripe +from stripe import StripeClient + +client = StripeClient("sk_test_...") # list customers -stripe.Customer.list( - api_key="sk_test_...", - stripe_account="acct_...", - stripe_version="2019-02-19" +client.customers.list( + options={ + "api_key": "sk_test_...", + "stripe_account": "acct_...", + "stripe_version": "2019-02-19", + } ) # retrieve single customer -stripe.Customer.retrieve( +client.customers.retrieve( "cus_123456789", - api_key="sk_test_...", - stripe_account="acct_...", - stripe_version="2019-02-19" + options={ + "api_key": "sk_test_...", + "stripe_account": "acct_...", + "stripe_version": "2019-02-19", + } ) ``` -### Configuring a Client +### Configuring an HTTP Client -The library can be configured to use `urlfetch`, `requests`, `pycurl`, or -`urllib2` with `stripe.default_http_client`: +You can configure your `StripeClient` to use `urlfetch`, `requests`, `pycurl`, or +`urllib2` with the `http_client` option: ```python -client = stripe.http_client.UrlFetchClient() -client = stripe.http_client.RequestsClient() -client = stripe.http_client.PycurlClient() -client = stripe.http_client.Urllib2Client() -stripe.default_http_client = client +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.Urllib2Client()) ``` Without a configured client, by default the library will attempt to load @@ -117,10 +123,10 @@ as a last resort). We usually recommend that people use `requests`. ### Configuring a Proxy -A proxy can be configured with `stripe.proxy`: +A proxy can be configured with the `proxy` client option: ```python -stripe.proxy = "https://user:pass@example.com:1234" +client = StripeClient("sk_test_...", proxy="https://user:pass@example.com:1234") ``` ### Configuring Automatic Retries @@ -129,7 +135,7 @@ You can enable automatic retries on requests that fail due to a transient problem by configuring the maximum number of retries: ```python -stripe.max_network_retries = 2 +client = StripeClient("sk_test_...", max_network_retries=2) ``` Various errors can trigger a retry, like a connection error or a timeout, and @@ -172,7 +178,7 @@ There are a few options for enabling it: You can access the HTTP response code and headers using the `last_response` property of the returned resource. ```python -customer = stripe.Customer.retrieve( +customer = client.customers.retrieve( "cus_123456789" ) @@ -233,7 +239,7 @@ in your `requirements.txt` to constrain `pip` to a certain minor range of `strip The types describe the [Stripe API version](https://stripe.com/docs/api/versioning) that was the latest at the time of release. This is the version that your library -sends by default. If you are overriding `stripe.api_version`, or using a +sends by default. If you are overriding `stripe.api_version` / `stripe_version` on the `StripeClient`, or using a [webhook endpoint](https://stripe.com/docs/webhooks#api-versions) tied to an older version, be aware that the data you see at runtime may not match the types. diff --git a/flake8_stripe/flake8_stripe.py b/flake8_stripe/flake8_stripe.py index 9f6516c81..1b012be43 100644 --- a/flake8_stripe/flake8_stripe.py +++ b/flake8_stripe/flake8_stripe.py @@ -24,7 +24,9 @@ class TypingImportsChecker: allowed_typing_extensions_imports = [ "Literal", "NoReturn", + "NotRequired", "Protocol", + "Self", "TYPE_CHECKING", "Type", "TypedDict", @@ -173,3 +175,49 @@ def run(self) -> Iterator[Tuple[int, int, str, type]]: msg, type(self), ) + + +class BanPublicMethodsChecker: + name = __name__ + version = "0.1.0" + + def __init__(self, tree: ast.AST, filename: str): + self.tree = tree + self.filename = filename + + def run(self) -> Iterator[Tuple[int, int, str, type]]: + for node in ast.walk(self.tree): + if isinstance(node, ast.Call): + name = None + if isinstance(node.func, ast.Attribute): + name = node.func.attr + elif isinstance(node.func, ast.Name): + name = node.func.id + + if not name: + continue + + if name == "convert_to_stripe_object": + msg = "BAN100 Do not use public `convert_to_stripe_object` internally. Instead, call `_convert_to_stripe_object` directly." + yield ( + node.lineno, + node.col_offset, + msg, + type(self), + ) + if name == "construct_from": + msg = "BAN100 Do not use public `construct_from` internally. Instead, call `_construct_from` directly." + yield ( + node.lineno, + node.col_offset, + msg, + type(self), + ) + if name == "refresh_from": + msg = "BAN100 Do not use public `refresh_from` internally. Instead, call `_refresh_from` directly." + yield ( + node.lineno, + node.col_offset, + msg, + type(self), + ) diff --git a/stripe/__init__.py b/stripe/__init__.py index f2e187e67..71b054df9 100644 --- a/stripe/__init__.py +++ b/stripe/__init__.py @@ -12,6 +12,7 @@ # Configuration variables from stripe._api_version import _ApiVersion +from stripe._api_requestor import _APIRequestor # We must import the app_info module early to populate it into # `sys.modules`; otherwise doing `import stripe.app_info` will end up @@ -20,11 +21,17 @@ from stripe._app_info import AppInfo as AppInfo from stripe._version import VERSION as VERSION +# Constants +DEFAULT_API_BASE: str = "https://api.stripe.com" +DEFAULT_CONNECT_API_BASE: str = "https://connect.stripe.com" +DEFAULT_UPLOAD_API_BASE: str = "https://files.stripe.com" + + api_key: Optional[str] = None client_id: Optional[str] = None -api_base: str = "https://api.stripe.com" -connect_api_base: str = "https://connect.stripe.com" -upload_api_base: str = "https://files.stripe.com" +api_base: str = DEFAULT_API_BASE +connect_api_base: str = DEFAULT_CONNECT_API_BASE +upload_api_base: str = DEFAULT_UPLOAD_API_BASE api_version: str = _ApiVersion.CURRENT verify_ssl_certs: bool = True proxy: Optional[str] = None @@ -48,6 +55,9 @@ WebhookSignature as WebhookSignature, ) +# StripeClient +from stripe._stripe_client import StripeClient as StripeClient # noqa + # Sets some basic information about the running application that's sent along # with API requests. Useful for plugin authors to identify their plugin when @@ -109,8 +119,14 @@ def set_app_info( from stripe._verify_mixin import ( VerifyMixin as VerifyMixin, ) -from stripe._api_requestor import ( - APIRequestor as APIRequestor, +from stripe._requestor_options import ( + RequestorOptions as RequestorOptions, +) +from stripe._api_mode import ( + ApiMode as ApiMode, +) +from stripe._base_address import ( + BaseAddress as BaseAddress, ) # Response types @@ -149,7 +165,6 @@ def set_app_info( # Backwards compatibility re-exports if not TYPE_CHECKING: - from stripe import _api_requestor as api_requestor from stripe import _stripe_response as stripe_response from stripe import _stripe_object as stripe_object from stripe import _error_object as error_object @@ -210,105 +225,288 @@ def __getattr__(name): treasury as treasury, ) from stripe._account import Account as Account +from stripe._account_capability_service import ( + AccountCapabilityService as AccountCapabilityService, +) +from stripe._account_external_account_service import ( + AccountExternalAccountService as AccountExternalAccountService, +) from stripe._account_link import AccountLink as AccountLink +from stripe._account_link_service import ( + AccountLinkService as AccountLinkService, +) +from stripe._account_login_link_service import ( + AccountLoginLinkService as AccountLoginLinkService, +) +from stripe._account_person_service import ( + AccountPersonService as AccountPersonService, +) +from stripe._account_service import AccountService as AccountService from stripe._account_session import AccountSession as AccountSession +from stripe._account_session_service import ( + AccountSessionService as AccountSessionService, +) from stripe._apple_pay_domain import ApplePayDomain as ApplePayDomain +from stripe._apple_pay_domain_service import ( + ApplePayDomainService as ApplePayDomainService, +) from stripe._application import Application as Application from stripe._application_fee import ApplicationFee as ApplicationFee from stripe._application_fee_refund import ( ApplicationFeeRefund as ApplicationFeeRefund, ) +from stripe._application_fee_refund_service import ( + ApplicationFeeRefundService as ApplicationFeeRefundService, +) +from stripe._application_fee_service import ( + ApplicationFeeService as ApplicationFeeService, +) +from stripe._apps_service import AppsService as AppsService from stripe._balance import Balance as Balance +from stripe._balance_service import BalanceService as BalanceService from stripe._balance_transaction import ( BalanceTransaction as BalanceTransaction, ) +from stripe._balance_transaction_service import ( + BalanceTransactionService as BalanceTransactionService, +) from stripe._bank_account import BankAccount as BankAccount +from stripe._billing_portal_service import ( + BillingPortalService as BillingPortalService, +) from stripe._capability import Capability as Capability from stripe._card import Card as Card from stripe._cash_balance import CashBalance as CashBalance from stripe._charge import Charge as Charge +from stripe._charge_service import ChargeService as ChargeService +from stripe._checkout_service import CheckoutService as CheckoutService +from stripe._climate_service import ClimateService as ClimateService from stripe._connect_collection_transfer import ( ConnectCollectionTransfer as ConnectCollectionTransfer, ) from stripe._country_spec import CountrySpec as CountrySpec +from stripe._country_spec_service import ( + CountrySpecService as CountrySpecService, +) from stripe._coupon import Coupon as Coupon +from stripe._coupon_service import CouponService as CouponService from stripe._credit_note import CreditNote as CreditNote from stripe._credit_note_line_item import ( CreditNoteLineItem as CreditNoteLineItem, ) +from stripe._credit_note_line_item_service import ( + CreditNoteLineItemService as CreditNoteLineItemService, +) +from stripe._credit_note_preview_lines_service import ( + CreditNotePreviewLinesService as CreditNotePreviewLinesService, +) +from stripe._credit_note_service import CreditNoteService as CreditNoteService from stripe._customer import Customer as Customer from stripe._customer_balance_transaction import ( CustomerBalanceTransaction as CustomerBalanceTransaction, ) +from stripe._customer_balance_transaction_service import ( + CustomerBalanceTransactionService as CustomerBalanceTransactionService, +) +from stripe._customer_cash_balance_service import ( + CustomerCashBalanceService as CustomerCashBalanceService, +) from stripe._customer_cash_balance_transaction import ( CustomerCashBalanceTransaction as CustomerCashBalanceTransaction, ) +from stripe._customer_cash_balance_transaction_service import ( + CustomerCashBalanceTransactionService as CustomerCashBalanceTransactionService, +) +from stripe._customer_funding_instructions_service import ( + CustomerFundingInstructionsService as CustomerFundingInstructionsService, +) +from stripe._customer_payment_method_service import ( + CustomerPaymentMethodService as CustomerPaymentMethodService, +) +from stripe._customer_payment_source_service import ( + CustomerPaymentSourceService as CustomerPaymentSourceService, +) +from stripe._customer_service import CustomerService as CustomerService from stripe._customer_session import CustomerSession as CustomerSession +from stripe._customer_session_service import ( + CustomerSessionService as CustomerSessionService, +) +from stripe._customer_tax_id_service import ( + CustomerTaxIdService as CustomerTaxIdService, +) from stripe._discount import Discount as Discount from stripe._dispute import Dispute as Dispute +from stripe._dispute_service import DisputeService as DisputeService from stripe._ephemeral_key import EphemeralKey as EphemeralKey +from stripe._ephemeral_key_service import ( + EphemeralKeyService as EphemeralKeyService, +) from stripe._event import Event as Event +from stripe._event_service import EventService as EventService from stripe._exchange_rate import ExchangeRate as ExchangeRate +from stripe._exchange_rate_service import ( + ExchangeRateService as ExchangeRateService, +) from stripe._file import File as File from stripe._file_link import FileLink as FileLink +from stripe._file_link_service import FileLinkService as FileLinkService +from stripe._file_service import FileService as FileService +from stripe._financial_connections_service import ( + FinancialConnectionsService as FinancialConnectionsService, +) from stripe._funding_instructions import ( FundingInstructions as FundingInstructions, ) +from stripe._identity_service import IdentityService as IdentityService from stripe._invoice import Invoice as Invoice from stripe._invoice_item import InvoiceItem as InvoiceItem +from stripe._invoice_item_service import ( + InvoiceItemService as InvoiceItemService, +) from stripe._invoice_line_item import InvoiceLineItem as InvoiceLineItem +from stripe._invoice_line_item_service import ( + InvoiceLineItemService as InvoiceLineItemService, +) +from stripe._invoice_service import InvoiceService as InvoiceService +from stripe._invoice_upcoming_lines_service import ( + InvoiceUpcomingLinesService as InvoiceUpcomingLinesService, +) +from stripe._issuing_service import IssuingService as IssuingService from stripe._line_item import LineItem as LineItem from stripe._login_link import LoginLink as LoginLink from stripe._mandate import Mandate as Mandate +from stripe._mandate_service import MandateService as MandateService from stripe._payment_intent import PaymentIntent as PaymentIntent +from stripe._payment_intent_service import ( + PaymentIntentService as PaymentIntentService, +) from stripe._payment_link import PaymentLink as PaymentLink +from stripe._payment_link_line_item_service import ( + PaymentLinkLineItemService as PaymentLinkLineItemService, +) +from stripe._payment_link_service import ( + PaymentLinkService as PaymentLinkService, +) from stripe._payment_method import PaymentMethod as PaymentMethod from stripe._payment_method_configuration import ( PaymentMethodConfiguration as PaymentMethodConfiguration, ) +from stripe._payment_method_configuration_service import ( + PaymentMethodConfigurationService as PaymentMethodConfigurationService, +) from stripe._payment_method_domain import ( PaymentMethodDomain as PaymentMethodDomain, ) +from stripe._payment_method_domain_service import ( + PaymentMethodDomainService as PaymentMethodDomainService, +) +from stripe._payment_method_service import ( + PaymentMethodService as PaymentMethodService, +) from stripe._payout import Payout as Payout +from stripe._payout_service import PayoutService as PayoutService from stripe._person import Person as Person from stripe._plan import Plan as Plan +from stripe._plan_service import PlanService as PlanService from stripe._platform_tax_fee import PlatformTaxFee as PlatformTaxFee from stripe._price import Price as Price +from stripe._price_service import PriceService as PriceService from stripe._product import Product as Product +from stripe._product_service import ProductService as ProductService from stripe._promotion_code import PromotionCode as PromotionCode +from stripe._promotion_code_service import ( + PromotionCodeService as PromotionCodeService, +) from stripe._quote import Quote as Quote +from stripe._quote_computed_upfront_line_items_service import ( + QuoteComputedUpfrontLineItemsService as QuoteComputedUpfrontLineItemsService, +) +from stripe._quote_line_item_service import ( + QuoteLineItemService as QuoteLineItemService, +) +from stripe._quote_service import QuoteService as QuoteService +from stripe._radar_service import RadarService as RadarService from stripe._refund import Refund as Refund +from stripe._refund_service import RefundService as RefundService +from stripe._reporting_service import ReportingService as ReportingService from stripe._reserve_transaction import ( ReserveTransaction as ReserveTransaction, ) from stripe._reversal import Reversal as Reversal from stripe._review import Review as Review +from stripe._review_service import ReviewService as ReviewService from stripe._setup_attempt import SetupAttempt as SetupAttempt +from stripe._setup_attempt_service import ( + SetupAttemptService as SetupAttemptService, +) from stripe._setup_intent import SetupIntent as SetupIntent +from stripe._setup_intent_service import ( + SetupIntentService as SetupIntentService, +) from stripe._shipping_rate import ShippingRate as ShippingRate +from stripe._shipping_rate_service import ( + ShippingRateService as ShippingRateService, +) +from stripe._sigma_service import SigmaService as SigmaService from stripe._source import Source as Source from stripe._source_mandate_notification import ( SourceMandateNotification as SourceMandateNotification, ) +from stripe._source_service import SourceService as SourceService from stripe._source_transaction import SourceTransaction as SourceTransaction +from stripe._source_transaction_service import ( + SourceTransactionService as SourceTransactionService, +) from stripe._subscription import Subscription as Subscription from stripe._subscription_item import SubscriptionItem as SubscriptionItem +from stripe._subscription_item_service import ( + SubscriptionItemService as SubscriptionItemService, +) +from stripe._subscription_item_usage_record_service import ( + SubscriptionItemUsageRecordService as SubscriptionItemUsageRecordService, +) +from stripe._subscription_item_usage_record_summary_service import ( + SubscriptionItemUsageRecordSummaryService as SubscriptionItemUsageRecordSummaryService, +) from stripe._subscription_schedule import ( SubscriptionSchedule as SubscriptionSchedule, ) +from stripe._subscription_schedule_service import ( + SubscriptionScheduleService as SubscriptionScheduleService, +) +from stripe._subscription_service import ( + SubscriptionService as SubscriptionService, +) from stripe._tax_code import TaxCode as TaxCode +from stripe._tax_code_service import TaxCodeService as TaxCodeService from stripe._tax_deducted_at_source import ( TaxDeductedAtSource as TaxDeductedAtSource, ) from stripe._tax_id import TaxId as TaxId from stripe._tax_rate import TaxRate as TaxRate +from stripe._tax_rate_service import TaxRateService as TaxRateService +from stripe._tax_service import TaxService as TaxService +from stripe._terminal_service import TerminalService as TerminalService +from stripe._test_helpers_service import ( + TestHelpersService as TestHelpersService, +) from stripe._token import Token as Token +from stripe._token_service import TokenService as TokenService from stripe._topup import Topup as Topup +from stripe._topup_service import TopupService as TopupService from stripe._transfer import Transfer as Transfer +from stripe._transfer_reversal_service import ( + TransferReversalService as TransferReversalService, +) +from stripe._transfer_service import TransferService as TransferService +from stripe._treasury_service import TreasuryService as TreasuryService from stripe._usage_record import UsageRecord as UsageRecord from stripe._usage_record_summary import ( UsageRecordSummary as UsageRecordSummary, ) from stripe._webhook_endpoint import WebhookEndpoint as WebhookEndpoint +from stripe._webhook_endpoint_service import ( + WebhookEndpointService as WebhookEndpointService, +) # The end of the section generated from our OpenAPI spec diff --git a/stripe/_account.py b/stripe/_account.py index 649854e47..829ea20fc 100644 --- a/stripe/_account.py +++ b/stripe/_account.py @@ -3630,16 +3630,7 @@ class RetrievePersonParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Account": + def create(cls, **params: Unpack["Account.CreateParams"]) -> "Account": """ With [Connect](https://stripe.com/docs/connect), you can create Stripe accounts for your users. To do this, you'll first need to [register your platform](https://dashboard.stripe.com/account/applications/settings). @@ -3653,10 +3644,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -3722,13 +3709,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Account.ListParams"] ) -> ListObject["Account"]: """ Returns a list of accounts connected to your platform via [Connect](https://stripe.com/docs/connect). If you're not a platform, the list is empty. @@ -3736,9 +3717,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -3752,14 +3730,7 @@ def list( @classmethod def _cls_persons( - cls, - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.PersonsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, account: str, **params: Unpack["Account.PersonsParams"] ) -> ListObject["Person"]: """ Returns a list of people associated with the account's legal entity. The people are returned sorted by creation date, with the most recent people appearing first. @@ -3771,9 +3742,6 @@ def _cls_persons( "/v1/accounts/{account}/persons".format( account=_util.sanitize_id(account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -3781,13 +3749,7 @@ def _cls_persons( @overload @staticmethod def persons( - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.PersonsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + account: str, **params: Unpack["Account.PersonsParams"] ) -> ListObject["Person"]: """ Returns a list of people associated with the account's legal entity. The people are returned sorted by creation date, with the most recent people appearing first. @@ -3796,11 +3758,7 @@ def persons( @overload def persons( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.PersonsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Account.PersonsParams"] ) -> ListObject["Person"]: """ Returns a list of people associated with the account's legal entity. The people are returned sorted by creation date, with the most recent people appearing first. @@ -3809,11 +3767,7 @@ def persons( @class_method_variant("_cls_persons") def persons( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.PersonsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Account.PersonsParams"] ) -> ListObject["Person"]: """ Returns a list of people associated with the account's legal entity. The people are returned sorted by creation date, with the most recent people appearing first. @@ -3825,21 +3779,13 @@ def persons( # pyright: ignore[reportGeneralTypeIssues] "/v1/accounts/{account}/persons".format( account=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_reject( - cls, - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.RejectParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, account: str, **params: Unpack["Account.RejectParams"] ) -> "Account": """ With [Connect](https://stripe.com/docs/connect), you may flag accounts as suspicious. @@ -3853,9 +3799,6 @@ def _cls_reject( "/v1/accounts/{account}/reject".format( account=_util.sanitize_id(account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -3863,13 +3806,7 @@ def _cls_reject( @overload @staticmethod def reject( - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.RejectParams" - ] # pyright: ignore[reportGeneralTypeIssues] + account: str, **params: Unpack["Account.RejectParams"] ) -> "Account": """ With [Connect](https://stripe.com/docs/connect), you may flag accounts as suspicious. @@ -3879,13 +3816,7 @@ def reject( ... @overload - def reject( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.RejectParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Account": + def reject(self, **params: Unpack["Account.RejectParams"]) -> "Account": """ With [Connect](https://stripe.com/docs/connect), you may flag accounts as suspicious. @@ -3895,11 +3826,7 @@ def reject( @class_method_variant("_cls_reject") def reject( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.RejectParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Account.RejectParams"] ) -> "Account": """ With [Connect](https://stripe.com/docs/connect), you may flag accounts as suspicious. @@ -3913,7 +3840,6 @@ def reject( # pyright: ignore[reportGeneralTypeIssues] "/v1/accounts/{account}/reject".format( account=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -3922,8 +3848,8 @@ def reject( # pyright: ignore[reportGeneralTypeIssues] # capabilities property which is a hash and not the sub-list of capabilities. @classmethod - def retrieve(cls, id=None, api_key=None, **params) -> "Account": - instance = cls(id, api_key, **params) + def retrieve(cls, id=None, **params) -> "Account": + instance = cls(id, **params) instance.refresh() return instance @@ -3962,12 +3888,7 @@ def retrieve_capability( cls, account: str, capability: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.RetrieveCapabilityParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Account.RetrieveCapabilityParams"] ) -> "Capability": """ Retrieves information about the specified Account Capability. @@ -3980,9 +3901,6 @@ def retrieve_capability( account=_util.sanitize_id(account), capability=_util.sanitize_id(capability), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -3992,12 +3910,7 @@ def modify_capability( cls, account: str, capability: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.ModifyCapabilityParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Account.ModifyCapabilityParams"] ) -> "Capability": """ Updates an existing Account Capability. Request or remove a capability by updating its requested parameter. @@ -4010,23 +3923,13 @@ def modify_capability( account=_util.sanitize_id(account), capability=_util.sanitize_id(capability), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def list_capabilities( - cls, - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.ListCapabilitiesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, account: str, **params: Unpack["Account.ListCapabilitiesParams"] ) -> ListObject["Capability"]: """ Returns a list of capabilities associated with the account. The capabilities are returned sorted by creation date, with the most recent capability appearing first. @@ -4038,9 +3941,6 @@ def list_capabilities( "/v1/accounts/{account}/capabilities".format( account=_util.sanitize_id(account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -4049,12 +3949,7 @@ def list_capabilities( def create_external_account( cls, account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.CreateExternalAccountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Account.CreateExternalAccountParams"] ) -> Union["BankAccount", "Card"]: """ Create an external account for a given account. @@ -4066,9 +3961,6 @@ def create_external_account( "/v1/accounts/{account}/external_accounts".format( account=_util.sanitize_id(account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -4078,12 +3970,7 @@ def retrieve_external_account( cls, account: str, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.RetrieveExternalAccountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Account.RetrieveExternalAccountParams"] ) -> Union["BankAccount", "Card"]: """ Retrieve a specified external account for a given account. @@ -4096,9 +3983,6 @@ def retrieve_external_account( account=_util.sanitize_id(account), id=_util.sanitize_id(id), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -4108,12 +3992,7 @@ def modify_external_account( cls, account: str, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.ModifyExternalAccountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Account.ModifyExternalAccountParams"] ) -> Union["BankAccount", "Card"]: """ Updates the metadata, account holder name, account holder type of a bank account belonging to a [Custom account](https://stripe.com/docs/connect/custom-accounts), and optionally sets it as the default for its currency. Other bank account details are not editable by design. @@ -4128,9 +4007,6 @@ def modify_external_account( account=_util.sanitize_id(account), id=_util.sanitize_id(id), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -4140,12 +4016,7 @@ def delete_external_account( cls, account: str, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.DeleteExternalAccountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Account.DeleteExternalAccountParams"] ) -> Union["BankAccount", "Card"]: """ Delete a specified external account for a given account. @@ -4158,9 +4029,6 @@ def delete_external_account( account=_util.sanitize_id(account), id=_util.sanitize_id(id), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -4169,12 +4037,7 @@ def delete_external_account( def list_external_accounts( cls, account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.ListExternalAccountsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Account.ListExternalAccountsParams"] ) -> ListObject[Union["BankAccount", "Card"]]: """ List external accounts for an account. @@ -4186,23 +4049,13 @@ def list_external_accounts( "/v1/accounts/{account}/external_accounts".format( account=_util.sanitize_id(account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def create_login_link( - cls, - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.CreateLoginLinkParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, account: str, **params: Unpack["Account.CreateLoginLinkParams"] ) -> "LoginLink": """ Creates a single-use login link for an Express account to access their Stripe dashboard. @@ -4216,23 +4069,13 @@ def create_login_link( "/v1/accounts/{account}/login_links".format( account=_util.sanitize_id(account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def create_person( - cls, - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.CreatePersonParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, account: str, **params: Unpack["Account.CreatePersonParams"] ) -> "Person": """ Creates a new person. @@ -4244,9 +4087,6 @@ def create_person( "/v1/accounts/{account}/persons".format( account=_util.sanitize_id(account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -4256,12 +4096,7 @@ def retrieve_person( cls, account: str, person: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.RetrievePersonParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Account.RetrievePersonParams"] ) -> "Person": """ Retrieves an existing person. @@ -4274,9 +4109,6 @@ def retrieve_person( account=_util.sanitize_id(account), person=_util.sanitize_id(person), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -4286,12 +4118,7 @@ def modify_person( cls, account: str, person: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.ModifyPersonParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Account.ModifyPersonParams"] ) -> "Person": """ Updates an existing person. @@ -4304,9 +4131,6 @@ def modify_person( account=_util.sanitize_id(account), person=_util.sanitize_id(person), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -4316,12 +4140,7 @@ def delete_person( cls, account: str, person: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.DeletePersonParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Account.DeletePersonParams"] ) -> "Person": """ Deletes an existing person's relationship to the account's legal entity. Any person with a relationship for an account can be deleted through the API, except if the person is the account_opener. If your integration is using the executive parameter, you cannot delete the only verified executive on file. @@ -4334,23 +4153,13 @@ def delete_person( account=_util.sanitize_id(account), person=_util.sanitize_id(person), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def list_persons( - cls, - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.ListPersonsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, account: str, **params: Unpack["Account.ListPersonsParams"] ) -> ListObject["Person"]: """ Returns a list of people associated with the account's legal entity. The people are returned sorted by creation date, with the most recent people appearing first. @@ -4362,9 +4171,6 @@ def list_persons( "/v1/accounts/{account}/persons".format( account=_util.sanitize_id(account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) diff --git a/stripe/_account_capability_service.py b/stripe/_account_capability_service.py new file mode 100644 index 000000000..7a6876f22 --- /dev/null +++ b/stripe/_account_capability_service.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._capability import Capability +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class AccountCapabilityService(StripeService): + class ListParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + requested: NotRequired["bool"] + """ + To request a new capability for an account, pass true. There can be a delay before the requested capability becomes active. If the capability has any activation requirements, the response includes them in the `requirements` arrays. + + If a capability isn't permanent, you can remove it from the account by passing false. Most capabilities are permanent after they've been requested. Attempting to remove a permanent capability returns an error. + """ + + def list( + self, + account: str, + params: "AccountCapabilityService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Capability]: + """ + Returns a list of capabilities associated with the account. The capabilities are returned sorted by creation date, with the most recent capability appearing first. + """ + return cast( + ListObject[Capability], + self._requestor.request( + "get", + "/v1/accounts/{account}/capabilities".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + account: str, + capability: str, + params: "AccountCapabilityService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Capability: + """ + Retrieves information about the specified Account Capability. + """ + return cast( + Capability, + self._requestor.request( + "get", + "/v1/accounts/{account}/capabilities/{capability}".format( + account=_util.sanitize_id(account), + capability=_util.sanitize_id(capability), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + account: str, + capability: str, + params: "AccountCapabilityService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Capability: + """ + Updates an existing Account Capability. Request or remove a capability by updating its requested parameter. + """ + return cast( + Capability, + self._requestor.request( + "post", + "/v1/accounts/{account}/capabilities/{capability}".format( + account=_util.sanitize_id(account), + capability=_util.sanitize_id(capability), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_account_external_account_service.py b/stripe/_account_external_account_service.py new file mode 100644 index 000000000..f34b7046f --- /dev/null +++ b/stripe/_account_external_account_service.py @@ -0,0 +1,326 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._bank_account import BankAccount +from stripe._card import Card +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, Union, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class AccountExternalAccountService(StripeService): + class CreateParams(TypedDict): + default_for_currency: NotRequired["bool"] + """ + When set to true, or if this is the first external account added in this currency, this account becomes the default external account for its currency. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + external_account: Union[ + str, + "AccountExternalAccountService.CreateParamsCard", + "AccountExternalAccountService.CreateParamsBankAccount", + "AccountExternalAccountService.CreateParamsCardToken", + ] + """ + Please refer to full [documentation](https://stripe.com/docs/api) instead. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class CreateParamsBankAccount(TypedDict): + object: Literal["bank_account"] + account_holder_name: NotRequired["str"] + """ + The name of the person or business that owns the bank account.This field is required when attaching the bank account to a `Customer` object. + """ + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + The type of entity that holds the account. It can be `company` or `individual`. This field is required when attaching the bank account to a `Customer` object. + """ + account_number: str + """ + The account number for the bank account, in string form. Must be a checking account. + """ + country: str + """ + The country in which the bank account is located. + """ + currency: NotRequired["str"] + """ + The currency the bank account is in. This must be a country/currency pairing that [Stripe supports.](docs/payouts) + """ + routing_number: NotRequired["str"] + """ + The routing number, sort code, or other country-appropriateinstitution number for the bank account. For US bank accounts, this is required and should bethe ACH routing number, not the wire routing number. If you are providing an IBAN for`account_number`, this field is not required. + """ + + class CreateParamsCard(TypedDict): + object: Literal["card"] + address_city: NotRequired["str"] + address_country: NotRequired["str"] + address_line1: NotRequired["str"] + address_line2: NotRequired["str"] + address_state: NotRequired["str"] + address_zip: NotRequired["str"] + currency: NotRequired["str"] + cvc: NotRequired["str"] + exp_month: int + exp_year: int + name: NotRequired["str"] + number: str + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + """ + + class CreateParamsCardToken(TypedDict): + object: Literal["card"] + currency: NotRequired["str"] + token: str + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + object: NotRequired["Literal['bank_account', 'card']"] + """ + Filter external accounts according to a particular object type. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + account_holder_name: NotRequired["str"] + """ + The name of the person or business that owns the bank account. + """ + account_holder_type: NotRequired[ + "Literal['']|Literal['company', 'individual']" + ] + """ + The type of entity that holds the account. This can be either `individual` or `company`. + """ + account_type: NotRequired[ + "Literal['checking', 'futsu', 'savings', 'toza']" + ] + """ + The bank account type. This can only be `checking` or `savings` in most countries. In Japan, this can only be `futsu` or `toza`. + """ + address_city: NotRequired["str"] + """ + City/District/Suburb/Town/Village. + """ + address_country: NotRequired["str"] + """ + Billing address country, if provided when creating card. + """ + address_line1: NotRequired["str"] + """ + Address line 1 (Street address/PO Box/Company name). + """ + address_line2: NotRequired["str"] + """ + Address line 2 (Apartment/Suite/Unit/Building). + """ + address_state: NotRequired["str"] + """ + State/County/Province/Region. + """ + address_zip: NotRequired["str"] + """ + ZIP or postal code. + """ + default_for_currency: NotRequired["bool"] + """ + When set to true, this becomes the default external account for its currency. + """ + documents: NotRequired[ + "AccountExternalAccountService.UpdateParamsDocuments" + ] + """ + Documents that may be submitted to satisfy various informational requests. + """ + exp_month: NotRequired["str"] + """ + Two digit number representing the card's expiration month. + """ + exp_year: NotRequired["str"] + """ + Four digit number representing the card's expiration year. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: NotRequired["str"] + """ + Cardholder name. + """ + + class UpdateParamsDocuments(TypedDict): + bank_account_ownership_verification: NotRequired[ + "AccountExternalAccountService.UpdateParamsDocumentsBankAccountOwnershipVerification" + ] + """ + One or more documents that support the [Bank account ownership verification](https://support.stripe.com/questions/bank-account-ownership-verification) requirement. Must be a document associated with the bank account that displays the last 4 digits of the account number, either a statement or a voided check. + """ + + class UpdateParamsDocumentsBankAccountOwnershipVerification(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + def delete( + self, + account: str, + id: str, + params: "AccountExternalAccountService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> Union[BankAccount, Card]: + """ + Delete a specified external account for a given account. + """ + return cast( + Union[BankAccount, Card], + self._requestor.request( + "delete", + "/v1/accounts/{account}/external_accounts/{id}".format( + account=_util.sanitize_id(account), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + account: str, + id: str, + params: "AccountExternalAccountService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Union[BankAccount, Card]: + """ + Retrieve a specified external account for a given account. + """ + return cast( + Union[BankAccount, Card], + self._requestor.request( + "get", + "/v1/accounts/{account}/external_accounts/{id}".format( + account=_util.sanitize_id(account), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + account: str, + id: str, + params: "AccountExternalAccountService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Union[BankAccount, Card]: + """ + Updates the metadata, account holder name, account holder type of a bank account belonging to a [Custom account](https://stripe.com/docs/connect/custom-accounts), and optionally sets it as the default for its currency. Other bank account details are not editable by design. + + You can re-enable a disabled bank account by performing an update call without providing any arguments or changes. + """ + return cast( + Union[BankAccount, Card], + self._requestor.request( + "post", + "/v1/accounts/{account}/external_accounts/{id}".format( + account=_util.sanitize_id(account), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + account: str, + params: "AccountExternalAccountService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Union[BankAccount, Card]]: + """ + List external accounts for an account. + """ + return cast( + ListObject[Union[BankAccount, Card]], + self._requestor.request( + "get", + "/v1/accounts/{account}/external_accounts".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + account: str, + params: "AccountExternalAccountService.CreateParams", + options: RequestOptions = {}, + ) -> Union[BankAccount, Card]: + """ + Create an external account for a given account. + """ + return cast( + Union[BankAccount, Card], + self._requestor.request( + "post", + "/v1/accounts/{account}/external_accounts".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_account_link.py b/stripe/_account_link.py index 4b3783a2f..ca958de5e 100644 --- a/stripe/_account_link.py +++ b/stripe/_account_link.py @@ -2,7 +2,7 @@ # File generated from our OpenAPI spec from stripe._createable_api_resource import CreateableAPIResource from stripe._request_options import RequestOptions -from typing import ClassVar, List, Optional, cast +from typing import ClassVar, List, cast from typing_extensions import Literal, NotRequired, TypedDict, Unpack @@ -77,14 +77,7 @@ class CreateParamsCollectionOptions(TypedDict): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "AccountLink.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["AccountLink.CreateParams"] ) -> "AccountLink": """ Creates an AccountLink object that includes a single-use Stripe URL that the platform can redirect their user to in order to take them through the Connect Onboarding flow. @@ -94,10 +87,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) diff --git a/stripe/_account_link_service.py b/stripe/_account_link_service.py new file mode 100644 index 000000000..2e007050a --- /dev/null +++ b/stripe/_account_link_service.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._account_link import AccountLink +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class AccountLinkService(StripeService): + class CreateParams(TypedDict): + account: str + """ + The identifier of the account to create an account link for. + """ + collect: NotRequired["Literal['currently_due', 'eventually_due']"] + """ + The collect parameter is deprecated. Use `collection_options` instead. + """ + collection_options: NotRequired[ + "AccountLinkService.CreateParamsCollectionOptions" + ] + """ + Specifies the requirements that Stripe collects from connected accounts in the Connect Onboarding flow. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + refresh_url: NotRequired["str"] + """ + The URL the user will be redirected to if the account link is expired, has been previously-visited, or is otherwise invalid. The URL you specify should attempt to generate a new account link with the same parameters used to create the original account link, then redirect the user to the new account link's URL so they can continue with Connect Onboarding. If a new account link cannot be generated or the redirect fails you should display a useful error to the user. + """ + return_url: NotRequired["str"] + """ + The URL that the user will be redirected to upon leaving or completing the linked flow. + """ + type: Literal["account_onboarding", "account_update"] + """ + The type of account link the user is requesting. Possible values are `account_onboarding` or `account_update`. + """ + + class CreateParamsCollectionOptions(TypedDict): + fields: Literal["currently_due", "eventually_due"] + """ + Specifies whether the platform collects only currently_due requirements (`currently_due`) or both currently_due and eventually_due requirements (`eventually_due`). If you don't specify `collection_options`, the default value is `currently_due`. + """ + future_requirements: NotRequired["Literal['include', 'omit']"] + """ + Specifies whether the platform collects future_requirements in addition to requirements in Connect Onboarding. The default value is `omit`. + """ + + def create( + self, + params: "AccountLinkService.CreateParams", + options: RequestOptions = {}, + ) -> AccountLink: + """ + Creates an AccountLink object that includes a single-use Stripe URL that the platform can redirect their user to in order to take them through the Connect Onboarding flow. + """ + return cast( + AccountLink, + self._requestor.request( + "post", + "/v1/account_links", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_account_login_link_service.py b/stripe/_account_login_link_service.py new file mode 100644 index 000000000..7aeb58947 --- /dev/null +++ b/stripe/_account_login_link_service.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._login_link import LoginLink +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class AccountLoginLinkService(StripeService): + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def create( + self, + account: str, + params: "AccountLoginLinkService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> LoginLink: + """ + Creates a single-use login link for an Express account to access their Stripe dashboard. + + You may only create login links for [Express accounts](https://stripe.com/docs/connect/express-accounts) connected to your platform. + """ + return cast( + LoginLink, + self._requestor.request( + "post", + "/v1/accounts/{account}/login_links".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_account_person_service.py b/stripe/_account_person_service.py new file mode 100644 index 000000000..c87e9e6f9 --- /dev/null +++ b/stripe/_account_person_service.py @@ -0,0 +1,935 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._person import Person +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class AccountPersonService(StripeService): + class CreateParams(TypedDict): + additional_tos_acceptances: NotRequired[ + "AccountPersonService.CreateParamsAdditionalTosAcceptances" + ] + """ + Details on the legal guardian's acceptance of the required Stripe agreements. + """ + address: NotRequired["AccountPersonService.CreateParamsAddress"] + """ + The person's address. + """ + address_kana: NotRequired[ + "AccountPersonService.CreateParamsAddressKana" + ] + """ + The Kana variation of the person's address (Japan only). + """ + address_kanji: NotRequired[ + "AccountPersonService.CreateParamsAddressKanji" + ] + """ + The Kanji variation of the person's address (Japan only). + """ + dob: NotRequired["Literal['']|AccountPersonService.CreateParamsDob"] + """ + The person's date of birth. + """ + documents: NotRequired["AccountPersonService.CreateParamsDocuments"] + """ + Documents that may be submitted to satisfy various informational requests. + """ + email: NotRequired["str"] + """ + The person's email address. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + first_name: NotRequired["str"] + """ + The person's first name. + """ + first_name_kana: NotRequired["str"] + """ + The Kana variation of the person's first name (Japan only). + """ + first_name_kanji: NotRequired["str"] + """ + The Kanji variation of the person's first name (Japan only). + """ + full_name_aliases: NotRequired["Literal['']|List[str]"] + """ + A list of alternate names or aliases that the person is known by. + """ + gender: NotRequired["str"] + """ + The person's gender (International regulations require either "male" or "female"). + """ + id_number: NotRequired["str"] + """ + The person's ID number, as appropriate for their country. For example, a social security number in the U.S., social insurance number in Canada, etc. Instead of the number itself, you can also provide a [PII token provided by Stripe.js](https://stripe.com/docs/js/tokens/create_token?type=pii). + """ + id_number_secondary: NotRequired["str"] + """ + The person's secondary ID number, as appropriate for their country, will be used for enhanced verification checks. In Thailand, this would be the laser code found on the back of an ID card. Instead of the number itself, you can also provide a [PII token provided by Stripe.js](https://stripe.com/docs/js/tokens/create_token?type=pii). + """ + last_name: NotRequired["str"] + """ + The person's last name. + """ + last_name_kana: NotRequired["str"] + """ + The Kana variation of the person's last name (Japan only). + """ + last_name_kanji: NotRequired["str"] + """ + The Kanji variation of the person's last name (Japan only). + """ + maiden_name: NotRequired["str"] + """ + The person's maiden name. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + nationality: NotRequired["str"] + """ + The country where the person is a national. Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)), or "XX" if unavailable. + """ + person_token: NotRequired["str"] + """ + A [person token](https://stripe.com/docs/connect/account-tokens), used to securely provide details to the person. + """ + phone: NotRequired["str"] + """ + The person's phone number. + """ + political_exposure: NotRequired["str"] + """ + Indicates if the person or any of their representatives, family members, or other closely related persons, declares that they hold or have held an important public job or function, in any jurisdiction. + """ + registered_address: NotRequired[ + "AccountPersonService.CreateParamsRegisteredAddress" + ] + """ + The person's registered address. + """ + relationship: NotRequired[ + "AccountPersonService.CreateParamsRelationship" + ] + """ + The relationship that this person has with the account's legal entity. + """ + ssn_last_4: NotRequired["str"] + """ + The last four digits of the person's Social Security number (U.S. only). + """ + verification: NotRequired[ + "AccountPersonService.CreateParamsVerification" + ] + """ + The person's verification status. + """ + + class CreateParamsAdditionalTosAcceptances(TypedDict): + account: NotRequired[ + "AccountPersonService.CreateParamsAdditionalTosAcceptancesAccount" + ] + """ + Details on the legal guardian's acceptance of the main Stripe service agreement. + """ + + class CreateParamsAdditionalTosAcceptancesAccount(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the account representative accepted the service agreement. + """ + ip: NotRequired["str"] + """ + The IP address from which the account representative accepted the service agreement. + """ + user_agent: NotRequired["Literal['']|str"] + """ + The user agent of the browser from which the account representative accepted the service agreement. + """ + + class CreateParamsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsAddressKana(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class CreateParamsAddressKanji(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class CreateParamsDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class CreateParamsDocuments(TypedDict): + company_authorization: NotRequired[ + "AccountPersonService.CreateParamsDocumentsCompanyAuthorization" + ] + """ + One or more documents that demonstrate proof that this person is authorized to represent the company. + """ + passport: NotRequired[ + "AccountPersonService.CreateParamsDocumentsPassport" + ] + """ + One or more documents showing the person's passport page with photo and personal data. + """ + visa: NotRequired["AccountPersonService.CreateParamsDocumentsVisa"] + """ + One or more documents showing the person's visa required for living in the country where they are residing. + """ + + class CreateParamsDocumentsCompanyAuthorization(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class CreateParamsDocumentsPassport(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class CreateParamsDocumentsVisa(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class CreateParamsRegisteredAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsRelationship(TypedDict): + director: NotRequired["bool"] + """ + Whether the person is a director of the account's legal entity. Directors are typically members of the governing board of the company, or responsible for ensuring the company meets its regulatory obligations. + """ + executive: NotRequired["bool"] + """ + Whether the person has significant responsibility to control, manage, or direct the organization. + """ + legal_guardian: NotRequired["bool"] + """ + Whether the person is the legal guardian of the account's representative. + """ + owner: NotRequired["bool"] + """ + Whether the person is an owner of the account's legal entity. + """ + percent_ownership: NotRequired["Literal['']|float"] + """ + The percent owned by the person of the account's legal entity. + """ + representative: NotRequired["bool"] + """ + Whether the person is authorized as the primary representative of the account. This is the person nominated by the business to provide information about themselves, and general information about the account. There can only be one representative at any given time. At the time the account is created, this person should be set to the person responsible for opening the account. + """ + title: NotRequired["str"] + """ + The person's title (e.g., CEO, Support Engineer). + """ + + class CreateParamsVerification(TypedDict): + additional_document: NotRequired[ + "AccountPersonService.CreateParamsVerificationAdditionalDocument" + ] + """ + A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. + """ + document: NotRequired[ + "AccountPersonService.CreateParamsVerificationDocument" + ] + """ + An identifying document, either a passport or local ID card. + """ + + class CreateParamsVerificationAdditionalDocument(TypedDict): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class CreateParamsVerificationDocument(TypedDict): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + relationship: NotRequired[ + "AccountPersonService.ListParamsRelationship" + ] + """ + Filters on the list of people returned based on the person's relationship to the account's company. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsRelationship(TypedDict): + director: NotRequired["bool"] + """ + A filter on the list of people returned based on whether these people are directors of the account's company. + """ + executive: NotRequired["bool"] + """ + A filter on the list of people returned based on whether these people are executives of the account's company. + """ + legal_guardian: NotRequired["bool"] + """ + A filter on the list of people returned based on whether these people are legal guardians of the account's representative. + """ + owner: NotRequired["bool"] + """ + A filter on the list of people returned based on whether these people are owners of the account's company. + """ + representative: NotRequired["bool"] + """ + A filter on the list of people returned based on whether these people are the representative of the account's company. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + additional_tos_acceptances: NotRequired[ + "AccountPersonService.UpdateParamsAdditionalTosAcceptances" + ] + """ + Details on the legal guardian's acceptance of the required Stripe agreements. + """ + address: NotRequired["AccountPersonService.UpdateParamsAddress"] + """ + The person's address. + """ + address_kana: NotRequired[ + "AccountPersonService.UpdateParamsAddressKana" + ] + """ + The Kana variation of the person's address (Japan only). + """ + address_kanji: NotRequired[ + "AccountPersonService.UpdateParamsAddressKanji" + ] + """ + The Kanji variation of the person's address (Japan only). + """ + dob: NotRequired["Literal['']|AccountPersonService.UpdateParamsDob"] + """ + The person's date of birth. + """ + documents: NotRequired["AccountPersonService.UpdateParamsDocuments"] + """ + Documents that may be submitted to satisfy various informational requests. + """ + email: NotRequired["str"] + """ + The person's email address. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + first_name: NotRequired["str"] + """ + The person's first name. + """ + first_name_kana: NotRequired["str"] + """ + The Kana variation of the person's first name (Japan only). + """ + first_name_kanji: NotRequired["str"] + """ + The Kanji variation of the person's first name (Japan only). + """ + full_name_aliases: NotRequired["Literal['']|List[str]"] + """ + A list of alternate names or aliases that the person is known by. + """ + gender: NotRequired["str"] + """ + The person's gender (International regulations require either "male" or "female"). + """ + id_number: NotRequired["str"] + """ + The person's ID number, as appropriate for their country. For example, a social security number in the U.S., social insurance number in Canada, etc. Instead of the number itself, you can also provide a [PII token provided by Stripe.js](https://stripe.com/docs/js/tokens/create_token?type=pii). + """ + id_number_secondary: NotRequired["str"] + """ + The person's secondary ID number, as appropriate for their country, will be used for enhanced verification checks. In Thailand, this would be the laser code found on the back of an ID card. Instead of the number itself, you can also provide a [PII token provided by Stripe.js](https://stripe.com/docs/js/tokens/create_token?type=pii). + """ + last_name: NotRequired["str"] + """ + The person's last name. + """ + last_name_kana: NotRequired["str"] + """ + The Kana variation of the person's last name (Japan only). + """ + last_name_kanji: NotRequired["str"] + """ + The Kanji variation of the person's last name (Japan only). + """ + maiden_name: NotRequired["str"] + """ + The person's maiden name. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + nationality: NotRequired["str"] + """ + The country where the person is a national. Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)), or "XX" if unavailable. + """ + person_token: NotRequired["str"] + """ + A [person token](https://stripe.com/docs/connect/account-tokens), used to securely provide details to the person. + """ + phone: NotRequired["str"] + """ + The person's phone number. + """ + political_exposure: NotRequired["str"] + """ + Indicates if the person or any of their representatives, family members, or other closely related persons, declares that they hold or have held an important public job or function, in any jurisdiction. + """ + registered_address: NotRequired[ + "AccountPersonService.UpdateParamsRegisteredAddress" + ] + """ + The person's registered address. + """ + relationship: NotRequired[ + "AccountPersonService.UpdateParamsRelationship" + ] + """ + The relationship that this person has with the account's legal entity. + """ + ssn_last_4: NotRequired["str"] + """ + The last four digits of the person's Social Security number (U.S. only). + """ + verification: NotRequired[ + "AccountPersonService.UpdateParamsVerification" + ] + """ + The person's verification status. + """ + + class UpdateParamsAdditionalTosAcceptances(TypedDict): + account: NotRequired[ + "AccountPersonService.UpdateParamsAdditionalTosAcceptancesAccount" + ] + """ + Details on the legal guardian's acceptance of the main Stripe service agreement. + """ + + class UpdateParamsAdditionalTosAcceptancesAccount(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the account representative accepted the service agreement. + """ + ip: NotRequired["str"] + """ + The IP address from which the account representative accepted the service agreement. + """ + user_agent: NotRequired["Literal['']|str"] + """ + The user agent of the browser from which the account representative accepted the service agreement. + """ + + class UpdateParamsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsAddressKana(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class UpdateParamsAddressKanji(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class UpdateParamsDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class UpdateParamsDocuments(TypedDict): + company_authorization: NotRequired[ + "AccountPersonService.UpdateParamsDocumentsCompanyAuthorization" + ] + """ + One or more documents that demonstrate proof that this person is authorized to represent the company. + """ + passport: NotRequired[ + "AccountPersonService.UpdateParamsDocumentsPassport" + ] + """ + One or more documents showing the person's passport page with photo and personal data. + """ + visa: NotRequired["AccountPersonService.UpdateParamsDocumentsVisa"] + """ + One or more documents showing the person's visa required for living in the country where they are residing. + """ + + class UpdateParamsDocumentsCompanyAuthorization(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class UpdateParamsDocumentsPassport(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class UpdateParamsDocumentsVisa(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class UpdateParamsRegisteredAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsRelationship(TypedDict): + director: NotRequired["bool"] + """ + Whether the person is a director of the account's legal entity. Directors are typically members of the governing board of the company, or responsible for ensuring the company meets its regulatory obligations. + """ + executive: NotRequired["bool"] + """ + Whether the person has significant responsibility to control, manage, or direct the organization. + """ + legal_guardian: NotRequired["bool"] + """ + Whether the person is the legal guardian of the account's representative. + """ + owner: NotRequired["bool"] + """ + Whether the person is an owner of the account's legal entity. + """ + percent_ownership: NotRequired["Literal['']|float"] + """ + The percent owned by the person of the account's legal entity. + """ + representative: NotRequired["bool"] + """ + Whether the person is authorized as the primary representative of the account. This is the person nominated by the business to provide information about themselves, and general information about the account. There can only be one representative at any given time. At the time the account is created, this person should be set to the person responsible for opening the account. + """ + title: NotRequired["str"] + """ + The person's title (e.g., CEO, Support Engineer). + """ + + class UpdateParamsVerification(TypedDict): + additional_document: NotRequired[ + "AccountPersonService.UpdateParamsVerificationAdditionalDocument" + ] + """ + A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. + """ + document: NotRequired[ + "AccountPersonService.UpdateParamsVerificationDocument" + ] + """ + An identifying document, either a passport or local ID card. + """ + + class UpdateParamsVerificationAdditionalDocument(TypedDict): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class UpdateParamsVerificationDocument(TypedDict): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + def delete( + self, + account: str, + person: str, + params: "AccountPersonService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> Person: + """ + Deletes an existing person's relationship to the account's legal entity. Any person with a relationship for an account can be deleted through the API, except if the person is the account_opener. If your integration is using the executive parameter, you cannot delete the only verified executive on file. + """ + return cast( + Person, + self._requestor.request( + "delete", + "/v1/accounts/{account}/persons/{person}".format( + account=_util.sanitize_id(account), + person=_util.sanitize_id(person), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + account: str, + person: str, + params: "AccountPersonService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Person: + """ + Retrieves an existing person. + """ + return cast( + Person, + self._requestor.request( + "get", + "/v1/accounts/{account}/persons/{person}".format( + account=_util.sanitize_id(account), + person=_util.sanitize_id(person), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + account: str, + person: str, + params: "AccountPersonService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Person: + """ + Updates an existing person. + """ + return cast( + Person, + self._requestor.request( + "post", + "/v1/accounts/{account}/persons/{person}".format( + account=_util.sanitize_id(account), + person=_util.sanitize_id(person), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + account: str, + params: "AccountPersonService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Person]: + """ + Returns a list of people associated with the account's legal entity. The people are returned sorted by creation date, with the most recent people appearing first. + """ + return cast( + ListObject[Person], + self._requestor.request( + "get", + "/v1/accounts/{account}/persons".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + account: str, + params: "AccountPersonService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Person: + """ + Creates a new person. + """ + return cast( + Person, + self._requestor.request( + "post", + "/v1/accounts/{account}/persons".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_account_service.py b/stripe/_account_service.py new file mode 100644 index 000000000..898f5ba2f --- /dev/null +++ b/stripe/_account_service.py @@ -0,0 +1,3113 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._account import Account +from stripe._account_capability_service import AccountCapabilityService +from stripe._account_external_account_service import ( + AccountExternalAccountService, +) +from stripe._account_login_link_service import AccountLoginLinkService +from stripe._account_person_service import AccountPersonService +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class AccountService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.capabilities = AccountCapabilityService(self._requestor) + self.external_accounts = AccountExternalAccountService(self._requestor) + self.login_links = AccountLoginLinkService(self._requestor) + self.persons = AccountPersonService(self._requestor) + + class CreateParams(TypedDict): + account_token: NotRequired["str"] + """ + An [account token](https://stripe.com/docs/api#create_account_token), used to securely provide details to the account. + """ + business_profile: NotRequired[ + "AccountService.CreateParamsBusinessProfile" + ] + """ + Business information about the account. + """ + business_type: NotRequired[ + "Literal['company', 'government_entity', 'individual', 'non_profit']" + ] + """ + The business type. Once you create an [Account Link](https://stripe.com/docs/api/account_links) or [Account Session](https://stripe.com/docs/api/account_sessions), this property can only be updated for Custom accounts. + """ + capabilities: NotRequired["AccountService.CreateParamsCapabilities"] + """ + Each key of the dictionary represents a capability, and each capability maps to its settings (e.g. whether it has been requested or not). Each capability will be inactive until you have provided its specific requirements and Stripe has verified them. An account may have some of its requested capabilities be active and some be inactive. + """ + company: NotRequired["AccountService.CreateParamsCompany"] + """ + Information about the company or business. This field is available for any `business_type`. Once you create an [Account Link](https://stripe.com/docs/api/account_links) or [Account Session](https://stripe.com/docs/api/account_sessions), this property can only be updated for Custom accounts. + """ + country: NotRequired["str"] + """ + The country in which the account holder resides, or in which the business is legally established. This should be an ISO 3166-1 alpha-2 country code. For example, if you are in the United States and the business for which you're creating an account is legally represented in Canada, you would use `CA` as the country for the account being created. Available countries include [Stripe's global markets](https://stripe.com/global) as well as countries where [cross-border payouts](https://stripe.com/docs/connect/cross-border-payouts) are supported. + """ + default_currency: NotRequired["str"] + """ + Three-letter ISO currency code representing the default currency for the account. This must be a currency that [Stripe supports in the account's country](https://stripe.com/docs/payouts). + """ + documents: NotRequired["AccountService.CreateParamsDocuments"] + """ + Documents that may be submitted to satisfy various informational requests. + """ + email: NotRequired["str"] + """ + The email address of the account holder. This is only to make the account easier to identify to you. Stripe only emails Custom accounts with your consent. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + external_account: NotRequired[ + "str|AccountService.CreateParamsBankAccount|AccountService.CreateParamsCard|AccountService.CreateParamsCardToken" + ] + """ + A card or bank account to attach to the account for receiving [payouts](https://stripe.com/docs/connect/bank-debit-card-payouts) (you won't be able to use it for top-ups). You can provide either a token, like the ones returned by [Stripe.js](https://stripe.com/docs/js), or a dictionary, as documented in the `external_account` parameter for [bank account](https://stripe.com/docs/api#account_create_bank_account) creation. + + By default, providing an external account sets it as the new default external account for its currency, and deletes the old default if one exists. To add additional external accounts without replacing the existing default for the currency, use the [bank account](https://stripe.com/docs/api#account_create_bank_account) or [card creation](https://stripe.com/docs/api#account_create_card) APIs. + + Once you create an [Account Link](https://stripe.com/docs/api/account_links) or [Account Session](https://stripe.com/docs/api/account_sessions), this property can only be updated for Custom accounts. + """ + individual: NotRequired["AccountService.CreateParamsIndividual"] + """ + Information about the person represented by the account. This field is null unless `business_type` is set to `individual`. Once you create an [Account Link](https://stripe.com/docs/api/account_links) or [Account Session](https://stripe.com/docs/api/account_sessions), this property can only be updated for Custom accounts. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + settings: NotRequired["AccountService.CreateParamsSettings"] + """ + Options for customizing how the account functions within Stripe. + """ + tos_acceptance: NotRequired["AccountService.CreateParamsTosAcceptance"] + """ + Details on the account's acceptance of the [Stripe Services Agreement](https://stripe.com/docs/connect/updating-accounts#tos-acceptance) This property can only be updated for Custom accounts. + """ + type: NotRequired["Literal['custom', 'express', 'standard']"] + """ + The type of Stripe account to create. May be one of `custom`, `express` or `standard`. + """ + + class CreateParamsBankAccount(TypedDict): + object: Literal["bank_account"] + account_holder_name: NotRequired["str"] + """ + The name of the person or business that owns the bank account.This field is required when attaching the bank account to a `Customer` object. + """ + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + The type of entity that holds the account. It can be `company` or `individual`. This field is required when attaching the bank account to a `Customer` object. + """ + account_number: str + """ + The account number for the bank account, in string form. Must be a checking account. + """ + country: str + """ + The country in which the bank account is located. + """ + currency: NotRequired["str"] + """ + The currency the bank account is in. This must be a country/currency pairing that [Stripe supports.](docs/payouts) + """ + routing_number: NotRequired["str"] + """ + The routing number, sort code, or other country-appropriateinstitution number for the bank account. For US bank accounts, this is required and should bethe ACH routing number, not the wire routing number. If you are providing an IBAN for`account_number`, this field is not required. + """ + + class CreateParamsBusinessProfile(TypedDict): + annual_revenue: NotRequired[ + "AccountService.CreateParamsBusinessProfileAnnualRevenue" + ] + """ + The applicant's gross annual revenue for its preceding fiscal year. + """ + estimated_worker_count: NotRequired["int"] + """ + An estimated upper bound of employees, contractors, vendors, etc. currently working for the business. + """ + mcc: NotRequired["str"] + """ + [The merchant category code for the account](https://stripe.com/docs/connect/setting-mcc). MCCs are used to classify businesses based on the goods or services they provide. + """ + monthly_estimated_revenue: NotRequired[ + "AccountService.CreateParamsBusinessProfileMonthlyEstimatedRevenue" + ] + """ + An estimate of the monthly revenue of the business. Only accepted for accounts in Brazil and India. + """ + name: NotRequired["str"] + """ + The customer-facing business name. + """ + product_description: NotRequired["str"] + """ + Internal-only description of the product sold by, or service provided by, the business. Used by Stripe for risk and underwriting purposes. + """ + support_address: NotRequired[ + "AccountService.CreateParamsBusinessProfileSupportAddress" + ] + """ + A publicly available mailing address for sending support issues to. + """ + support_email: NotRequired["str"] + """ + A publicly available email address for sending support issues to. + """ + support_phone: NotRequired["str"] + """ + A publicly available phone number to call with support issues. + """ + support_url: NotRequired["Literal['']|str"] + """ + A publicly available website for handling support issues. + """ + url: NotRequired["str"] + """ + The business's publicly available website. + """ + + class CreateParamsBusinessProfileAnnualRevenue(TypedDict): + amount: int + """ + A non-negative integer representing the amount in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + fiscal_year_end: str + """ + The close-out date of the preceding fiscal year in ISO 8601 format. E.g. 2023-12-31 for the 31st of December, 2023. + """ + + class CreateParamsBusinessProfileMonthlyEstimatedRevenue(TypedDict): + amount: int + """ + A non-negative integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + + class CreateParamsBusinessProfileSupportAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsCapabilities(TypedDict): + acss_debit_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesAcssDebitPayments" + ] + """ + The acss_debit_payments capability. + """ + affirm_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesAffirmPayments" + ] + """ + The affirm_payments capability. + """ + afterpay_clearpay_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesAfterpayClearpayPayments" + ] + """ + The afterpay_clearpay_payments capability. + """ + au_becs_debit_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesAuBecsDebitPayments" + ] + """ + The au_becs_debit_payments capability. + """ + bacs_debit_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesBacsDebitPayments" + ] + """ + The bacs_debit_payments capability. + """ + bancontact_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesBancontactPayments" + ] + """ + The bancontact_payments capability. + """ + bank_transfer_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesBankTransferPayments" + ] + """ + The bank_transfer_payments capability. + """ + blik_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesBlikPayments" + ] + """ + The blik_payments capability. + """ + boleto_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesBoletoPayments" + ] + """ + The boleto_payments capability. + """ + card_issuing: NotRequired[ + "AccountService.CreateParamsCapabilitiesCardIssuing" + ] + """ + The card_issuing capability. + """ + card_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesCardPayments" + ] + """ + The card_payments capability. + """ + cartes_bancaires_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesCartesBancairesPayments" + ] + """ + The cartes_bancaires_payments capability. + """ + cashapp_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesCashappPayments" + ] + """ + The cashapp_payments capability. + """ + eps_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesEpsPayments" + ] + """ + The eps_payments capability. + """ + fpx_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesFpxPayments" + ] + """ + The fpx_payments capability. + """ + giropay_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesGiropayPayments" + ] + """ + The giropay_payments capability. + """ + grabpay_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesGrabpayPayments" + ] + """ + The grabpay_payments capability. + """ + ideal_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesIdealPayments" + ] + """ + The ideal_payments capability. + """ + india_international_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesIndiaInternationalPayments" + ] + """ + The india_international_payments capability. + """ + jcb_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesJcbPayments" + ] + """ + The jcb_payments capability. + """ + klarna_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesKlarnaPayments" + ] + """ + The klarna_payments capability. + """ + konbini_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesKonbiniPayments" + ] + """ + The konbini_payments capability. + """ + legacy_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesLegacyPayments" + ] + """ + The legacy_payments capability. + """ + link_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesLinkPayments" + ] + """ + The link_payments capability. + """ + oxxo_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesOxxoPayments" + ] + """ + The oxxo_payments capability. + """ + p24_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesP24Payments" + ] + """ + The p24_payments capability. + """ + paynow_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesPaynowPayments" + ] + """ + The paynow_payments capability. + """ + promptpay_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesPromptpayPayments" + ] + """ + The promptpay_payments capability. + """ + revolut_pay_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesRevolutPayPayments" + ] + """ + The revolut_pay_payments capability. + """ + sepa_debit_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesSepaDebitPayments" + ] + """ + The sepa_debit_payments capability. + """ + sofort_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesSofortPayments" + ] + """ + The sofort_payments capability. + """ + tax_reporting_us_1099_k: NotRequired[ + "AccountService.CreateParamsCapabilitiesTaxReportingUs1099K" + ] + """ + The tax_reporting_us_1099_k capability. + """ + tax_reporting_us_1099_misc: NotRequired[ + "AccountService.CreateParamsCapabilitiesTaxReportingUs1099Misc" + ] + """ + The tax_reporting_us_1099_misc capability. + """ + transfers: NotRequired[ + "AccountService.CreateParamsCapabilitiesTransfers" + ] + """ + The transfers capability. + """ + treasury: NotRequired[ + "AccountService.CreateParamsCapabilitiesTreasury" + ] + """ + The treasury capability. + """ + us_bank_account_ach_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesUsBankAccountAchPayments" + ] + """ + The us_bank_account_ach_payments capability. + """ + zip_payments: NotRequired[ + "AccountService.CreateParamsCapabilitiesZipPayments" + ] + """ + The zip_payments capability. + """ + + class CreateParamsCapabilitiesAcssDebitPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesAffirmPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesAfterpayClearpayPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesAuBecsDebitPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesBacsDebitPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesBancontactPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesBankTransferPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesBlikPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesBoletoPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesCardIssuing(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesCardPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesCartesBancairesPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesCashappPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesEpsPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesFpxPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesGiropayPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesGrabpayPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesIdealPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesIndiaInternationalPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesJcbPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesKlarnaPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesKonbiniPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesLegacyPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesLinkPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesOxxoPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesP24Payments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesPaynowPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesPromptpayPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesRevolutPayPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesSepaDebitPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesSofortPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesTaxReportingUs1099K(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesTaxReportingUs1099Misc(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesTransfers(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesTreasury(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesUsBankAccountAchPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCapabilitiesZipPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class CreateParamsCard(TypedDict): + object: Literal["card"] + address_city: NotRequired["str"] + address_country: NotRequired["str"] + address_line1: NotRequired["str"] + address_line2: NotRequired["str"] + address_state: NotRequired["str"] + address_zip: NotRequired["str"] + currency: NotRequired["str"] + cvc: NotRequired["str"] + exp_month: int + exp_year: int + name: NotRequired["str"] + number: str + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + """ + default_for_currency: NotRequired["bool"] + + class CreateParamsCardToken(TypedDict): + object: Literal["card"] + currency: NotRequired["str"] + token: str + + class CreateParamsCompany(TypedDict): + address: NotRequired["AccountService.CreateParamsCompanyAddress"] + """ + The company's primary address. + """ + address_kana: NotRequired[ + "AccountService.CreateParamsCompanyAddressKana" + ] + """ + The Kana variation of the company's primary address (Japan only). + """ + address_kanji: NotRequired[ + "AccountService.CreateParamsCompanyAddressKanji" + ] + """ + The Kanji variation of the company's primary address (Japan only). + """ + directors_provided: NotRequired["bool"] + """ + Whether the company's directors have been provided. Set this Boolean to `true` after creating all the company's directors with [the Persons API](https://stripe.com/docs/api/persons) for accounts with a `relationship.director` requirement. This value is not automatically set to `true` after creating directors, so it needs to be updated to indicate all directors have been provided. + """ + executives_provided: NotRequired["bool"] + """ + Whether the company's executives have been provided. Set this Boolean to `true` after creating all the company's executives with [the Persons API](https://stripe.com/docs/api/persons) for accounts with a `relationship.executive` requirement. + """ + export_license_id: NotRequired["str"] + """ + The export license ID number of the company, also referred as Import Export Code (India only). + """ + export_purpose_code: NotRequired["str"] + """ + The purpose code to use for export transactions (India only). + """ + name: NotRequired["str"] + """ + The company's legal name. + """ + name_kana: NotRequired["str"] + """ + The Kana variation of the company's legal name (Japan only). + """ + name_kanji: NotRequired["str"] + """ + The Kanji variation of the company's legal name (Japan only). + """ + owners_provided: NotRequired["bool"] + """ + Whether the company's owners have been provided. Set this Boolean to `true` after creating all the company's owners with [the Persons API](https://stripe.com/docs/api/persons) for accounts with a `relationship.owner` requirement. + """ + ownership_declaration: NotRequired[ + "AccountService.CreateParamsCompanyOwnershipDeclaration" + ] + """ + This hash is used to attest that the beneficial owner information provided to Stripe is both current and correct. + """ + phone: NotRequired["str"] + """ + The company's phone number (used for verification). + """ + registration_number: NotRequired["str"] + """ + The identification number given to a company when it is registered or incorporated, if distinct from the identification number used for filing taxes. (Examples are the CIN for companies and LLP IN for partnerships in India, and the Company Registration Number in Hong Kong). + """ + structure: NotRequired[ + "Literal['']|Literal['free_zone_establishment', 'free_zone_llc', 'government_instrumentality', 'governmental_unit', 'incorporated_non_profit', 'incorporated_partnership', 'limited_liability_partnership', 'llc', 'multi_member_llc', 'private_company', 'private_corporation', 'private_partnership', 'public_company', 'public_corporation', 'public_partnership', 'registered_charity', 'single_member_llc', 'sole_establishment', 'sole_proprietorship', 'tax_exempt_government_instrumentality', 'unincorporated_association', 'unincorporated_non_profit', 'unincorporated_partnership']" + ] + """ + The category identifying the legal structure of the company or legal entity. See [Business structure](https://stripe.com/docs/connect/identity-verification#business-structure) for more details. Pass an empty string to unset this value. + """ + tax_id: NotRequired["str"] + """ + The business ID number of the company, as appropriate for the company's country. (Examples are an Employer ID Number in the U.S., a Business Number in Canada, or a Company Number in the UK.) + """ + tax_id_registrar: NotRequired["str"] + """ + The jurisdiction in which the `tax_id` is registered (Germany-based companies only). + """ + vat_id: NotRequired["str"] + """ + The VAT number of the company. + """ + verification: NotRequired[ + "AccountService.CreateParamsCompanyVerification" + ] + """ + Information on the verification state of the company. + """ + + class CreateParamsCompanyAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsCompanyAddressKana(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class CreateParamsCompanyAddressKanji(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class CreateParamsCompanyOwnershipDeclaration(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the beneficial owner attestation was made. + """ + ip: NotRequired["str"] + """ + The IP address from which the beneficial owner attestation was made. + """ + user_agent: NotRequired["str"] + """ + The user agent of the browser from which the beneficial owner attestation was made. + """ + + class CreateParamsCompanyVerification(TypedDict): + document: NotRequired[ + "AccountService.CreateParamsCompanyVerificationDocument" + ] + """ + A document verifying the business. + """ + + class CreateParamsCompanyVerificationDocument(TypedDict): + back: NotRequired["str"] + """ + The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class CreateParamsDocuments(TypedDict): + bank_account_ownership_verification: NotRequired[ + "AccountService.CreateParamsDocumentsBankAccountOwnershipVerification" + ] + """ + One or more documents that support the [Bank account ownership verification](https://support.stripe.com/questions/bank-account-ownership-verification) requirement. Must be a document associated with the account's primary active bank account that displays the last 4 digits of the account number, either a statement or a voided check. + """ + company_license: NotRequired[ + "AccountService.CreateParamsDocumentsCompanyLicense" + ] + """ + One or more documents that demonstrate proof of a company's license to operate. + """ + company_memorandum_of_association: NotRequired[ + "AccountService.CreateParamsDocumentsCompanyMemorandumOfAssociation" + ] + """ + One or more documents showing the company's Memorandum of Association. + """ + company_ministerial_decree: NotRequired[ + "AccountService.CreateParamsDocumentsCompanyMinisterialDecree" + ] + """ + (Certain countries only) One or more documents showing the ministerial decree legalizing the company's establishment. + """ + company_registration_verification: NotRequired[ + "AccountService.CreateParamsDocumentsCompanyRegistrationVerification" + ] + """ + One or more documents that demonstrate proof of a company's registration with the appropriate local authorities. + """ + company_tax_id_verification: NotRequired[ + "AccountService.CreateParamsDocumentsCompanyTaxIdVerification" + ] + """ + One or more documents that demonstrate proof of a company's tax ID. + """ + proof_of_registration: NotRequired[ + "AccountService.CreateParamsDocumentsProofOfRegistration" + ] + """ + One or more documents showing the company's proof of registration with the national business registry. + """ + + class CreateParamsDocumentsBankAccountOwnershipVerification(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class CreateParamsDocumentsCompanyLicense(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class CreateParamsDocumentsCompanyMemorandumOfAssociation(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class CreateParamsDocumentsCompanyMinisterialDecree(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class CreateParamsDocumentsCompanyRegistrationVerification(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class CreateParamsDocumentsCompanyTaxIdVerification(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class CreateParamsDocumentsProofOfRegistration(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class CreateParamsIndividual(TypedDict): + address: NotRequired["AccountService.CreateParamsIndividualAddress"] + """ + The individual's primary address. + """ + address_kana: NotRequired[ + "AccountService.CreateParamsIndividualAddressKana" + ] + """ + The Kana variation of the the individual's primary address (Japan only). + """ + address_kanji: NotRequired[ + "AccountService.CreateParamsIndividualAddressKanji" + ] + """ + The Kanji variation of the the individual's primary address (Japan only). + """ + dob: NotRequired[ + "Literal['']|AccountService.CreateParamsIndividualDob" + ] + """ + The individual's date of birth. + """ + email: NotRequired["str"] + """ + The individual's email address. + """ + first_name: NotRequired["str"] + """ + The individual's first name. + """ + first_name_kana: NotRequired["str"] + """ + The Kana variation of the the individual's first name (Japan only). + """ + first_name_kanji: NotRequired["str"] + """ + The Kanji variation of the individual's first name (Japan only). + """ + full_name_aliases: NotRequired["Literal['']|List[str]"] + """ + A list of alternate names or aliases that the individual is known by. + """ + gender: NotRequired["str"] + """ + The individual's gender (International regulations require either "male" or "female"). + """ + id_number: NotRequired["str"] + """ + The government-issued ID number of the individual, as appropriate for the representative's country. (Examples are a Social Security Number in the U.S., or a Social Insurance Number in Canada). Instead of the number itself, you can also provide a [PII token created with Stripe.js](https://stripe.com/docs/js/tokens/create_token?type=pii). + """ + id_number_secondary: NotRequired["str"] + """ + The government-issued secondary ID number of the individual, as appropriate for the representative's country, will be used for enhanced verification checks. In Thailand, this would be the laser code found on the back of an ID card. Instead of the number itself, you can also provide a [PII token created with Stripe.js](https://stripe.com/docs/js/tokens/create_token?type=pii). + """ + last_name: NotRequired["str"] + """ + The individual's last name. + """ + last_name_kana: NotRequired["str"] + """ + The Kana variation of the individual's last name (Japan only). + """ + last_name_kanji: NotRequired["str"] + """ + The Kanji variation of the individual's last name (Japan only). + """ + maiden_name: NotRequired["str"] + """ + The individual's maiden name. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + phone: NotRequired["str"] + """ + The individual's phone number. + """ + political_exposure: NotRequired["Literal['existing', 'none']"] + """ + Indicates if the person or any of their representatives, family members, or other closely related persons, declares that they hold or have held an important public job or function, in any jurisdiction. + """ + registered_address: NotRequired[ + "AccountService.CreateParamsIndividualRegisteredAddress" + ] + """ + The individual's registered address. + """ + ssn_last_4: NotRequired["str"] + """ + The last four digits of the individual's Social Security Number (U.S. only). + """ + verification: NotRequired[ + "AccountService.CreateParamsIndividualVerification" + ] + """ + The individual's verification document information. + """ + + class CreateParamsIndividualAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsIndividualAddressKana(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class CreateParamsIndividualAddressKanji(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class CreateParamsIndividualDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class CreateParamsIndividualRegisteredAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsIndividualVerification(TypedDict): + additional_document: NotRequired[ + "AccountService.CreateParamsIndividualVerificationAdditionalDocument" + ] + """ + A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. + """ + document: NotRequired[ + "AccountService.CreateParamsIndividualVerificationDocument" + ] + """ + An identifying document, either a passport or local ID card. + """ + + class CreateParamsIndividualVerificationAdditionalDocument(TypedDict): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class CreateParamsIndividualVerificationDocument(TypedDict): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class CreateParamsSettings(TypedDict): + bacs_debit_payments: NotRequired[ + "AccountService.CreateParamsSettingsBacsDebitPayments" + ] + """ + Settings specific to Bacs Direct Debit. + """ + branding: NotRequired["AccountService.CreateParamsSettingsBranding"] + """ + Settings used to apply the account's branding to email receipts, invoices, Checkout, and other products. + """ + card_issuing: NotRequired[ + "AccountService.CreateParamsSettingsCardIssuing" + ] + """ + Settings specific to the account's use of the Card Issuing product. + """ + card_payments: NotRequired[ + "AccountService.CreateParamsSettingsCardPayments" + ] + """ + Settings specific to card charging on the account. + """ + payments: NotRequired["AccountService.CreateParamsSettingsPayments"] + """ + Settings that apply across payment methods for charging on the account. + """ + payouts: NotRequired["AccountService.CreateParamsSettingsPayouts"] + """ + Settings specific to the account's payouts. + """ + treasury: NotRequired["AccountService.CreateParamsSettingsTreasury"] + """ + Settings specific to the account's Treasury FinancialAccounts. + """ + + class CreateParamsSettingsBacsDebitPayments(TypedDict): + display_name: NotRequired["str"] + """ + The Bacs Direct Debit Display Name for this account. For payments made with Bacs Direct Debit, this name appears on the mandate as the statement descriptor. Mobile banking apps display it as the name of the business. To use custom branding, set the Bacs Direct Debit Display Name during or right after creation. Custom branding incurs an additional monthly fee for the platform. If you don't set the display name before requesting Bacs capability, it's automatically set as "Stripe" and the account is onboarded to Stripe branding, which is free. + """ + + class CreateParamsSettingsBranding(TypedDict): + icon: NotRequired["str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) An icon for the account. Must be square and at least 128px x 128px. + """ + logo: NotRequired["str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A logo for the account that will be used in Checkout instead of the icon and without the account's name next to it if provided. Must be at least 128px x 128px. + """ + primary_color: NotRequired["str"] + """ + A CSS hex color value representing the primary branding color for this account. + """ + secondary_color: NotRequired["str"] + """ + A CSS hex color value representing the secondary branding color for this account. + """ + + class CreateParamsSettingsCardIssuing(TypedDict): + tos_acceptance: NotRequired[ + "AccountService.CreateParamsSettingsCardIssuingTosAcceptance" + ] + """ + Details on the account's acceptance of the [Stripe Issuing Terms and Disclosures](https://stripe.com/docs/issuing/connect/tos_acceptance). + """ + + class CreateParamsSettingsCardIssuingTosAcceptance(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the account representative accepted the service agreement. + """ + ip: NotRequired["str"] + """ + The IP address from which the account representative accepted the service agreement. + """ + user_agent: NotRequired["Literal['']|str"] + """ + The user agent of the browser from which the account representative accepted the service agreement. + """ + + class CreateParamsSettingsCardPayments(TypedDict): + decline_on: NotRequired[ + "AccountService.CreateParamsSettingsCardPaymentsDeclineOn" + ] + """ + Automatically declines certain charge types regardless of whether the card issuer accepted or declined the charge. + """ + statement_descriptor_prefix: NotRequired["str"] + """ + The default text that appears on credit card statements when a charge is made. This field prefixes any dynamic `statement_descriptor` specified on the charge. `statement_descriptor_prefix` is useful for maximizing descriptor space for the dynamic portion. + """ + statement_descriptor_prefix_kana: NotRequired["Literal['']|str"] + """ + The Kana variation of the default text that appears on credit card statements when a charge is made (Japan only). This field prefixes any dynamic `statement_descriptor_suffix_kana` specified on the charge. `statement_descriptor_prefix_kana` is useful for maximizing descriptor space for the dynamic portion. + """ + statement_descriptor_prefix_kanji: NotRequired["Literal['']|str"] + """ + The Kanji variation of the default text that appears on credit card statements when a charge is made (Japan only). This field prefixes any dynamic `statement_descriptor_suffix_kanji` specified on the charge. `statement_descriptor_prefix_kanji` is useful for maximizing descriptor space for the dynamic portion. + """ + + class CreateParamsSettingsCardPaymentsDeclineOn(TypedDict): + avs_failure: NotRequired["bool"] + """ + Whether Stripe automatically declines charges with an incorrect ZIP or postal code. This setting only applies when a ZIP or postal code is provided and they fail bank verification. + """ + cvc_failure: NotRequired["bool"] + """ + Whether Stripe automatically declines charges with an incorrect CVC. This setting only applies when a CVC is provided and it fails bank verification. + """ + + class CreateParamsSettingsPayments(TypedDict): + statement_descriptor: NotRequired["str"] + """ + The default text that appears on credit card statements when a charge is made. This field prefixes any dynamic `statement_descriptor` specified on the charge. + """ + statement_descriptor_kana: NotRequired["str"] + """ + The Kana variation of the default text that appears on credit card statements when a charge is made (Japan only). + """ + statement_descriptor_kanji: NotRequired["str"] + """ + The Kanji variation of the default text that appears on credit card statements when a charge is made (Japan only). + """ + + class CreateParamsSettingsPayouts(TypedDict): + debit_negative_balances: NotRequired["bool"] + """ + A Boolean indicating whether Stripe should try to reclaim negative balances from an attached bank account. For details, see [Understanding Connect Account Balances](https://stripe.com/docs/connect/account-balances). + """ + schedule: NotRequired[ + "AccountService.CreateParamsSettingsPayoutsSchedule" + ] + """ + Details on when funds from charges are available, and when they are paid out to an external account. For details, see our [Setting Bank and Debit Card Payouts](https://stripe.com/docs/connect/bank-transfers#payout-information) documentation. + """ + statement_descriptor: NotRequired["str"] + """ + The text that appears on the bank account statement for payouts. If not set, this defaults to the platform's bank descriptor as set in the Dashboard. + """ + + class CreateParamsSettingsPayoutsSchedule(TypedDict): + delay_days: NotRequired["Literal['minimum']|int"] + """ + The number of days charge funds are held before being paid out. May also be set to `minimum`, representing the lowest available value for the account country. Default is `minimum`. The `delay_days` parameter remains at the last configured value if `interval` is `manual`. [Learn more about controlling payout delay days](https://stripe.com/docs/connect/manage-payout-schedule). + """ + interval: NotRequired[ + "Literal['daily', 'manual', 'monthly', 'weekly']" + ] + """ + How frequently available funds are paid out. One of: `daily`, `manual`, `weekly`, or `monthly`. Default is `daily`. + """ + monthly_anchor: NotRequired["int"] + """ + The day of the month when available funds are paid out, specified as a number between 1--31. Payouts nominally scheduled between the 29th and 31st of the month are instead sent on the last day of a shorter month. Required and applicable only if `interval` is `monthly`. + """ + weekly_anchor: NotRequired[ + "Literal['friday', 'monday', 'saturday', 'sunday', 'thursday', 'tuesday', 'wednesday']" + ] + """ + The day of the week when available funds are paid out, specified as `monday`, `tuesday`, etc. (required and applicable only if `interval` is `weekly`.) + """ + + class CreateParamsSettingsTreasury(TypedDict): + tos_acceptance: NotRequired[ + "AccountService.CreateParamsSettingsTreasuryTosAcceptance" + ] + """ + Details on the account's acceptance of the Stripe Treasury Services Agreement. + """ + + class CreateParamsSettingsTreasuryTosAcceptance(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the account representative accepted the service agreement. + """ + ip: NotRequired["str"] + """ + The IP address from which the account representative accepted the service agreement. + """ + user_agent: NotRequired["Literal['']|str"] + """ + The user agent of the browser from which the account representative accepted the service agreement. + """ + + class CreateParamsTosAcceptance(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the account representative accepted their service agreement. + """ + ip: NotRequired["str"] + """ + The IP address from which the account representative accepted their service agreement. + """ + service_agreement: NotRequired["str"] + """ + The user's service agreement type. + """ + user_agent: NotRequired["str"] + """ + The user agent of the browser from which the account representative accepted their service agreement. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + created: NotRequired["AccountService.ListParamsCreated|int"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RejectParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + reason: str + """ + The reason for rejecting the account. Can be `fraud`, `terms_of_service`, or `other`. + """ + + class RetrieveCurrentParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + account_token: NotRequired["str"] + """ + An [account token](https://stripe.com/docs/api#create_account_token), used to securely provide details to the account. + """ + business_profile: NotRequired[ + "AccountService.UpdateParamsBusinessProfile" + ] + """ + Business information about the account. + """ + business_type: NotRequired[ + "Literal['company', 'government_entity', 'individual', 'non_profit']" + ] + """ + The business type. Once you create an [Account Link](https://stripe.com/docs/api/account_links) or [Account Session](https://stripe.com/docs/api/account_sessions), this property can only be updated for Custom accounts. + """ + capabilities: NotRequired["AccountService.UpdateParamsCapabilities"] + """ + Each key of the dictionary represents a capability, and each capability maps to its settings (e.g. whether it has been requested or not). Each capability will be inactive until you have provided its specific requirements and Stripe has verified them. An account may have some of its requested capabilities be active and some be inactive. + """ + company: NotRequired["AccountService.UpdateParamsCompany"] + """ + Information about the company or business. This field is available for any `business_type`. Once you create an [Account Link](https://stripe.com/docs/api/account_links) or [Account Session](https://stripe.com/docs/api/account_sessions), this property can only be updated for Custom accounts. + """ + default_currency: NotRequired["str"] + """ + Three-letter ISO currency code representing the default currency for the account. This must be a currency that [Stripe supports in the account's country](https://stripe.com/docs/payouts). + """ + documents: NotRequired["AccountService.UpdateParamsDocuments"] + """ + Documents that may be submitted to satisfy various informational requests. + """ + email: NotRequired["str"] + """ + The email address of the account holder. This is only to make the account easier to identify to you. Stripe only emails Custom accounts with your consent. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + external_account: NotRequired[ + "Literal['']|str|AccountService.UpdateParamsBankAccount|AccountService.UpdateParamsCard|AccountService.UpdateParamsCardToken" + ] + """ + A card or bank account to attach to the account for receiving [payouts](https://stripe.com/docs/connect/bank-debit-card-payouts) (you won't be able to use it for top-ups). You can provide either a token, like the ones returned by [Stripe.js](https://stripe.com/docs/js), or a dictionary, as documented in the `external_account` parameter for [bank account](https://stripe.com/docs/api#account_create_bank_account) creation. + + By default, providing an external account sets it as the new default external account for its currency, and deletes the old default if one exists. To add additional external accounts without replacing the existing default for the currency, use the [bank account](https://stripe.com/docs/api#account_create_bank_account) or [card creation](https://stripe.com/docs/api#account_create_card) APIs. + + Once you create an [Account Link](https://stripe.com/docs/api/account_links) or [Account Session](https://stripe.com/docs/api/account_sessions), this property can only be updated for Custom accounts. + """ + individual: NotRequired["AccountService.UpdateParamsIndividual"] + """ + Information about the person represented by the account. This field is null unless `business_type` is set to `individual`. Once you create an [Account Link](https://stripe.com/docs/api/account_links) or [Account Session](https://stripe.com/docs/api/account_sessions), this property can only be updated for Custom accounts. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + settings: NotRequired["AccountService.UpdateParamsSettings"] + """ + Options for customizing how the account functions within Stripe. + """ + tos_acceptance: NotRequired["AccountService.UpdateParamsTosAcceptance"] + """ + Details on the account's acceptance of the [Stripe Services Agreement](https://stripe.com/docs/connect/updating-accounts#tos-acceptance) This property can only be updated for Custom accounts. + """ + + class UpdateParamsBankAccount(TypedDict): + object: Literal["bank_account"] + account_holder_name: NotRequired["str"] + """ + The name of the person or business that owns the bank account.This field is required when attaching the bank account to a `Customer` object. + """ + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + The type of entity that holds the account. It can be `company` or `individual`. This field is required when attaching the bank account to a `Customer` object. + """ + account_number: str + """ + The account number for the bank account, in string form. Must be a checking account. + """ + country: str + """ + The country in which the bank account is located. + """ + currency: NotRequired["str"] + """ + The currency the bank account is in. This must be a country/currency pairing that [Stripe supports.](docs/payouts) + """ + routing_number: NotRequired["str"] + """ + The routing number, sort code, or other country-appropriateinstitution number for the bank account. For US bank accounts, this is required and should bethe ACH routing number, not the wire routing number. If you are providing an IBAN for`account_number`, this field is not required. + """ + + class UpdateParamsBusinessProfile(TypedDict): + annual_revenue: NotRequired[ + "AccountService.UpdateParamsBusinessProfileAnnualRevenue" + ] + """ + The applicant's gross annual revenue for its preceding fiscal year. + """ + estimated_worker_count: NotRequired["int"] + """ + An estimated upper bound of employees, contractors, vendors, etc. currently working for the business. + """ + mcc: NotRequired["str"] + """ + [The merchant category code for the account](https://stripe.com/docs/connect/setting-mcc). MCCs are used to classify businesses based on the goods or services they provide. + """ + monthly_estimated_revenue: NotRequired[ + "AccountService.UpdateParamsBusinessProfileMonthlyEstimatedRevenue" + ] + """ + An estimate of the monthly revenue of the business. Only accepted for accounts in Brazil and India. + """ + name: NotRequired["str"] + """ + The customer-facing business name. + """ + product_description: NotRequired["str"] + """ + Internal-only description of the product sold by, or service provided by, the business. Used by Stripe for risk and underwriting purposes. + """ + support_address: NotRequired[ + "AccountService.UpdateParamsBusinessProfileSupportAddress" + ] + """ + A publicly available mailing address for sending support issues to. + """ + support_email: NotRequired["str"] + """ + A publicly available email address for sending support issues to. + """ + support_phone: NotRequired["str"] + """ + A publicly available phone number to call with support issues. + """ + support_url: NotRequired["Literal['']|str"] + """ + A publicly available website for handling support issues. + """ + url: NotRequired["str"] + """ + The business's publicly available website. + """ + + class UpdateParamsBusinessProfileAnnualRevenue(TypedDict): + amount: int + """ + A non-negative integer representing the amount in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + fiscal_year_end: str + """ + The close-out date of the preceding fiscal year in ISO 8601 format. E.g. 2023-12-31 for the 31st of December, 2023. + """ + + class UpdateParamsBusinessProfileMonthlyEstimatedRevenue(TypedDict): + amount: int + """ + A non-negative integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + + class UpdateParamsBusinessProfileSupportAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsCapabilities(TypedDict): + acss_debit_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesAcssDebitPayments" + ] + """ + The acss_debit_payments capability. + """ + affirm_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesAffirmPayments" + ] + """ + The affirm_payments capability. + """ + afterpay_clearpay_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesAfterpayClearpayPayments" + ] + """ + The afterpay_clearpay_payments capability. + """ + au_becs_debit_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesAuBecsDebitPayments" + ] + """ + The au_becs_debit_payments capability. + """ + bacs_debit_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesBacsDebitPayments" + ] + """ + The bacs_debit_payments capability. + """ + bancontact_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesBancontactPayments" + ] + """ + The bancontact_payments capability. + """ + bank_transfer_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesBankTransferPayments" + ] + """ + The bank_transfer_payments capability. + """ + blik_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesBlikPayments" + ] + """ + The blik_payments capability. + """ + boleto_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesBoletoPayments" + ] + """ + The boleto_payments capability. + """ + card_issuing: NotRequired[ + "AccountService.UpdateParamsCapabilitiesCardIssuing" + ] + """ + The card_issuing capability. + """ + card_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesCardPayments" + ] + """ + The card_payments capability. + """ + cartes_bancaires_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesCartesBancairesPayments" + ] + """ + The cartes_bancaires_payments capability. + """ + cashapp_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesCashappPayments" + ] + """ + The cashapp_payments capability. + """ + eps_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesEpsPayments" + ] + """ + The eps_payments capability. + """ + fpx_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesFpxPayments" + ] + """ + The fpx_payments capability. + """ + giropay_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesGiropayPayments" + ] + """ + The giropay_payments capability. + """ + grabpay_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesGrabpayPayments" + ] + """ + The grabpay_payments capability. + """ + ideal_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesIdealPayments" + ] + """ + The ideal_payments capability. + """ + india_international_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesIndiaInternationalPayments" + ] + """ + The india_international_payments capability. + """ + jcb_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesJcbPayments" + ] + """ + The jcb_payments capability. + """ + klarna_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesKlarnaPayments" + ] + """ + The klarna_payments capability. + """ + konbini_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesKonbiniPayments" + ] + """ + The konbini_payments capability. + """ + legacy_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesLegacyPayments" + ] + """ + The legacy_payments capability. + """ + link_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesLinkPayments" + ] + """ + The link_payments capability. + """ + oxxo_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesOxxoPayments" + ] + """ + The oxxo_payments capability. + """ + p24_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesP24Payments" + ] + """ + The p24_payments capability. + """ + paynow_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesPaynowPayments" + ] + """ + The paynow_payments capability. + """ + promptpay_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesPromptpayPayments" + ] + """ + The promptpay_payments capability. + """ + revolut_pay_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesRevolutPayPayments" + ] + """ + The revolut_pay_payments capability. + """ + sepa_debit_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesSepaDebitPayments" + ] + """ + The sepa_debit_payments capability. + """ + sofort_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesSofortPayments" + ] + """ + The sofort_payments capability. + """ + tax_reporting_us_1099_k: NotRequired[ + "AccountService.UpdateParamsCapabilitiesTaxReportingUs1099K" + ] + """ + The tax_reporting_us_1099_k capability. + """ + tax_reporting_us_1099_misc: NotRequired[ + "AccountService.UpdateParamsCapabilitiesTaxReportingUs1099Misc" + ] + """ + The tax_reporting_us_1099_misc capability. + """ + transfers: NotRequired[ + "AccountService.UpdateParamsCapabilitiesTransfers" + ] + """ + The transfers capability. + """ + treasury: NotRequired[ + "AccountService.UpdateParamsCapabilitiesTreasury" + ] + """ + The treasury capability. + """ + us_bank_account_ach_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesUsBankAccountAchPayments" + ] + """ + The us_bank_account_ach_payments capability. + """ + zip_payments: NotRequired[ + "AccountService.UpdateParamsCapabilitiesZipPayments" + ] + """ + The zip_payments capability. + """ + + class UpdateParamsCapabilitiesAcssDebitPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesAffirmPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesAfterpayClearpayPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesAuBecsDebitPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesBacsDebitPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesBancontactPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesBankTransferPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesBlikPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesBoletoPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesCardIssuing(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesCardPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesCartesBancairesPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesCashappPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesEpsPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesFpxPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesGiropayPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesGrabpayPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesIdealPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesIndiaInternationalPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesJcbPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesKlarnaPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesKonbiniPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesLegacyPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesLinkPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesOxxoPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesP24Payments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesPaynowPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesPromptpayPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesRevolutPayPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesSepaDebitPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesSofortPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesTaxReportingUs1099K(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesTaxReportingUs1099Misc(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesTransfers(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesTreasury(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesUsBankAccountAchPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCapabilitiesZipPayments(TypedDict): + requested: NotRequired["bool"] + """ + Passing true requests the capability for the account, if it is not already requested. A requested capability may not immediately become active. Any requirements to activate the capability are returned in the `requirements` arrays. + """ + + class UpdateParamsCard(TypedDict): + object: Literal["card"] + address_city: NotRequired["str"] + address_country: NotRequired["str"] + address_line1: NotRequired["str"] + address_line2: NotRequired["str"] + address_state: NotRequired["str"] + address_zip: NotRequired["str"] + currency: NotRequired["str"] + cvc: NotRequired["str"] + exp_month: int + exp_year: int + name: NotRequired["str"] + number: str + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + """ + default_for_currency: NotRequired["bool"] + + class UpdateParamsCardToken(TypedDict): + object: Literal["card"] + currency: NotRequired["str"] + token: str + + class UpdateParamsCompany(TypedDict): + address: NotRequired["AccountService.UpdateParamsCompanyAddress"] + """ + The company's primary address. + """ + address_kana: NotRequired[ + "AccountService.UpdateParamsCompanyAddressKana" + ] + """ + The Kana variation of the company's primary address (Japan only). + """ + address_kanji: NotRequired[ + "AccountService.UpdateParamsCompanyAddressKanji" + ] + """ + The Kanji variation of the company's primary address (Japan only). + """ + directors_provided: NotRequired["bool"] + """ + Whether the company's directors have been provided. Set this Boolean to `true` after creating all the company's directors with [the Persons API](https://stripe.com/docs/api/persons) for accounts with a `relationship.director` requirement. This value is not automatically set to `true` after creating directors, so it needs to be updated to indicate all directors have been provided. + """ + executives_provided: NotRequired["bool"] + """ + Whether the company's executives have been provided. Set this Boolean to `true` after creating all the company's executives with [the Persons API](https://stripe.com/docs/api/persons) for accounts with a `relationship.executive` requirement. + """ + export_license_id: NotRequired["str"] + """ + The export license ID number of the company, also referred as Import Export Code (India only). + """ + export_purpose_code: NotRequired["str"] + """ + The purpose code to use for export transactions (India only). + """ + name: NotRequired["str"] + """ + The company's legal name. + """ + name_kana: NotRequired["str"] + """ + The Kana variation of the company's legal name (Japan only). + """ + name_kanji: NotRequired["str"] + """ + The Kanji variation of the company's legal name (Japan only). + """ + owners_provided: NotRequired["bool"] + """ + Whether the company's owners have been provided. Set this Boolean to `true` after creating all the company's owners with [the Persons API](https://stripe.com/docs/api/persons) for accounts with a `relationship.owner` requirement. + """ + ownership_declaration: NotRequired[ + "AccountService.UpdateParamsCompanyOwnershipDeclaration" + ] + """ + This hash is used to attest that the beneficial owner information provided to Stripe is both current and correct. + """ + phone: NotRequired["str"] + """ + The company's phone number (used for verification). + """ + registration_number: NotRequired["str"] + """ + The identification number given to a company when it is registered or incorporated, if distinct from the identification number used for filing taxes. (Examples are the CIN for companies and LLP IN for partnerships in India, and the Company Registration Number in Hong Kong). + """ + structure: NotRequired[ + "Literal['']|Literal['free_zone_establishment', 'free_zone_llc', 'government_instrumentality', 'governmental_unit', 'incorporated_non_profit', 'incorporated_partnership', 'limited_liability_partnership', 'llc', 'multi_member_llc', 'private_company', 'private_corporation', 'private_partnership', 'public_company', 'public_corporation', 'public_partnership', 'registered_charity', 'single_member_llc', 'sole_establishment', 'sole_proprietorship', 'tax_exempt_government_instrumentality', 'unincorporated_association', 'unincorporated_non_profit', 'unincorporated_partnership']" + ] + """ + The category identifying the legal structure of the company or legal entity. See [Business structure](https://stripe.com/docs/connect/identity-verification#business-structure) for more details. Pass an empty string to unset this value. + """ + tax_id: NotRequired["str"] + """ + The business ID number of the company, as appropriate for the company's country. (Examples are an Employer ID Number in the U.S., a Business Number in Canada, or a Company Number in the UK.) + """ + tax_id_registrar: NotRequired["str"] + """ + The jurisdiction in which the `tax_id` is registered (Germany-based companies only). + """ + vat_id: NotRequired["str"] + """ + The VAT number of the company. + """ + verification: NotRequired[ + "AccountService.UpdateParamsCompanyVerification" + ] + """ + Information on the verification state of the company. + """ + + class UpdateParamsCompanyAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsCompanyAddressKana(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class UpdateParamsCompanyAddressKanji(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class UpdateParamsCompanyOwnershipDeclaration(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the beneficial owner attestation was made. + """ + ip: NotRequired["str"] + """ + The IP address from which the beneficial owner attestation was made. + """ + user_agent: NotRequired["str"] + """ + The user agent of the browser from which the beneficial owner attestation was made. + """ + + class UpdateParamsCompanyVerification(TypedDict): + document: NotRequired[ + "AccountService.UpdateParamsCompanyVerificationDocument" + ] + """ + A document verifying the business. + """ + + class UpdateParamsCompanyVerificationDocument(TypedDict): + back: NotRequired["str"] + """ + The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class UpdateParamsDocuments(TypedDict): + bank_account_ownership_verification: NotRequired[ + "AccountService.UpdateParamsDocumentsBankAccountOwnershipVerification" + ] + """ + One or more documents that support the [Bank account ownership verification](https://support.stripe.com/questions/bank-account-ownership-verification) requirement. Must be a document associated with the account's primary active bank account that displays the last 4 digits of the account number, either a statement or a voided check. + """ + company_license: NotRequired[ + "AccountService.UpdateParamsDocumentsCompanyLicense" + ] + """ + One or more documents that demonstrate proof of a company's license to operate. + """ + company_memorandum_of_association: NotRequired[ + "AccountService.UpdateParamsDocumentsCompanyMemorandumOfAssociation" + ] + """ + One or more documents showing the company's Memorandum of Association. + """ + company_ministerial_decree: NotRequired[ + "AccountService.UpdateParamsDocumentsCompanyMinisterialDecree" + ] + """ + (Certain countries only) One or more documents showing the ministerial decree legalizing the company's establishment. + """ + company_registration_verification: NotRequired[ + "AccountService.UpdateParamsDocumentsCompanyRegistrationVerification" + ] + """ + One or more documents that demonstrate proof of a company's registration with the appropriate local authorities. + """ + company_tax_id_verification: NotRequired[ + "AccountService.UpdateParamsDocumentsCompanyTaxIdVerification" + ] + """ + One or more documents that demonstrate proof of a company's tax ID. + """ + proof_of_registration: NotRequired[ + "AccountService.UpdateParamsDocumentsProofOfRegistration" + ] + """ + One or more documents showing the company's proof of registration with the national business registry. + """ + + class UpdateParamsDocumentsBankAccountOwnershipVerification(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class UpdateParamsDocumentsCompanyLicense(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class UpdateParamsDocumentsCompanyMemorandumOfAssociation(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class UpdateParamsDocumentsCompanyMinisterialDecree(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class UpdateParamsDocumentsCompanyRegistrationVerification(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class UpdateParamsDocumentsCompanyTaxIdVerification(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class UpdateParamsDocumentsProofOfRegistration(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class UpdateParamsIndividual(TypedDict): + address: NotRequired["AccountService.UpdateParamsIndividualAddress"] + """ + The individual's primary address. + """ + address_kana: NotRequired[ + "AccountService.UpdateParamsIndividualAddressKana" + ] + """ + The Kana variation of the the individual's primary address (Japan only). + """ + address_kanji: NotRequired[ + "AccountService.UpdateParamsIndividualAddressKanji" + ] + """ + The Kanji variation of the the individual's primary address (Japan only). + """ + dob: NotRequired[ + "Literal['']|AccountService.UpdateParamsIndividualDob" + ] + """ + The individual's date of birth. + """ + email: NotRequired["str"] + """ + The individual's email address. + """ + first_name: NotRequired["str"] + """ + The individual's first name. + """ + first_name_kana: NotRequired["str"] + """ + The Kana variation of the the individual's first name (Japan only). + """ + first_name_kanji: NotRequired["str"] + """ + The Kanji variation of the individual's first name (Japan only). + """ + full_name_aliases: NotRequired["Literal['']|List[str]"] + """ + A list of alternate names or aliases that the individual is known by. + """ + gender: NotRequired["str"] + """ + The individual's gender (International regulations require either "male" or "female"). + """ + id_number: NotRequired["str"] + """ + The government-issued ID number of the individual, as appropriate for the representative's country. (Examples are a Social Security Number in the U.S., or a Social Insurance Number in Canada). Instead of the number itself, you can also provide a [PII token created with Stripe.js](https://stripe.com/docs/js/tokens/create_token?type=pii). + """ + id_number_secondary: NotRequired["str"] + """ + The government-issued secondary ID number of the individual, as appropriate for the representative's country, will be used for enhanced verification checks. In Thailand, this would be the laser code found on the back of an ID card. Instead of the number itself, you can also provide a [PII token created with Stripe.js](https://stripe.com/docs/js/tokens/create_token?type=pii). + """ + last_name: NotRequired["str"] + """ + The individual's last name. + """ + last_name_kana: NotRequired["str"] + """ + The Kana variation of the individual's last name (Japan only). + """ + last_name_kanji: NotRequired["str"] + """ + The Kanji variation of the individual's last name (Japan only). + """ + maiden_name: NotRequired["str"] + """ + The individual's maiden name. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + phone: NotRequired["str"] + """ + The individual's phone number. + """ + political_exposure: NotRequired["Literal['existing', 'none']"] + """ + Indicates if the person or any of their representatives, family members, or other closely related persons, declares that they hold or have held an important public job or function, in any jurisdiction. + """ + registered_address: NotRequired[ + "AccountService.UpdateParamsIndividualRegisteredAddress" + ] + """ + The individual's registered address. + """ + ssn_last_4: NotRequired["str"] + """ + The last four digits of the individual's Social Security Number (U.S. only). + """ + verification: NotRequired[ + "AccountService.UpdateParamsIndividualVerification" + ] + """ + The individual's verification document information. + """ + + class UpdateParamsIndividualAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsIndividualAddressKana(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class UpdateParamsIndividualAddressKanji(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class UpdateParamsIndividualDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class UpdateParamsIndividualRegisteredAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsIndividualVerification(TypedDict): + additional_document: NotRequired[ + "AccountService.UpdateParamsIndividualVerificationAdditionalDocument" + ] + """ + A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. + """ + document: NotRequired[ + "AccountService.UpdateParamsIndividualVerificationDocument" + ] + """ + An identifying document, either a passport or local ID card. + """ + + class UpdateParamsIndividualVerificationAdditionalDocument(TypedDict): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class UpdateParamsIndividualVerificationDocument(TypedDict): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class UpdateParamsSettings(TypedDict): + bacs_debit_payments: NotRequired[ + "AccountService.UpdateParamsSettingsBacsDebitPayments" + ] + """ + Settings specific to Bacs Direct Debit payments. + """ + branding: NotRequired["AccountService.UpdateParamsSettingsBranding"] + """ + Settings used to apply the account's branding to email receipts, invoices, Checkout, and other products. + """ + card_issuing: NotRequired[ + "AccountService.UpdateParamsSettingsCardIssuing" + ] + """ + Settings specific to the account's use of the Card Issuing product. + """ + card_payments: NotRequired[ + "AccountService.UpdateParamsSettingsCardPayments" + ] + """ + Settings specific to card charging on the account. + """ + payments: NotRequired["AccountService.UpdateParamsSettingsPayments"] + """ + Settings that apply across payment methods for charging on the account. + """ + payouts: NotRequired["AccountService.UpdateParamsSettingsPayouts"] + """ + Settings specific to the account's payouts. + """ + treasury: NotRequired["AccountService.UpdateParamsSettingsTreasury"] + """ + Settings specific to the account's Treasury FinancialAccounts. + """ + + class UpdateParamsSettingsBacsDebitPayments(TypedDict): + display_name: NotRequired["str"] + """ + The Bacs Direct Debit Display Name for this account. For payments made with Bacs Direct Debit, this name appears on the mandate as the statement descriptor. Mobile banking apps display it as the name of the business. To use custom branding, set the Bacs Direct Debit Display Name during or right after creation. Custom branding incurs an additional monthly fee for the platform. If you don't set the display name before requesting Bacs capability, it's automatically set as "Stripe" and the account is onboarded to Stripe branding, which is free. + """ + + class UpdateParamsSettingsBranding(TypedDict): + icon: NotRequired["str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) An icon for the account. Must be square and at least 128px x 128px. + """ + logo: NotRequired["str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A logo for the account that will be used in Checkout instead of the icon and without the account's name next to it if provided. Must be at least 128px x 128px. + """ + primary_color: NotRequired["str"] + """ + A CSS hex color value representing the primary branding color for this account. + """ + secondary_color: NotRequired["str"] + """ + A CSS hex color value representing the secondary branding color for this account. + """ + + class UpdateParamsSettingsCardIssuing(TypedDict): + tos_acceptance: NotRequired[ + "AccountService.UpdateParamsSettingsCardIssuingTosAcceptance" + ] + """ + Details on the account's acceptance of the [Stripe Issuing Terms and Disclosures](https://stripe.com/docs/issuing/connect/tos_acceptance). + """ + + class UpdateParamsSettingsCardIssuingTosAcceptance(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the account representative accepted the service agreement. + """ + ip: NotRequired["str"] + """ + The IP address from which the account representative accepted the service agreement. + """ + user_agent: NotRequired["Literal['']|str"] + """ + The user agent of the browser from which the account representative accepted the service agreement. + """ + + class UpdateParamsSettingsCardPayments(TypedDict): + decline_on: NotRequired[ + "AccountService.UpdateParamsSettingsCardPaymentsDeclineOn" + ] + """ + Automatically declines certain charge types regardless of whether the card issuer accepted or declined the charge. + """ + statement_descriptor_prefix: NotRequired["str"] + """ + The default text that appears on credit card statements when a charge is made. This field prefixes any dynamic `statement_descriptor` specified on the charge. `statement_descriptor_prefix` is useful for maximizing descriptor space for the dynamic portion. + """ + statement_descriptor_prefix_kana: NotRequired["Literal['']|str"] + """ + The Kana variation of the default text that appears on credit card statements when a charge is made (Japan only). This field prefixes any dynamic `statement_descriptor_suffix_kana` specified on the charge. `statement_descriptor_prefix_kana` is useful for maximizing descriptor space for the dynamic portion. + """ + statement_descriptor_prefix_kanji: NotRequired["Literal['']|str"] + """ + The Kanji variation of the default text that appears on credit card statements when a charge is made (Japan only). This field prefixes any dynamic `statement_descriptor_suffix_kanji` specified on the charge. `statement_descriptor_prefix_kanji` is useful for maximizing descriptor space for the dynamic portion. + """ + + class UpdateParamsSettingsCardPaymentsDeclineOn(TypedDict): + avs_failure: NotRequired["bool"] + """ + Whether Stripe automatically declines charges with an incorrect ZIP or postal code. This setting only applies when a ZIP or postal code is provided and they fail bank verification. + """ + cvc_failure: NotRequired["bool"] + """ + Whether Stripe automatically declines charges with an incorrect CVC. This setting only applies when a CVC is provided and it fails bank verification. + """ + + class UpdateParamsSettingsPayments(TypedDict): + statement_descriptor: NotRequired["str"] + """ + The default text that appears on credit card statements when a charge is made. This field prefixes any dynamic `statement_descriptor` specified on the charge. + """ + statement_descriptor_kana: NotRequired["str"] + """ + The Kana variation of the default text that appears on credit card statements when a charge is made (Japan only). + """ + statement_descriptor_kanji: NotRequired["str"] + """ + The Kanji variation of the default text that appears on credit card statements when a charge is made (Japan only). + """ + + class UpdateParamsSettingsPayouts(TypedDict): + debit_negative_balances: NotRequired["bool"] + """ + A Boolean indicating whether Stripe should try to reclaim negative balances from an attached bank account. For details, see [Understanding Connect Account Balances](https://stripe.com/docs/connect/account-balances). + """ + schedule: NotRequired[ + "AccountService.UpdateParamsSettingsPayoutsSchedule" + ] + """ + Details on when funds from charges are available, and when they are paid out to an external account. For details, see our [Setting Bank and Debit Card Payouts](https://stripe.com/docs/connect/bank-transfers#payout-information) documentation. + """ + statement_descriptor: NotRequired["str"] + """ + The text that appears on the bank account statement for payouts. If not set, this defaults to the platform's bank descriptor as set in the Dashboard. + """ + + class UpdateParamsSettingsPayoutsSchedule(TypedDict): + delay_days: NotRequired["Literal['minimum']|int"] + """ + The number of days charge funds are held before being paid out. May also be set to `minimum`, representing the lowest available value for the account country. Default is `minimum`. The `delay_days` parameter remains at the last configured value if `interval` is `manual`. [Learn more about controlling payout delay days](https://stripe.com/docs/connect/manage-payout-schedule). + """ + interval: NotRequired[ + "Literal['daily', 'manual', 'monthly', 'weekly']" + ] + """ + How frequently available funds are paid out. One of: `daily`, `manual`, `weekly`, or `monthly`. Default is `daily`. + """ + monthly_anchor: NotRequired["int"] + """ + The day of the month when available funds are paid out, specified as a number between 1--31. Payouts nominally scheduled between the 29th and 31st of the month are instead sent on the last day of a shorter month. Required and applicable only if `interval` is `monthly`. + """ + weekly_anchor: NotRequired[ + "Literal['friday', 'monday', 'saturday', 'sunday', 'thursday', 'tuesday', 'wednesday']" + ] + """ + The day of the week when available funds are paid out, specified as `monday`, `tuesday`, etc. (required and applicable only if `interval` is `weekly`.) + """ + + class UpdateParamsSettingsTreasury(TypedDict): + tos_acceptance: NotRequired[ + "AccountService.UpdateParamsSettingsTreasuryTosAcceptance" + ] + """ + Details on the account's acceptance of the Stripe Treasury Services Agreement. + """ + + class UpdateParamsSettingsTreasuryTosAcceptance(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the account representative accepted the service agreement. + """ + ip: NotRequired["str"] + """ + The IP address from which the account representative accepted the service agreement. + """ + user_agent: NotRequired["Literal['']|str"] + """ + The user agent of the browser from which the account representative accepted the service agreement. + """ + + class UpdateParamsTosAcceptance(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the account representative accepted their service agreement. + """ + ip: NotRequired["str"] + """ + The IP address from which the account representative accepted their service agreement. + """ + service_agreement: NotRequired["str"] + """ + The user's service agreement type. + """ + user_agent: NotRequired["str"] + """ + The user agent of the browser from which the account representative accepted their service agreement. + """ + + def delete( + self, + account: str, + params: "AccountService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> Account: + """ + With [Connect](https://stripe.com/docs/connect), you can delete accounts you manage. + + Accounts created using test-mode keys can be deleted at any time. Standard accounts created using live-mode keys cannot be deleted. Custom or Express accounts created using live-mode keys can only be deleted once all balances are zero. + + If you want to delete your own account, use the [account information tab in your account settings](https://dashboard.stripe.com/settings/account) instead. + """ + return cast( + Account, + self._requestor.request( + "delete", + "/v1/accounts/{account}".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + account: str, + params: "AccountService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Account: + """ + Retrieves the details of an account. + """ + return cast( + Account, + self._requestor.request( + "get", + "/v1/accounts/{account}".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + account: str, + params: "AccountService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Account: + """ + Updates a [connected account](https://stripe.com/docs/connect/accounts) by setting the values of the parameters passed. Any parameters not provided are + left unchanged. + + For Custom accounts, you can update any information on the account. For other accounts, you can update all information until that + account has started to go through Connect Onboarding. Once you create an [Account Link or Account Session](https://stripe.com/docs/api/account_links), + some properties can only be changed or updated for Custom accounts. + + To update your own account, use the [Dashboard](https://dashboard.stripe.com/settings/account). Refer to our + [Connect](https://stripe.com/docs/connect/updating-accounts) documentation to learn more about updating accounts. + """ + return cast( + Account, + self._requestor.request( + "post", + "/v1/accounts/{account}".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve_current( + self, + params: "AccountService.RetrieveCurrentParams" = {}, + options: RequestOptions = {}, + ) -> Account: + """ + Retrieves the details of an account. + """ + return cast( + Account, + self._requestor.request( + "get", + "/v1/account", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "AccountService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Account]: + """ + Returns a list of accounts connected to your platform via [Connect](https://stripe.com/docs/connect). If you're not a platform, the list is empty. + """ + return cast( + ListObject[Account], + self._requestor.request( + "get", + "/v1/accounts", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "AccountService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Account: + """ + With [Connect](https://stripe.com/docs/connect), you can create Stripe accounts for your users. + To do this, you'll first need to [register your platform](https://dashboard.stripe.com/account/applications/settings). + + If you've already collected information for your connected accounts, you [can prefill that information](https://stripe.com/docs/connect/best-practices#onboarding) when + creating the account. Connect Onboarding won't ask for the prefilled information during account onboarding. + You can prefill any information on the account. + """ + return cast( + Account, + self._requestor.request( + "post", + "/v1/accounts", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def reject( + self, + account: str, + params: "AccountService.RejectParams", + options: RequestOptions = {}, + ) -> Account: + """ + With [Connect](https://stripe.com/docs/connect), you may flag accounts as suspicious. + + Test-mode Custom and Express accounts can be rejected at any time. Accounts created using live-mode keys may only be rejected once all balances are zero. + """ + return cast( + Account, + self._requestor.request( + "post", + "/v1/accounts/{account}/reject".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_account_session.py b/stripe/_account_session.py index caae3c662..f439c0f0a 100644 --- a/stripe/_account_session.py +++ b/stripe/_account_session.py @@ -3,7 +3,7 @@ from stripe._createable_api_resource import CreateableAPIResource from stripe._request_options import RequestOptions from stripe._stripe_object import StripeObject -from typing import ClassVar, List, Optional, cast +from typing import ClassVar, List, cast from typing_extensions import Literal, NotRequired, TypedDict, Unpack @@ -266,14 +266,7 @@ class CreateParamsComponentsPayoutsFeatures(TypedDict): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "AccountSession.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["AccountSession.CreateParams"] ) -> "AccountSession": """ Creates a AccountSession object that includes a single-use token that the platform can use on their front-end to grant client-side API access. @@ -283,10 +276,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) diff --git a/stripe/_account_session_service.py b/stripe/_account_session_service.py new file mode 100644 index 000000000..3eb209daf --- /dev/null +++ b/stripe/_account_session_service.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._account_session import AccountSession +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class AccountSessionService(StripeService): + class CreateParams(TypedDict): + account: str + """ + The identifier of the account to create an Account Session for. + """ + components: "AccountSessionService.CreateParamsComponents" + """ + Each key of the dictionary represents an embedded component, and each embedded component maps to its configuration (e.g. whether it has been enabled or not). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CreateParamsComponents(TypedDict): + account_onboarding: NotRequired[ + "AccountSessionService.CreateParamsComponentsAccountOnboarding" + ] + """ + Configuration for the account onboarding embedded component. + """ + payment_details: NotRequired[ + "AccountSessionService.CreateParamsComponentsPaymentDetails" + ] + """ + Configuration for the payment details embedded component. + """ + payments: NotRequired[ + "AccountSessionService.CreateParamsComponentsPayments" + ] + """ + Configuration for the payments embedded component. + """ + payouts: NotRequired[ + "AccountSessionService.CreateParamsComponentsPayouts" + ] + """ + Configuration for the payouts embedded component. + """ + + class CreateParamsComponentsAccountOnboarding(TypedDict): + enabled: bool + """ + Whether the embedded component is enabled. + """ + features: NotRequired[ + "AccountSessionService.CreateParamsComponentsAccountOnboardingFeatures" + ] + """ + The list of features enabled in the embedded component. + """ + + class CreateParamsComponentsAccountOnboardingFeatures(TypedDict): + pass + + class CreateParamsComponentsPaymentDetails(TypedDict): + enabled: bool + """ + Whether the embedded component is enabled. + """ + features: NotRequired[ + "AccountSessionService.CreateParamsComponentsPaymentDetailsFeatures" + ] + """ + The list of features enabled in the embedded component. + """ + + class CreateParamsComponentsPaymentDetailsFeatures(TypedDict): + capture_payments: NotRequired["bool"] + """ + Whether to allow capturing and cancelling payment intents. This is `true` by default. + """ + dispute_management: NotRequired["bool"] + """ + Whether to allow responding to disputes, including submitting evidence and accepting disputes. This is `true` by default. + """ + refund_management: NotRequired["bool"] + """ + Whether to allow sending refunds. This is `true` by default. + """ + + class CreateParamsComponentsPayments(TypedDict): + enabled: bool + """ + Whether the embedded component is enabled. + """ + features: NotRequired[ + "AccountSessionService.CreateParamsComponentsPaymentsFeatures" + ] + """ + The list of features enabled in the embedded component. + """ + + class CreateParamsComponentsPaymentsFeatures(TypedDict): + capture_payments: NotRequired["bool"] + """ + Whether to allow capturing and cancelling payment intents. This is `true` by default. + """ + dispute_management: NotRequired["bool"] + """ + Whether to allow responding to disputes, including submitting evidence and accepting disputes. This is `true` by default. + """ + refund_management: NotRequired["bool"] + """ + Whether to allow sending refunds. This is `true` by default. + """ + + class CreateParamsComponentsPayouts(TypedDict): + enabled: bool + """ + Whether the embedded component is enabled. + """ + features: NotRequired[ + "AccountSessionService.CreateParamsComponentsPayoutsFeatures" + ] + """ + The list of features enabled in the embedded component. + """ + + class CreateParamsComponentsPayoutsFeatures(TypedDict): + edit_payout_schedule: NotRequired["bool"] + """ + Whether to allow payout schedule to be changed. Default `true` when Stripe owns Loss Liability, default `false` otherwise. + """ + instant_payouts: NotRequired["bool"] + """ + Whether to allow creation of instant payouts. Default `true` when Stripe owns Loss Liability, default `false` otherwise. + """ + standard_payouts: NotRequired["bool"] + """ + Whether to allow creation of standard payouts. Default `true` when Stripe owns Loss Liability, default `false` otherwise. + """ + + def create( + self, + params: "AccountSessionService.CreateParams", + options: RequestOptions = {}, + ) -> AccountSession: + """ + Creates a AccountSession object that includes a single-use token that the platform can use on their front-end to grant client-side API access. + """ + return cast( + AccountSession, + self._requestor.request( + "post", + "/v1/account_sessions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_api_mode.py b/stripe/_api_mode.py new file mode 100644 index 000000000..37e5530bd --- /dev/null +++ b/stripe/_api_mode.py @@ -0,0 +1,4 @@ +from typing_extensions import Literal + + +ApiMode = Literal["V1", "V1FILES"] diff --git a/stripe/_api_requestor.py b/stripe/_api_requestor.py index 771bf3652..fe75e0f0b 100644 --- a/stripe/_api_requestor.py +++ b/stripe/_api_requestor.py @@ -8,82 +8,139 @@ Mapping, Optional, Tuple, + Union, cast, + ClassVar, ) -from typing_extensions import NoReturn +from typing_extensions import TYPE_CHECKING, Literal, NoReturn, Unpack import uuid -import warnings +from urllib.parse import urlsplit, urlunsplit # breaking circular dependency import stripe # noqa: IMP101 -from stripe import _http_client, _util, _version -from stripe import oauth_error # noqa: SPY101 -from stripe._encode import _api_encode +from stripe._util import ( + log_debug, + log_info, + dashboard_link, + _convert_to_stripe_object, +) +from stripe._version import VERSION +import stripe._error as error +import stripe.oauth_error as oauth_error from stripe._multipart_data_generator import MultipartDataGenerator -from urllib.parse import urlencode, urlsplit, urlunsplit +from urllib.parse import urlencode +from stripe._encode import ( + _api_encode, +) from stripe._stripe_response import StripeResponse, StripeStreamResponse +from stripe._request_options import RequestOptions, merge_options +from stripe._requestor_options import ( + RequestorOptions, + _GlobalRequestorOptions, +) +from stripe._http_client import HTTPClient, new_default_http_client +from stripe._app_info import AppInfo +from stripe._base_address import BaseAddress +from stripe._api_mode import ApiMode -def _build_api_url(url, query): - scheme, netloc, path, base_query, fragment = urlsplit(url) +if TYPE_CHECKING: + from stripe._stripe_object import StripeObject - if base_query: - query = "%s&%s" % (base_query, query) +HttpVerb = Literal["get", "post", "delete"] - return urlunsplit((scheme, netloc, path, query, fragment)) +# Lazily initialized +_default_proxy: Optional[str] = None -class APIRequestor(object): - api_key: Optional[str] - api_base: str - api_version: str - stripe_account: Optional[str] +class _APIRequestor(object): + _instance: ClassVar["_APIRequestor|None"] = None def __init__( self, - key=None, - client=None, - api_base=None, - api_version=None, - account=None, + options: RequestorOptions = RequestorOptions(), + client: Optional[HTTPClient] = None, ): - self.api_base = api_base or stripe.api_base - self.api_key = key - self.api_version = api_version or stripe.api_version - self.stripe_account = account - - self._default_proxy = None - - from stripe import verify_ssl_certs as verify - from stripe import proxy + self._options = options + self._client = client + + # In the case of client=None, we should use the current value of stripe.default_http_client + # or lazily initialize it. Since stripe.default_http_client can change throughout the lifetime of + # an _APIRequestor, we shouldn't set it as stripe._client and should access it only through this + # getter. + def _get_http_client(self) -> HTTPClient: + client = self._client + if client is None: + global _default_proxy + + if not stripe.default_http_client: + # If the stripe.default_http_client has not been set by the user + # yet, we'll set it here. This way, we aren't creating a new + # HttpClient for every request. + stripe.default_http_client = new_default_http_client( + verify_ssl_certs=stripe.verify_ssl_certs, + proxy=stripe.proxy, + ) + _default_proxy = stripe.proxy + elif stripe.proxy != _default_proxy: + import warnings - if client: - self._client = client - elif stripe.default_http_client: - self._client = stripe.default_http_client - if proxy != self._default_proxy: warnings.warn( "stripe.proxy was updated after sending a " "request - this is a no-op. To use a different proxy, " "set stripe.default_http_client to a new client " "configured with the proxy." ) - else: - # If the stripe.default_http_client has not been set by the user - # yet, we'll set it here. This way, we aren't creating a new - # HttpClient for every request. - stripe.default_http_client = _http_client.new_default_http_client( - verify_ssl_certs=verify, proxy=proxy - ) - self._client = stripe.default_http_client - self._default_proxy = proxy + + assert stripe.default_http_client is not None + return stripe.default_http_client + return client + + def _replace_options( + self, options: Optional[RequestOptions] + ) -> "_APIRequestor": + options = options or {} + new_options = self._options.to_dict() + for key in ["api_key", "stripe_account", "stripe_version"]: + if key in options and options[key] is not None: + new_options[key] = options[key] + return _APIRequestor( + options=RequestorOptions(**new_options), client=self._client + ) + + @property + def api_key(self): + return self._options.api_key + + @property + def stripe_account(self): + return self._options.stripe_account + + @property + def stripe_version(self): + return self._options.stripe_version + + @property + def base_addresses(self): + return self._options.base_addresses @classmethod - @_util.deprecated( - "This method is internal to stripe-python and the public interface will be removed in a future stripe-python version" - ) - def format_app_info(cls, info): - return cls._format_app_info(info) + def _global_instance(cls): + """ + Returns the singleton instance of _APIRequestor, to be used when + calling a static method such as stripe.Customer.create(...) + """ + + # Lazily initialize. + if cls._instance is None: + cls._instance = cls(options=_GlobalRequestorOptions(), client=None) + return cls._instance + + @staticmethod + def _global_with_options( + **params: Unpack[RequestOptions], + ) -> "_APIRequestor": + return _APIRequestor._global_instance()._replace_options(params) @classmethod def _format_app_info(cls, info): @@ -99,52 +156,67 @@ def request( method: str, url: str, params: Optional[Mapping[str, Any]] = None, - headers: Optional[Mapping[str, str]] = None, + options: Optional[RequestOptions] = None, *, + base_address: BaseAddress, + api_mode: ApiMode, _usage: Optional[List[str]] = None, - ) -> Tuple[StripeResponse, str]: - rbody, rcode, rheaders, my_api_key = self.request_raw( + ) -> "StripeObject": + requestor = self._replace_options(options) + rbody, rcode, rheaders = requestor.request_raw( method.lower(), url, params, - headers, is_streaming=False, + api_mode=api_mode, + base_address=base_address, + options=options, _usage=_usage, ) - resp = self.interpret_response(rbody, rcode, rheaders) - return resp, my_api_key + resp = requestor._interpret_response(rbody, rcode, rheaders) + + return _convert_to_stripe_object( + resp=resp, + params=params, + requestor=requestor, + api_mode=api_mode, + ) def request_stream( self, method: str, url: str, params: Optional[Mapping[str, Any]] = None, - headers: Optional[Mapping[str, str]] = None, + options: Optional[RequestOptions] = None, *, + base_address: BaseAddress, + api_mode: ApiMode, _usage: Optional[List[str]] = None, - ) -> Tuple[StripeStreamResponse, str]: - stream, rcode, rheaders, my_api_key = self.request_raw( + ) -> StripeStreamResponse: + stream, rcode, rheaders = self.request_raw( method.lower(), url, params, - headers, is_streaming=True, + api_mode=api_mode, + base_address=base_address, + options=options, _usage=_usage, ) - resp = self.interpret_streaming_response( + resp = self._interpret_streaming_response( # TODO: should be able to remove this cast once self._client.request_stream_with_retries # returns a more specific type. cast(IOBase, stream), rcode, rheaders, ) - return resp, my_api_key + return resp def handle_error_response(self, rbody, rcode, resp, rheaders) -> NoReturn: try: error_data = resp["error"] except (KeyError, TypeError): - raise stripe.APIError( + raise error.APIError( "Invalid response object from API: %r (HTTP response code " "was %d)" % (rbody, rcode), rbody, @@ -170,7 +242,7 @@ def handle_error_response(self, rbody, rcode, resp, rheaders) -> NoReturn: raise err def specific_api_error(self, rbody, rcode, resp, rheaders, error_data): - _util.log_info( + log_info( "Stripe API error received", error_code=error_data.get("code"), error_type=error_data.get("type"), @@ -182,16 +254,16 @@ def specific_api_error(self, rbody, rcode, resp, rheaders, error_data): if rcode == 429 or ( rcode == 400 and error_data.get("code") == "rate_limit" ): - return stripe.RateLimitError( + return error.RateLimitError( error_data.get("message"), rbody, rcode, resp, rheaders ) elif rcode in [400, 404]: if error_data.get("type") == "idempotency_error": - return stripe.IdempotencyError( + return error.IdempotencyError( error_data.get("message"), rbody, rcode, resp, rheaders ) else: - return stripe.InvalidRequestError( + return error.InvalidRequestError( error_data.get("message"), error_data.get("param"), error_data.get("code"), @@ -201,11 +273,11 @@ def specific_api_error(self, rbody, rcode, resp, rheaders, error_data): rheaders, ) elif rcode == 401: - return stripe.AuthenticationError( + return error.AuthenticationError( error_data.get("message"), rbody, rcode, resp, rheaders ) elif rcode == 402: - return stripe.CardError( + return error.CardError( error_data.get("message"), error_data.get("param"), error_data.get("code"), @@ -215,18 +287,18 @@ def specific_api_error(self, rbody, rcode, resp, rheaders, error_data): rheaders, ) elif rcode == 403: - return stripe.PermissionError( + return error.PermissionError( error_data.get("message"), rbody, rcode, resp, rheaders ) else: - return stripe.APIError( + return error.APIError( error_data.get("message"), rbody, rcode, resp, rheaders ) def specific_oauth_error(self, rbody, rcode, resp, rheaders, error_code): description = resp.get("error_description", error_code) - _util.log_info( + log_info( "Stripe OAuth error received", error_code=error_code, error_description=description, @@ -249,16 +321,16 @@ def specific_oauth_error(self, rbody, rcode, resp, rheaders, error_code): return None - def request_headers(self, api_key, method): - user_agent = "Stripe/v1 PythonBindings/%s" % (_version.VERSION,) + def request_headers(self, method, options: RequestOptions): + user_agent = "Stripe/v1 PythonBindings/%s" % (VERSION,) if stripe.app_info: user_agent += " " + self._format_app_info(stripe.app_info) - ua = { - "bindings_version": _version.VERSION, + ua: Dict[str, Union[str, AppInfo]] = { + "bindings_version": VERSION, "lang": "python", "publisher": "stripe", - "httplib": self._client.name, + "httplib": self._get_http_client().name, } for attr, func in [ ["lang_version", platform.python_version], @@ -273,20 +345,24 @@ def request_headers(self, api_key, method): if stripe.app_info: ua["application"] = stripe.app_info - headers = { + headers: Dict[str, Optional[str]] = { "X-Stripe-Client-User-Agent": json.dumps(ua), "User-Agent": user_agent, - "Authorization": "Bearer %s" % (api_key,), + "Authorization": "Bearer %s" % (options.get("api_key"),), } - if self.stripe_account: - headers["Stripe-Account"] = self.stripe_account + if options.get("stripe_account"): + headers["Stripe-Account"] = options.get("stripe_account") + + if options.get("idempotency_key"): + headers["Idempotency-Key"] = options.get("idempotency_key") if method == "post": - headers["Content-Type"] = "application/x-www-form-urlencoded" headers.setdefault("Idempotency-Key", str(uuid.uuid4())) + headers["Content-Type"] = "application/x-www-form-urlencoded" - headers["Stripe-Version"] = self.api_version + if options.get("stripe_version"): + headers["Stripe-Version"] = options.get("stripe_version") return headers @@ -295,28 +371,20 @@ def request_raw( method: str, url: str, params: Optional[Mapping[str, Any]] = None, - supplied_headers: Optional[Mapping[str, str]] = None, + options: Optional[RequestOptions] = None, is_streaming: bool = False, *, + base_address: BaseAddress, + api_mode: ApiMode, _usage: Optional[List[str]] = None, - ) -> Tuple[object, int, Mapping[str, str], str]: + ) -> Tuple[object, int, Mapping[str, str]]: """ Mechanism for issuing an API call """ + request_options = merge_options(self._options, options) - supplied_headers_dict: Optional[Dict[str, str]] = ( - dict(supplied_headers) if supplied_headers is not None else None - ) - - if self.api_key: - my_api_key = self.api_key - else: - from stripe import api_key - - my_api_key = api_key - - if my_api_key is None: - raise stripe.AuthenticationError( + if request_options.get("api_key") is None: + raise error.AuthenticationError( "No API key provided. (HINT: set your API key using " '"stripe.api_key = "). You can generate API keys ' "from the Stripe web interface. See https://stripe.com/api " @@ -324,7 +392,10 @@ def request_raw( "questions." ) - abs_url = "%s%s" % (self.api_base, url) + abs_url = "%s%s" % ( + self._options.base_addresses.get(base_address), + url, + ) encoded_params = urlencode(list(_api_encode(params or {}))) @@ -333,41 +404,53 @@ def request_raw( # makes these parameter strings easier to read. encoded_params = encoded_params.replace("%5B", "[").replace("%5D", "]") + encoded_body = encoded_params + + supplied_headers = None + if ( + "headers" in request_options + and request_options["headers"] is not None + ): + supplied_headers = dict(request_options["headers"]) + + headers = self.request_headers(method, request_options) + if method == "get" or method == "delete": if params: - abs_url = _build_api_url(abs_url, encoded_params) + query = encoded_params + scheme, netloc, path, base_query, fragment = urlsplit(abs_url) + + if base_query: + query = "%s&%s" % (base_query, query) + + abs_url = urlunsplit((scheme, netloc, path, query, fragment)) post_data = None elif method == "post": - if ( - supplied_headers_dict is not None - and supplied_headers_dict.get("Content-Type") - == "multipart/form-data" - ): + if api_mode == "V1FILES": generator = MultipartDataGenerator() generator.add_params(params or {}) post_data = generator.get_post_data() - supplied_headers_dict[ + headers[ "Content-Type" ] = "multipart/form-data; boundary=%s" % (generator.boundary,) else: - post_data = encoded_params + post_data = encoded_body else: - raise stripe.APIConnectionError( + raise error.APIConnectionError( "Unrecognized HTTP method %r. This may indicate a bug in the " "Stripe bindings. Please contact support@stripe.com for " "assistance." % (method,) ) - headers = self.request_headers(my_api_key, method) - if supplied_headers_dict is not None: - for key, value in supplied_headers_dict.items(): + if supplied_headers is not None: + for key, value in supplied_headers.items(): headers[key] = value - _util.log_info("Request to Stripe api", method=method, path=abs_url) - _util.log_debug( + log_info("Request to Stripe api", method=method, url=abs_url) + log_debug( "Post details", post_data=encoded_params, - api_version=self.api_version, + api_version=request_options.get("stripe_version"), ) if is_streaming: @@ -375,33 +458,48 @@ def request_raw( rcontent, rcode, rheaders, - ) = self._client.request_stream_with_retries( - method, abs_url, headers, post_data, _usage=_usage + ) = self._get_http_client().request_stream_with_retries( + method, + abs_url, + headers, + post_data, + max_network_retries=request_options.get("max_network_retries"), + _usage=_usage, ) else: - rcontent, rcode, rheaders = self._client.request_with_retries( - method, abs_url, headers, post_data, _usage=_usage + ( + rcontent, + rcode, + rheaders, + ) = self._get_http_client().request_with_retries( + method, + abs_url, + headers, + post_data, + max_network_retries=request_options.get("max_network_retries"), + _usage=_usage, ) - _util.log_info( - "Stripe API response", path=abs_url, response_code=rcode - ) - _util.log_debug("API response body", body=rcontent) + log_info("Stripe API response", path=abs_url, response_code=rcode) + log_debug("API response body", body=rcontent) if "Request-Id" in rheaders: request_id = rheaders["Request-Id"] - _util.log_debug( + log_debug( "Dashboard link for request", - link=_util.dashboard_link(request_id), + link=dashboard_link(request_id), ) - return rcontent, rcode, rheaders, my_api_key + return rcontent, rcode, rheaders def _should_handle_code_as_error(self, rcode): return not 200 <= rcode < 300 - def interpret_response( - self, rbody: object, rcode: int, rheaders: Mapping[str, str] + def _interpret_response( + self, + rbody: object, + rcode: int, + rheaders: Mapping[str, str], ) -> StripeResponse: try: if hasattr(rbody, "decode"): @@ -414,7 +512,7 @@ def interpret_response( rheaders, ) except Exception: - raise stripe.APIError( + raise error.APIError( "Invalid response body from API: %s " "(HTTP response code was %d)" % (rbody, rcode), cast(bytes, rbody), @@ -425,8 +523,11 @@ def interpret_response( self.handle_error_response(rbody, rcode, resp.data, rheaders) return resp - def interpret_streaming_response( - self, stream: IOBase, rcode: int, rheaders: Mapping[str, str] + def _interpret_streaming_response( + self, + stream: IOBase, + rcode: int, + rheaders: Mapping[str, str], ) -> StripeStreamResponse: # Streaming response are handled with minimal processing for the success # case (ie. we don't want to read the content). When an error is @@ -443,10 +544,10 @@ def interpret_streaming_response( "can be consumed when streaming a response." ) - self.interpret_response(json_content, rcode, rheaders) - # interpret_response is guaranteed to throw since we've checked self._should_handle_code_as_error + self._interpret_response(json_content, rcode, rheaders) + # _interpret_response is guaranteed to throw since we've checked self._should_handle_code_as_error raise RuntimeError( - "interpret_response should have raised an error" + "_interpret_response should have raised an error" ) else: return StripeStreamResponse(stream, rcode, rheaders) diff --git a/stripe/_api_resource.py b/stripe/_api_resource.py index fbe9215b9..1581e292a 100644 --- a/stripe/_api_resource.py +++ b/stripe/_api_resource.py @@ -1,19 +1,16 @@ from typing_extensions import Literal, Self from stripe._error import InvalidRequestError -from stripe._util import ( - read_special_variable, - populate_headers, - convert_to_stripe_object, -) -from stripe._api_requestor import APIRequestor from stripe._stripe_object import StripeObject +from stripe._request_options import extract_options_from_dict +from stripe._api_mode import ApiMode +from stripe._base_address import BaseAddress +from stripe._api_requestor import _APIRequestor from stripe import _util from urllib.parse import quote_plus from typing import ( Any, ClassVar, - Dict, Generic, List, Optional, @@ -22,7 +19,6 @@ Mapping, ) - T = TypeVar("T", bound=StripeObject) @@ -33,8 +29,8 @@ class APIResource(StripeObject, Generic[T]): @_util.deprecated( "This method is deprecated and will be removed in a future version of stripe-python. Child classes of APIResource should define their own `retrieve` and use APIResource._request directly." ) - def retrieve(cls, id, api_key=None, **params) -> T: - instance = cls(id, api_key, **params) + def retrieve(cls, id, **params) -> T: + instance = cls(id, **params) instance.refresh() return cast(T, instance) @@ -74,27 +70,22 @@ def _request( self, method_, url_, - api_key=None, - idempotency_key=None, - stripe_version=None, - stripe_account=None, - headers=None, params=None, + *, + base_address: BaseAddress = "api", + api_mode: ApiMode = "V1", ) -> StripeObject: obj = StripeObject._request( self, method_, url_, - api_key, - idempotency_key, - stripe_version, - stripe_account, - headers, - params, + params=params, + base_address=base_address, + api_mode=api_mode, ) if type(self) is type(obj): - self.refresh_from(obj) + self._refresh_from(values=obj, api_mode=api_mode) return self else: return obj @@ -105,28 +96,23 @@ def _request_and_refresh( self, method_: Literal["get", "post", "delete"], url_: str, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - headers: Optional[Dict[str, str]] = None, params: Optional[Mapping[str, Any]] = None, _usage: Optional[List[str]] = None, + *, + base_address: BaseAddress = "api", + api_mode: ApiMode = "V1", ) -> Self: obj = StripeObject._request( self, method_, url_, - api_key, - idempotency_key, - stripe_version, - stripe_account, - headers, - params, + params=params, + base_address=base_address, + api_mode=api_mode, _usage=_usage, ) - self.refresh_from(obj) + self._refresh_from(values=obj, api_mode=api_mode) return self # The `method_` and `url_` arguments are suffixed with an underscore to @@ -136,36 +122,19 @@ def _static_request( cls, method_, url_, - api_key=None, - idempotency_key=None, - stripe_version=None, - stripe_account=None, - params=None, + params: Optional[Mapping[str, Any]] = None, + *, + base_address: BaseAddress = "api", + api_mode: ApiMode = "V1", ): - params = None if params is None else params.copy() - api_key = read_special_variable(params, "api_key", api_key) - idempotency_key = read_special_variable( - params, "idempotency_key", idempotency_key - ) - stripe_version = read_special_variable( - params, "stripe_version", stripe_version - ) - stripe_account = read_special_variable( - params, "stripe_account", stripe_account - ) - headers = read_special_variable(params, "headers", None) - - requestor = APIRequestor( - api_key, api_version=stripe_version, account=stripe_account - ) - - if idempotency_key is not None: - headers = {} if headers is None else headers.copy() - headers.update(populate_headers(idempotency_key)) - - response, api_key = requestor.request(method_, url_, params, headers) - return convert_to_stripe_object( - response, api_key, stripe_version, stripe_account, params + request_options, request_params = extract_options_from_dict(params) + return _APIRequestor._global_instance().request( + method_, + url_, + params=request_params, + options=request_options, + base_address=base_address, + api_mode=api_mode, ) # The `method_` and `url_` arguments are suffixed with an underscore to @@ -175,32 +144,17 @@ def _static_request_stream( cls, method_, url_, - api_key=None, - idempotency_key=None, - stripe_version=None, - stripe_account=None, params=None, + *, + base_address: BaseAddress = "api", + api_mode: ApiMode = "V1", ): - params = None if params is None else params.copy() - api_key = read_special_variable(params, "api_key", api_key) - idempotency_key = read_special_variable( - params, "idempotency_key", idempotency_key - ) - stripe_version = read_special_variable( - params, "stripe_version", stripe_version - ) - stripe_account = read_special_variable( - params, "stripe_account", stripe_account - ) - headers = read_special_variable(params, "headers", None) - - requestor = APIRequestor( - api_key, api_version=stripe_version, account=stripe_account + request_options, request_params = extract_options_from_dict(params) + return _APIRequestor._global_instance().request_stream( + method_, + url_, + params=request_params, + options=request_options, + base_address=base_address, + api_mode=api_mode, ) - - if idempotency_key is not None: - headers = {} if headers is None else headers.copy() - headers.update(populate_headers(idempotency_key)) - - response, _ = requestor.request_stream(method_, url_, params, headers) - return response diff --git a/stripe/_apple_pay_domain.py b/stripe/_apple_pay_domain.py index c400be894..553279c94 100644 --- a/stripe/_apple_pay_domain.py +++ b/stripe/_apple_pay_domain.py @@ -77,14 +77,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ApplePayDomain.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ApplePayDomain.CreateParams"] ) -> "ApplePayDomain": """ Create an apple pay domain. @@ -94,10 +87,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -149,13 +138,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ApplePayDomain.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ApplePayDomain.ListParams"] ) -> ListObject["ApplePayDomain"]: """ List apple pay domains. @@ -163,9 +146,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_apple_pay_domain_service.py b/stripe/_apple_pay_domain_service.py new file mode 100644 index 000000000..a8aa554d8 --- /dev/null +++ b/stripe/_apple_pay_domain_service.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._apple_pay_domain import ApplePayDomain +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class ApplePayDomainService(StripeService): + class CreateParams(TypedDict): + domain_name: str + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + domain_name: NotRequired["str"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def delete( + self, + domain: str, + params: "ApplePayDomainService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> ApplePayDomain: + """ + Delete an apple pay domain. + """ + return cast( + ApplePayDomain, + self._requestor.request( + "delete", + "/v1/apple_pay/domains/{domain}".format( + domain=_util.sanitize_id(domain), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + domain: str, + params: "ApplePayDomainService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> ApplePayDomain: + """ + Retrieve an apple pay domain. + """ + return cast( + ApplePayDomain, + self._requestor.request( + "get", + "/v1/apple_pay/domains/{domain}".format( + domain=_util.sanitize_id(domain), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "ApplePayDomainService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[ApplePayDomain]: + """ + List apple pay domains. + """ + return cast( + ListObject[ApplePayDomain], + self._requestor.request( + "get", + "/v1/apple_pay/domains", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "ApplePayDomainService.CreateParams", + options: RequestOptions = {}, + ) -> ApplePayDomain: + """ + Create an apple pay domain. + """ + return cast( + ApplePayDomain, + self._requestor.request( + "post", + "/v1/apple_pay/domains", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_application_fee.py b/stripe/_application_fee.py index 50949ace1..ef0a2c7da 100644 --- a/stripe/_application_fee.py +++ b/stripe/_application_fee.py @@ -196,13 +196,7 @@ class RetrieveRefundParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ApplicationFee.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ApplicationFee.ListParams"] ) -> ListObject["ApplicationFee"]: """ Returns a list of application fees you've previously collected. The application fees are returned in sorted order, with the most recent fees appearing first. @@ -210,9 +204,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -226,14 +217,7 @@ def list( @classmethod def _cls_refund( - cls, - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ApplicationFee.RefundParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, id: str, **params: Unpack["ApplicationFee.RefundParams"] ) -> "ApplicationFeeRefund": """ Refunds an application fee that has previously been collected but not yet refunded. @@ -253,9 +237,6 @@ def _cls_refund( "/v1/application_fees/{id}/refunds".format( id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -263,13 +244,7 @@ def _cls_refund( @overload @staticmethod def refund( - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ApplicationFee.RefundParams" - ] # pyright: ignore[reportGeneralTypeIssues] + id: str, **params: Unpack["ApplicationFee.RefundParams"] ) -> "ApplicationFeeRefund": """ Refunds an application fee that has previously been collected but not yet refunded. @@ -286,11 +261,7 @@ def refund( @overload def refund( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "ApplicationFee.RefundParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["ApplicationFee.RefundParams"] ) -> "ApplicationFeeRefund": """ Refunds an application fee that has previously been collected but not yet refunded. @@ -307,11 +278,7 @@ def refund( @class_method_variant("_cls_refund") def refund( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "ApplicationFee.RefundParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["ApplicationFee.RefundParams"] ) -> "ApplicationFeeRefund": """ Refunds an application fee that has previously been collected but not yet refunded. @@ -331,7 +298,6 @@ def refund( # pyright: ignore[reportGeneralTypeIssues] "/v1/application_fees/{id}/refunds".format( id=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -349,14 +315,7 @@ def retrieve( @classmethod def create_refund( - cls, - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ApplicationFee.CreateRefundParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, id: str, **params: Unpack["ApplicationFee.CreateRefundParams"] ) -> "ApplicationFeeRefund": """ Refunds an application fee that has previously been collected but not yet refunded. @@ -376,9 +335,6 @@ def create_refund( "/v1/application_fees/{id}/refunds".format( id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -388,12 +344,7 @@ def retrieve_refund( cls, fee: str, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ApplicationFee.RetrieveRefundParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["ApplicationFee.RetrieveRefundParams"] ) -> "ApplicationFeeRefund": """ By default, you can see the 10 most recent refunds stored directly on the application fee object, but you can also retrieve details about a specific refund stored on the application fee. @@ -405,9 +356,6 @@ def retrieve_refund( "/v1/application_fees/{fee}/refunds/{id}".format( fee=_util.sanitize_id(fee), id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -417,12 +365,7 @@ def modify_refund( cls, fee: str, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ApplicationFee.ModifyRefundParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["ApplicationFee.ModifyRefundParams"] ) -> "ApplicationFeeRefund": """ Updates the specified application fee refund by setting the values of the parameters passed. Any parameters not provided will be left unchanged. @@ -436,23 +379,13 @@ def modify_refund( "/v1/application_fees/{fee}/refunds/{id}".format( fee=_util.sanitize_id(fee), id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def list_refunds( - cls, - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ApplicationFee.ListRefundsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, id: str, **params: Unpack["ApplicationFee.ListRefundsParams"] ) -> ListObject["ApplicationFeeRefund"]: """ You can see a list of the refunds belonging to a specific application fee. Note that the 10 most recent refunds are always available by default on the application fee object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page through additional refunds. @@ -464,9 +397,6 @@ def list_refunds( "/v1/application_fees/{id}/refunds".format( id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) diff --git a/stripe/_application_fee_refund.py b/stripe/_application_fee_refund.py index ca7fa6c4d..556c2a71f 100644 --- a/stripe/_application_fee_refund.py +++ b/stripe/_application_fee_refund.py @@ -73,7 +73,7 @@ def instance_url(self): return self._build_instance_url(self.fee, self.id) @classmethod - def retrieve(cls, id, api_key=None, **params) -> "ApplicationFeeRefund": + def retrieve(cls, id, **params) -> "ApplicationFeeRefund": raise NotImplementedError( "Can't retrieve a refund without an application fee ID. " "Use application_fee.refunds.retrieve('refund_id') instead." diff --git a/stripe/_application_fee_refund_service.py b/stripe/_application_fee_refund_service.py new file mode 100644 index 000000000..91eed41be --- /dev/null +++ b/stripe/_application_fee_refund_service.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._application_fee_refund import ApplicationFeeRefund +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ApplicationFeeRefundService(StripeService): + class CreateParams(TypedDict): + amount: NotRequired["int"] + """ + A positive integer, in _cents (or local equivalent)_, representing how much of this fee to refund. Can refund only up to the remaining unrefunded amount of the fee. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + def retrieve( + self, + fee: str, + id: str, + params: "ApplicationFeeRefundService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> ApplicationFeeRefund: + """ + By default, you can see the 10 most recent refunds stored directly on the application fee object, but you can also retrieve details about a specific refund stored on the application fee. + """ + return cast( + ApplicationFeeRefund, + self._requestor.request( + "get", + "/v1/application_fees/{fee}/refunds/{id}".format( + fee=_util.sanitize_id(fee), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + fee: str, + id: str, + params: "ApplicationFeeRefundService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> ApplicationFeeRefund: + """ + Updates the specified application fee refund by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + + This request only accepts metadata as an argument. + """ + return cast( + ApplicationFeeRefund, + self._requestor.request( + "post", + "/v1/application_fees/{fee}/refunds/{id}".format( + fee=_util.sanitize_id(fee), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + id: str, + params: "ApplicationFeeRefundService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[ApplicationFeeRefund]: + """ + You can see a list of the refunds belonging to a specific application fee. Note that the 10 most recent refunds are always available by default on the application fee object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page through additional refunds. + """ + return cast( + ListObject[ApplicationFeeRefund], + self._requestor.request( + "get", + "/v1/application_fees/{id}/refunds".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + id: str, + params: "ApplicationFeeRefundService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> ApplicationFeeRefund: + """ + Refunds an application fee that has previously been collected but not yet refunded. + Funds will be refunded to the Stripe account from which the fee was originally collected. + + You can optionally refund only part of an application fee. + You can do so multiple times, until the entire fee has been refunded. + + Once entirely refunded, an application fee can't be refunded again. + This method will raise an error when called on an already-refunded application fee, + or when trying to refund more money than is left on an application fee. + """ + return cast( + ApplicationFeeRefund, + self._requestor.request( + "post", + "/v1/application_fees/{id}/refunds".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_application_fee_service.py b/stripe/_application_fee_service.py new file mode 100644 index 000000000..3e41d3b66 --- /dev/null +++ b/stripe/_application_fee_service.py @@ -0,0 +1,104 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._application_fee import ApplicationFee +from stripe._application_fee_refund_service import ApplicationFeeRefundService +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class ApplicationFeeService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.refunds = ApplicationFeeRefundService(self._requestor) + + class ListParams(TypedDict): + charge: NotRequired["str"] + """ + Only return application fees for the charge specified by this charge ID. + """ + created: NotRequired["ApplicationFeeService.ListParamsCreated|int"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "ApplicationFeeService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[ApplicationFee]: + """ + Returns a list of application fees you've previously collected. The application fees are returned in sorted order, with the most recent fees appearing first. + """ + return cast( + ListObject[ApplicationFee], + self._requestor.request( + "get", + "/v1/application_fees", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + id: str, + params: "ApplicationFeeService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> ApplicationFee: + """ + Retrieves the details of an application fee that your account has collected. The same information is returned when refunding the application fee. + """ + return cast( + ApplicationFee, + self._requestor.request( + "get", + "/v1/application_fees/{id}".format(id=_util.sanitize_id(id)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_apps_service.py b/stripe/_apps_service.py new file mode 100644 index 000000000..d42bf832c --- /dev/null +++ b/stripe/_apps_service.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.apps._secret_service import SecretService + + +class AppsService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.secrets = SecretService(self._requestor) diff --git a/stripe/_balance_service.py b/stripe/_balance_service.py new file mode 100644 index 000000000..f9967fdf9 --- /dev/null +++ b/stripe/_balance_service.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._balance import Balance +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class BalanceService(StripeService): + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def retrieve( + self, + params: "BalanceService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Balance: + """ + Retrieves the current account balance, based on the authentication that was used to make the request. + For a sample request, see [Accounting for negative balances](https://stripe.com/docs/connect/account-balances#accounting-for-negative-balances). + """ + return cast( + Balance, + self._requestor.request( + "get", + "/v1/balance", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_balance_transaction.py b/stripe/_balance_transaction.py index 1b75f3e39..cd2be2bef 100644 --- a/stripe/_balance_transaction.py +++ b/stripe/_balance_transaction.py @@ -259,13 +259,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "BalanceTransaction.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["BalanceTransaction.ListParams"] ) -> ListObject["BalanceTransaction"]: """ Returns a list of transactions that have contributed to the Stripe account balance (e.g., charges, transfers, and so forth). The transactions are returned in sorted order, with the most recent transactions appearing first. @@ -275,9 +269,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_balance_transaction_service.py b/stripe/_balance_transaction_service.py new file mode 100644 index 000000000..9dca28642 --- /dev/null +++ b/stripe/_balance_transaction_service.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._balance_transaction import BalanceTransaction +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class BalanceTransactionService(StripeService): + class ListParams(TypedDict): + created: NotRequired["BalanceTransactionService.ListParamsCreated|int"] + currency: NotRequired["str"] + """ + Only return transactions in a certain currency. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + payout: NotRequired["str"] + """ + For automatic Stripe payouts only, only returns transactions that were paid out on the specified payout ID. + """ + source: NotRequired["str"] + """ + Only returns the original transaction. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + type: NotRequired["str"] + """ + Only returns transactions of the given type. One of: `adjustment`, `advance`, `advance_funding`, `anticipation_repayment`, `application_fee`, `application_fee_refund`, `charge`, `climate_order_purchase`, `climate_order_refund`, `connect_collection_transfer`, `contribution`, `issuing_authorization_hold`, `issuing_authorization_release`, `issuing_dispute`, `issuing_transaction`, `obligation_outbound`, `obligation_reversal_inbound`, `payment`, `payment_failure_refund`, `payment_network_reserve_hold`, `payment_network_reserve_release`, `payment_refund`, `payment_reversal`, `payment_unreconciled`, `payout`, `payout_cancel`, `payout_failure`, `refund`, `refund_failure`, `reserve_transaction`, `reserved_funds`, `stripe_fee`, `stripe_fx_fee`, `tax_fee`, `topup`, `topup_reversal`, `transfer`, `transfer_cancel`, `transfer_failure`, or `transfer_refund`. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "BalanceTransactionService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[BalanceTransaction]: + """ + Returns a list of transactions that have contributed to the Stripe account balance (e.g., charges, transfers, and so forth). The transactions are returned in sorted order, with the most recent transactions appearing first. + + Note that this endpoint was previously called “Balance history” and used the path /v1/balance/history. + """ + return cast( + ListObject[BalanceTransaction], + self._requestor.request( + "get", + "/v1/balance_transactions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + id: str, + params: "BalanceTransactionService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> BalanceTransaction: + """ + Retrieves the balance transaction with the given ID. + + Note that this endpoint previously used the path /v1/balance/history/:id. + """ + return cast( + BalanceTransaction, + self._requestor.request( + "get", + "/v1/balance_transactions/{id}".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_bank_account.py b/stripe/_bank_account.py index 3c7dd8b7e..b462d4d28 100644 --- a/stripe/_bank_account.py +++ b/stripe/_bank_account.py @@ -451,14 +451,7 @@ def modify(cls, sid, **params): ) @classmethod - def retrieve( - cls, - id, - api_key=None, - stripe_version=None, - stripe_account=None, - **params - ): + def retrieve(cls, id, **params): raise NotImplementedError( "Can't retrieve a bank account without a customer or account ID. " "Use stripe.customer.retrieve_source('customer_id', 'bank_account_id') " diff --git a/stripe/_base_address.py b/stripe/_base_address.py new file mode 100644 index 000000000..aa7a133e7 --- /dev/null +++ b/stripe/_base_address.py @@ -0,0 +1,11 @@ +from typing import Optional +from typing_extensions import NotRequired, TypedDict, Literal + + +BaseAddress = Literal["api", "files", "connect"] + + +class BaseAddresses(TypedDict): + api: NotRequired[Optional[str]] + connect: NotRequired[Optional[str]] + files: NotRequired[Optional[str]] diff --git a/stripe/_billing_portal_service.py b/stripe/_billing_portal_service.py new file mode 100644 index 000000000..4c7818a59 --- /dev/null +++ b/stripe/_billing_portal_service.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.billing_portal._configuration_service import ConfigurationService +from stripe.billing_portal._session_service import SessionService + + +class BillingPortalService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.configurations = ConfigurationService(self._requestor) + self.sessions = SessionService(self._requestor) diff --git a/stripe/_capability.py b/stripe/_capability.py index d2f857d98..5233977f2 100644 --- a/stripe/_capability.py +++ b/stripe/_capability.py @@ -363,7 +363,7 @@ def modify(cls, sid, **params): ) @classmethod - def retrieve(cls, id, api_key=None, **params): + def retrieve(cls, id, **params): raise NotImplementedError( "Can't retrieve a capability without an account ID. Retrieve a capability using " "account.retrieve_capability('acct_123', 'acap_123')" diff --git a/stripe/_card.py b/stripe/_card.py index 142a0b489..4682f92de 100644 --- a/stripe/_card.py +++ b/stripe/_card.py @@ -250,14 +250,7 @@ def modify(cls, sid, **params): ) @classmethod - def retrieve( - cls, - id, - api_key=None, - stripe_version=None, - stripe_account=None, - **params - ): + def retrieve(cls, id, **params): raise NotImplementedError( "Can't retrieve a card without a customer or account ID. " "Use stripe.Customer.retrieve_source('customer_id', 'card_id') " diff --git a/stripe/_cash_balance.py b/stripe/_cash_balance.py index 5a8b6914d..325e363f1 100644 --- a/stripe/_cash_balance.py +++ b/stripe/_cash_balance.py @@ -49,7 +49,7 @@ def instance_url(self): return "%s/%s/cash_balance" % (base, cust_extn) @classmethod - def retrieve(cls, id, api_key=None, **params): + def retrieve(cls, id, **params): raise NotImplementedError( "Can't retrieve a Customer Cash Balance without a Customer ID. " "Use Customer.retrieve_cash_balance('cus_123')" diff --git a/stripe/_charge.py b/stripe/_charge.py index 5d478fcf3..3a0038b24 100644 --- a/stripe/_charge.py +++ b/stripe/_charge.py @@ -2212,14 +2212,7 @@ class SearchParams(RequestOptions): @classmethod def _cls_capture( - cls, - charge: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Charge.CaptureParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, charge: str, **params: Unpack["Charge.CaptureParams"] ) -> "Charge": """ Capture the payment of an existing, uncaptured charge that was created with the capture option set to false. @@ -2235,9 +2228,6 @@ def _cls_capture( "/v1/charges/{charge}/capture".format( charge=_util.sanitize_id(charge) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2245,13 +2235,7 @@ def _cls_capture( @overload @staticmethod def capture( - charge: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Charge.CaptureParams" - ] # pyright: ignore[reportGeneralTypeIssues] + charge: str, **params: Unpack["Charge.CaptureParams"] ) -> "Charge": """ Capture the payment of an existing, uncaptured charge that was created with the capture option set to false. @@ -2263,13 +2247,7 @@ def capture( ... @overload - def capture( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Charge.CaptureParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Charge": + def capture(self, **params: Unpack["Charge.CaptureParams"]) -> "Charge": """ Capture the payment of an existing, uncaptured charge that was created with the capture option set to false. @@ -2281,11 +2259,7 @@ def capture( @class_method_variant("_cls_capture") def capture( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Charge.CaptureParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Charge.CaptureParams"] ) -> "Charge": """ Capture the payment of an existing, uncaptured charge that was created with the capture option set to false. @@ -2301,22 +2275,12 @@ def capture( # pyright: ignore[reportGeneralTypeIssues] "/v1/charges/{charge}/capture".format( charge=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Charge.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Charge": + def create(cls, **params: Unpack["Charge.CreateParams"]) -> "Charge": """ This method is no longer recommended—use the [Payment Intents API](https://stripe.com/docs/api/payment_intents) to initiate a new payment instead. Confirmation of the PaymentIntent creates the Charge @@ -2327,23 +2291,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Charge.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Charge.ListParams"] ) -> ListObject["Charge"]: """ Returns a list of charges you've previously created. The charges are returned in sorted order, with the most recent charges appearing first. @@ -2351,9 +2305,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -2408,17 +2359,21 @@ def search_auto_paging_iter( return cls.search(*args, **kwargs).auto_paging_iter() def mark_as_fraudulent(self, idempotency_key=None) -> "Charge": - params = {"fraud_details": {"user_report": "fraudulent"}} + params = { + "fraud_details": {"user_report": "fraudulent"}, + "idempotency_key": idempotency_key, + } url = self.instance_url() - headers = _util.populate_headers(idempotency_key) - self.refresh_from(self.request("post", url, params, headers)) + self._request_and_refresh("post", url, params) return self def mark_as_safe(self, idempotency_key=None) -> "Charge": - params = {"fraud_details": {"user_report": "safe"}} + params = { + "fraud_details": {"user_report": "safe"}, + "idempotency_key": idempotency_key, + } url = self.instance_url() - headers = _util.populate_headers(idempotency_key) - self.refresh_from(self.request("post", url, params, headers)) + self._request_and_refresh("post", url, params) return self _inner_class_types = { diff --git a/stripe/_charge_service.py b/stripe/_charge_service.py new file mode 100644 index 000000000..41a15b86c --- /dev/null +++ b/stripe/_charge_service.py @@ -0,0 +1,501 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._charge import Charge +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._search_result_object import SearchResultObject +from stripe._stripe_service import StripeService +from typing import Dict, List, Union, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ChargeService(StripeService): + class CaptureParams(TypedDict): + amount: NotRequired["int"] + """ + The amount to capture, which must be less than or equal to the original amount. Any additional amount will be automatically refunded. + """ + application_fee: NotRequired["int"] + """ + An application fee to add on to this charge. + """ + application_fee_amount: NotRequired["int"] + """ + An application fee amount to add on to this charge, which must be less than or equal to the original amount. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + receipt_email: NotRequired["str"] + """ + The email address to send this charge's receipt to. This will override the previously-specified email address for this charge, if one was set. Receipts will not be sent in test mode. + """ + statement_descriptor: NotRequired["str"] + """ + For card charges, use `statement_descriptor_suffix` instead. Otherwise, you can use this value as the complete description of a charge on your customers' statements. Must contain at least one letter, maximum 22 characters. + """ + statement_descriptor_suffix: NotRequired["str"] + """ + Provides information about the charge that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. + """ + transfer_data: NotRequired["ChargeService.CaptureParamsTransferData"] + """ + An optional dictionary including the account to automatically transfer to as part of a destination charge. [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. + """ + transfer_group: NotRequired["str"] + """ + A string that identifies this transaction as part of a group. `transfer_group` may only be provided if it has not been set. See the [Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-options) for details. + """ + + class CaptureParamsTransferData(TypedDict): + amount: NotRequired["int"] + """ + The amount transferred to the destination account, if specified. By default, the entire charge amount is transferred to the destination account. + """ + + class CreateParams(TypedDict): + amount: NotRequired["int"] + """ + Amount intended to be collected by this payment. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + """ + application_fee: NotRequired["int"] + application_fee_amount: NotRequired["int"] + """ + A fee in cents (or local equivalent) that will be applied to the charge and transferred to the application owner's Stripe account. The request must be made with an OAuth key or the `Stripe-Account` header in order to take an application fee. For more information, see the application fees [documentation](https://stripe.com/docs/connect/direct-charges#collecting-fees). + """ + capture: NotRequired["bool"] + """ + Whether to immediately capture the charge. Defaults to `true`. When `false`, the charge issues an authorization (or pre-authorization), and will need to be [captured](https://stripe.com/docs/api#capture_charge) later. Uncaptured charges expire after a set number of days (7 by default). For more information, see the [authorizing charges and settling later](https://stripe.com/docs/charges/placing-a-hold) documentation. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + customer: NotRequired["str"] + """ + The ID of an existing customer that will be charged in this request. + """ + description: NotRequired["str"] + """ + An arbitrary string which you can attach to a `Charge` object. It is displayed when in the web interface alongside the charge. Note that if you use Stripe to send automatic email receipts to your customers, your receipt emails will include the `description` of the charge(s) that they are describing. + """ + destination: NotRequired["ChargeService.CreateParamsDestination"] + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + on_behalf_of: NotRequired["str"] + """ + The Stripe account ID for which these funds are intended. Automatically set if you use the `destination` parameter. For details, see [Creating Separate Charges and Transfers](https://stripe.com/docs/connect/separate-charges-and-transfers#on-behalf-of). + """ + radar_options: NotRequired["ChargeService.CreateParamsRadarOptions"] + """ + Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + """ + receipt_email: NotRequired["str"] + """ + The email address to which this charge's [receipt](https://stripe.com/docs/dashboard/receipts) will be sent. The receipt will not be sent until the charge is paid, and no receipts will be sent for test mode charges. If this charge is for a [Customer](https://stripe.com/docs/api/customers/object), the email address specified here will override the customer's email address. If `receipt_email` is specified for a charge in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + """ + shipping: NotRequired["ChargeService.CreateParamsShipping"] + """ + Shipping information for the charge. Helps prevent fraud on charges for physical goods. + """ + source: NotRequired["str"] + """ + A payment source to be charged. This can be the ID of a [card](https://stripe.com/docs/api#cards) (i.e., credit or debit card), a [bank account](https://stripe.com/docs/api#bank_accounts), a [source](https://stripe.com/docs/api#sources), a [token](https://stripe.com/docs/api#tokens), or a [connected account](https://stripe.com/docs/connect/account-debits#charging-a-connected-account). For certain sources---namely, [cards](https://stripe.com/docs/api#cards), [bank accounts](https://stripe.com/docs/api#bank_accounts), and attached [sources](https://stripe.com/docs/api#sources)---you must also pass the ID of the associated customer. + """ + statement_descriptor: NotRequired["str"] + """ + For card charges, use `statement_descriptor_suffix` instead. Otherwise, you can use this value as the complete description of a charge on your customers' statements. Must contain at least one letter, maximum 22 characters. + """ + statement_descriptor_suffix: NotRequired["str"] + """ + Provides information about the charge that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. + """ + transfer_data: NotRequired["ChargeService.CreateParamsTransferData"] + """ + An optional dictionary including the account to automatically transfer to as part of a destination charge. [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. + """ + transfer_group: NotRequired["str"] + """ + A string that identifies this transaction as part of a group. For details, see [Grouping transactions](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-options). + """ + + class CreateParamsDestination(TypedDict): + account: str + """ + ID of an existing, connected Stripe account. + """ + amount: NotRequired["int"] + """ + The amount to transfer to the destination account without creating an `Application Fee` object. Cannot be combined with the `application_fee` parameter. Must be less than or equal to the charge amount. + """ + + class CreateParamsRadarOptions(TypedDict): + session: NotRequired["str"] + """ + A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + """ + + class CreateParamsShipping(TypedDict): + address: "ChargeService.CreateParamsShippingAddress" + """ + Shipping address. + """ + carrier: NotRequired["str"] + """ + The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. + """ + name: str + """ + Recipient name. + """ + phone: NotRequired["str"] + """ + Recipient phone (including extension). + """ + tracking_number: NotRequired["str"] + """ + The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. + """ + + class CreateParamsShippingAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsTransferData(TypedDict): + amount: NotRequired["int"] + """ + The amount transferred to the destination account, if specified. By default, the entire charge amount is transferred to the destination account. + """ + destination: str + """ + ID of an existing, connected Stripe account. + """ + + class ListParams(TypedDict): + created: NotRequired["ChargeService.ListParamsCreated|int"] + customer: NotRequired["str"] + """ + Only return charges for the customer specified by this customer ID. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + payment_intent: NotRequired["str"] + """ + Only return charges that were created by the PaymentIntent specified by this PaymentIntent ID. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + transfer_group: NotRequired["str"] + """ + Only return charges for this transfer group. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class SearchParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + page: NotRequired["str"] + """ + A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + """ + query: str + """ + The search query string. See [search query language](https://stripe.com/docs/search#search-query-language) and the list of supported [query fields for charges](https://stripe.com/docs/search#query-fields-for-charges). + """ + + class UpdateParams(TypedDict): + customer: NotRequired["str"] + """ + The ID of an existing customer that will be associated with this request. This field may only be updated if there is no existing associated customer with this charge. + """ + description: NotRequired["str"] + """ + An arbitrary string which you can attach to a charge object. It is displayed when in the web interface alongside the charge. Note that if you use Stripe to send automatic email receipts to your customers, your receipt emails will include the `description` of the charge(s) that they are describing. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + fraud_details: NotRequired["ChargeService.UpdateParamsFraudDetails"] + """ + A set of key-value pairs you can attach to a charge giving information about its riskiness. If you believe a charge is fraudulent, include a `user_report` key with a value of `fraudulent`. If you believe a charge is safe, include a `user_report` key with a value of `safe`. Stripe will use the information you send to improve our fraud detection algorithms. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + receipt_email: NotRequired["str"] + """ + This is the email address that the receipt for this charge will be sent to. If this field is updated, then a new email receipt will be sent to the updated address. + """ + shipping: NotRequired["ChargeService.UpdateParamsShipping"] + """ + Shipping information for the charge. Helps prevent fraud on charges for physical goods. + """ + transfer_group: NotRequired["str"] + """ + A string that identifies this transaction as part of a group. `transfer_group` may only be provided if it has not been set. See the [Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-options) for details. + """ + + class UpdateParamsFraudDetails(TypedDict): + user_report: Union[Literal[""], Literal["fraudulent", "safe"]] + """ + Either `safe` or `fraudulent`. + """ + + class UpdateParamsShipping(TypedDict): + address: "ChargeService.UpdateParamsShippingAddress" + """ + Shipping address. + """ + carrier: NotRequired["str"] + """ + The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. + """ + name: str + """ + Recipient name. + """ + phone: NotRequired["str"] + """ + Recipient phone (including extension). + """ + tracking_number: NotRequired["str"] + """ + The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. + """ + + class UpdateParamsShippingAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + def list( + self, + params: "ChargeService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Charge]: + """ + Returns a list of charges you've previously created. The charges are returned in sorted order, with the most recent charges appearing first. + """ + return cast( + ListObject[Charge], + self._requestor.request( + "get", + "/v1/charges", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "ChargeService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Charge: + """ + This method is no longer recommended—use the [Payment Intents API](https://stripe.com/docs/api/payment_intents) + to initiate a new payment instead. Confirmation of the PaymentIntent creates the Charge + object used to request payment. + """ + return cast( + Charge, + self._requestor.request( + "post", + "/v1/charges", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + charge: str, + params: "ChargeService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Charge: + """ + Retrieves the details of a charge that has previously been created. Supply the unique charge ID that was returned from your previous request, and Stripe will return the corresponding charge information. The same information is returned when creating or refunding the charge. + """ + return cast( + Charge, + self._requestor.request( + "get", + "/v1/charges/{charge}".format( + charge=_util.sanitize_id(charge) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + charge: str, + params: "ChargeService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Charge: + """ + Updates the specified charge by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + """ + return cast( + Charge, + self._requestor.request( + "post", + "/v1/charges/{charge}".format( + charge=_util.sanitize_id(charge) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def search( + self, + params: "ChargeService.SearchParams", + options: RequestOptions = {}, + ) -> SearchResultObject[Charge]: + """ + Search for charges you've previously created using Stripe's [Search Query Language](https://stripe.com/docs/search#search-query-language). + Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating + conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up + to an hour behind during outages. Search functionality is not available to merchants in India. + """ + return cast( + SearchResultObject[Charge], + self._requestor.request( + "get", + "/v1/charges/search", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def capture( + self, + charge: str, + params: "ChargeService.CaptureParams" = {}, + options: RequestOptions = {}, + ) -> Charge: + """ + Capture the payment of an existing, uncaptured charge that was created with the capture option set to false. + + Uncaptured payments expire a set number of days after they are created ([7 by default](https://stripe.com/docs/charges/placing-a-hold)), after which they are marked as refunded and capture attempts will fail. + + Don't use this method to capture a PaymentIntent-initiated charge. Use [Capture a PaymentIntent](https://stripe.com/docs/api/payment_intents/capture). + """ + return cast( + Charge, + self._requestor.request( + "post", + "/v1/charges/{charge}/capture".format( + charge=_util.sanitize_id(charge), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_checkout_service.py b/stripe/_checkout_service.py new file mode 100644 index 000000000..c45587d49 --- /dev/null +++ b/stripe/_checkout_service.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.checkout._session_service import SessionService + + +class CheckoutService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.sessions = SessionService(self._requestor) diff --git a/stripe/_client_options.py b/stripe/_client_options.py new file mode 100644 index 000000000..4a498b8c9 --- /dev/null +++ b/stripe/_client_options.py @@ -0,0 +1,17 @@ +from typing import Optional + + +class _ClientOptions(object): + client_id: Optional[str] + proxy: Optional[str] + verify_ssl_certs: Optional[bool] + + def __init__( + self, + client_id: Optional[str] = None, + proxy: Optional[str] = None, + verify_ssl_certs: Optional[bool] = None, + ): + self.client_id = client_id + self.proxy = proxy + self.verify_ssl_certs = verify_ssl_certs diff --git a/stripe/_climate_service.py b/stripe/_climate_service.py new file mode 100644 index 000000000..a27025688 --- /dev/null +++ b/stripe/_climate_service.py @@ -0,0 +1,14 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.climate._order_service import OrderService +from stripe.climate._product_service import ProductService +from stripe.climate._supplier_service import SupplierService + + +class ClimateService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.orders = OrderService(self._requestor) + self.products = ProductService(self._requestor) + self.suppliers = SupplierService(self._requestor) diff --git a/stripe/_country_spec.py b/stripe/_country_spec.py index 0954c26e5..6ca8a1433 100644 --- a/stripe/_country_spec.py +++ b/stripe/_country_spec.py @@ -4,7 +4,7 @@ from stripe._listable_api_resource import ListableAPIResource from stripe._request_options import RequestOptions from stripe._stripe_object import StripeObject -from typing import ClassVar, Dict, List, Optional +from typing import ClassVar, Dict, List from typing_extensions import Literal, NotRequired, Unpack @@ -101,13 +101,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "CountrySpec.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["CountrySpec.ListParams"] ) -> ListObject["CountrySpec"]: """ Lists all Country Spec objects available in the API. @@ -115,9 +109,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_country_spec_service.py b/stripe/_country_spec_service.py new file mode 100644 index 000000000..4b1ad1fa8 --- /dev/null +++ b/stripe/_country_spec_service.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._country_spec import CountrySpec +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class CountrySpecService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "CountrySpecService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[CountrySpec]: + """ + Lists all Country Spec objects available in the API. + """ + return cast( + ListObject[CountrySpec], + self._requestor.request( + "get", + "/v1/country_specs", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + country: str, + params: "CountrySpecService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> CountrySpec: + """ + Returns a Country Spec for a given Country code. + """ + return cast( + CountrySpec, + self._requestor.request( + "get", + "/v1/country_specs/{country}".format( + country=_util.sanitize_id(country), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_coupon.py b/stripe/_coupon.py index 7604816f6..35377c582 100644 --- a/stripe/_coupon.py +++ b/stripe/_coupon.py @@ -253,16 +253,7 @@ class RetrieveParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Coupon.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Coupon": + def create(cls, **params: Unpack["Coupon.CreateParams"]) -> "Coupon": """ You can create coupons easily via the [coupon management](https://dashboard.stripe.com/coupons) page of the Stripe dashboard. Coupon creation is also accessible via the API if you need to create coupons on the fly. @@ -273,10 +264,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -324,13 +311,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Coupon.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Coupon.ListParams"] ) -> ListObject["Coupon"]: """ Returns a list of your coupons. @@ -338,9 +319,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_coupon_service.py b/stripe/_coupon_service.py new file mode 100644 index 000000000..e6e0d5a21 --- /dev/null +++ b/stripe/_coupon_service.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._coupon import Coupon +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CouponService(StripeService): + class CreateParams(TypedDict): + amount_off: NotRequired["int"] + """ + A positive integer representing the amount to subtract from an invoice total (required if `percent_off` is not passed). + """ + applies_to: NotRequired["CouponService.CreateParamsAppliesTo"] + """ + A hash containing directions for what this Coupon will apply discounts to. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) of the `amount_off` parameter (required if `amount_off` is passed). + """ + currency_options: NotRequired[ + "Dict[str, CouponService.CreateParamsCurrencyOptions]" + ] + """ + Coupons defined in each available currency option (only supported if `amount_off` is passed). Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + """ + duration: NotRequired["Literal['forever', 'once', 'repeating']"] + """ + Specifies how long the discount will be in effect if used on a subscription. Defaults to `once`. + """ + duration_in_months: NotRequired["int"] + """ + Required only if `duration` is `repeating`, in which case it must be a positive integer that specifies the number of months the discount will be in effect. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + id: NotRequired["str"] + """ + Unique string of your choice that will be used to identify this coupon when applying it to a customer. If you don't want to specify a particular code, you can leave the ID blank and we'll generate a random code for you. + """ + max_redemptions: NotRequired["int"] + """ + A positive integer specifying the number of times the coupon can be redeemed before it's no longer valid. For example, you might have a 50% off coupon that the first 20 readers of your blog can use. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: NotRequired["str"] + """ + Name of the coupon displayed to customers on, for instance invoices, or receipts. By default the `id` is shown if `name` is not set. + """ + percent_off: NotRequired["float"] + """ + A positive float larger than 0, and smaller or equal to 100, that represents the discount the coupon will apply (required if `amount_off` is not passed). + """ + redeem_by: NotRequired["int"] + """ + Unix timestamp specifying the last time at which the coupon can be redeemed. After the redeem_by date, the coupon can no longer be applied to new customers. + """ + + class CreateParamsAppliesTo(TypedDict): + products: NotRequired["List[str]"] + """ + An array of Product IDs that this Coupon will apply to. + """ + + class CreateParamsCurrencyOptions(TypedDict): + amount_off: int + """ + A positive integer representing the amount to subtract from an invoice total. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + created: NotRequired["CouponService.ListParamsCreated|int"] + """ + A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + currency_options: NotRequired[ + "Dict[str, CouponService.UpdateParamsCurrencyOptions]" + ] + """ + Coupons defined in each available currency option (only supported if the coupon is amount-based). Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: NotRequired["str"] + """ + Name of the coupon displayed to customers on, for instance invoices, or receipts. By default the `id` is shown if `name` is not set. + """ + + class UpdateParamsCurrencyOptions(TypedDict): + amount_off: int + """ + A positive integer representing the amount to subtract from an invoice total. + """ + + def delete( + self, + coupon: str, + params: "CouponService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> Coupon: + """ + You can delete coupons via the [coupon management](https://dashboard.stripe.com/coupons) page of the Stripe dashboard. However, deleting a coupon does not affect any customers who have already applied the coupon; it means that new customers can't redeem the coupon. You can also delete coupons via the API. + """ + return cast( + Coupon, + self._requestor.request( + "delete", + "/v1/coupons/{coupon}".format( + coupon=_util.sanitize_id(coupon) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + coupon: str, + params: "CouponService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Coupon: + """ + Retrieves the coupon with the given ID. + """ + return cast( + Coupon, + self._requestor.request( + "get", + "/v1/coupons/{coupon}".format( + coupon=_util.sanitize_id(coupon) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + coupon: str, + params: "CouponService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Coupon: + """ + Updates the metadata of a coupon. Other coupon details (currency, duration, amount_off) are, by design, not editable. + """ + return cast( + Coupon, + self._requestor.request( + "post", + "/v1/coupons/{coupon}".format( + coupon=_util.sanitize_id(coupon) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "CouponService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Coupon]: + """ + Returns a list of your coupons. + """ + return cast( + ListObject[Coupon], + self._requestor.request( + "get", + "/v1/coupons", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "CouponService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Coupon: + """ + You can create coupons easily via the [coupon management](https://dashboard.stripe.com/coupons) page of the Stripe dashboard. Coupon creation is also accessible via the API if you need to create coupons on the fly. + + A coupon has either a percent_off or an amount_off and currency. If you set an amount_off, that amount will be subtracted from any invoice's subtotal. For example, an invoice with a subtotal of 100 will have a final total of 0 if a coupon with an amount_off of 200 is applied to it and an invoice with a subtotal of 300 will have a final total of 100 if a coupon with an amount_off of 200 is applied to it. + """ + return cast( + Coupon, + self._requestor.request( + "post", + "/v1/coupons", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_createable_api_resource.py b/stripe/_createable_api_resource.py index 25ed8f6c8..993a32616 100644 --- a/stripe/_createable_api_resource.py +++ b/stripe/_createable_api_resource.py @@ -7,23 +7,8 @@ class CreateableAPIResource(APIResource[T]): @classmethod - def create( - cls, - api_key=None, - idempotency_key=None, - stripe_version=None, - stripe_account=None, - **params - ) -> T: + def create(cls, **params) -> T: return cast( T, - cls._static_request( - "post", - cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, - params, - ), + cls._static_request("post", cls.class_url(), params=params), ) diff --git a/stripe/_credit_note.py b/stripe/_credit_note.py index cfd168ffe..78063bf6a 100644 --- a/stripe/_credit_note.py +++ b/stripe/_credit_note.py @@ -715,14 +715,7 @@ class VoidCreditNoteParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "CreditNote.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["CreditNote.CreateParams"] ) -> "CreditNote": """ Issue a credit note to adjust the amount of a finalized invoice. For a status=open invoice, a credit note reduces @@ -745,23 +738,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "CreditNote.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["CreditNote.ListParams"] ) -> ListObject["CreditNote"]: """ Returns a list of credit notes. @@ -769,9 +752,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -798,13 +778,7 @@ def modify( @classmethod def preview( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "CreditNote.PreviewParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["CreditNote.PreviewParams"] ) -> "CreditNote": """ Get a preview of a credit note without creating it. @@ -814,22 +788,13 @@ def preview( cls._static_request( "get", "/v1/credit_notes/preview", - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def preview_lines( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "CreditNote.PreviewLinesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["CreditNote.PreviewLinesParams"] ) -> ListObject["CreditNoteLineItem"]: """ When retrieving a credit note preview, you'll get a lines property containing the first handful of those items. This URL you can retrieve the full (paginated) list of line items. @@ -839,9 +804,6 @@ def preview_lines( cls._static_request( "get", "/v1/credit_notes/preview/lines", - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -859,14 +821,7 @@ def retrieve( @classmethod def _cls_void_credit_note( - cls, - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "CreditNote.VoidCreditNoteParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, id: str, **params: Unpack["CreditNote.VoidCreditNoteParams"] ) -> "CreditNote": """ Marks a credit note as void. Learn more about [voiding credit notes](https://stripe.com/docs/billing/invoices/credit-notes#voiding). @@ -876,9 +831,6 @@ def _cls_void_credit_note( cls._static_request( "post", "/v1/credit_notes/{id}/void".format(id=_util.sanitize_id(id)), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -886,13 +838,7 @@ def _cls_void_credit_note( @overload @staticmethod def void_credit_note( - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "CreditNote.VoidCreditNoteParams" - ] # pyright: ignore[reportGeneralTypeIssues] + id: str, **params: Unpack["CreditNote.VoidCreditNoteParams"] ) -> "CreditNote": """ Marks a credit note as void. Learn more about [voiding credit notes](https://stripe.com/docs/billing/invoices/credit-notes#voiding). @@ -901,11 +847,7 @@ def void_credit_note( @overload def void_credit_note( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "CreditNote.VoidCreditNoteParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["CreditNote.VoidCreditNoteParams"] ) -> "CreditNote": """ Marks a credit note as void. Learn more about [voiding credit notes](https://stripe.com/docs/billing/invoices/credit-notes#voiding). @@ -914,11 +856,7 @@ def void_credit_note( @class_method_variant("_cls_void_credit_note") def void_credit_note( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "CreditNote.VoidCreditNoteParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["CreditNote.VoidCreditNoteParams"] ) -> "CreditNote": """ Marks a credit note as void. Learn more about [voiding credit notes](https://stripe.com/docs/billing/invoices/credit-notes#voiding). @@ -930,21 +868,13 @@ def void_credit_note( # pyright: ignore[reportGeneralTypeIssues] "/v1/credit_notes/{id}/void".format( id=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def list_lines( - cls, - credit_note: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "CreditNote.ListLinesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, credit_note: str, **params: Unpack["CreditNote.ListLinesParams"] ) -> ListObject["CreditNoteLineItem"]: """ When retrieving a credit note, you'll get a lines property containing the the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -956,9 +886,6 @@ def list_lines( "/v1/credit_notes/{credit_note}/lines".format( credit_note=_util.sanitize_id(credit_note) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) diff --git a/stripe/_credit_note_line_item.py b/stripe/_credit_note_line_item.py index 856301758..160e8c6dc 100644 --- a/stripe/_credit_note_line_item.py +++ b/stripe/_credit_note_line_item.py @@ -157,13 +157,7 @@ class ListParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "CreditNoteLineItem.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["CreditNoteLineItem.ListParams"] ) -> ListObject["CreditNoteLineItem"]: """ When retrieving a credit note, you'll get a lines property containing the the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -171,9 +165,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_credit_note_line_item_service.py b/stripe/_credit_note_line_item_service.py new file mode 100644 index 000000000..27835a5e5 --- /dev/null +++ b/stripe/_credit_note_line_item_service.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._credit_note_line_item import CreditNoteLineItem +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class CreditNoteLineItemService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + def list( + self, + credit_note: str, + params: "CreditNoteLineItemService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[CreditNoteLineItem]: + """ + When retrieving a credit note, you'll get a lines property containing the the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. + """ + return cast( + ListObject[CreditNoteLineItem], + self._requestor.request( + "get", + "/v1/credit_notes/{credit_note}/lines".format( + credit_note=_util.sanitize_id(credit_note), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_credit_note_preview_lines_service.py b/stripe/_credit_note_preview_lines_service.py new file mode 100644 index 000000000..ce0633f92 --- /dev/null +++ b/stripe/_credit_note_preview_lines_service.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._credit_note_line_item import CreditNoteLineItem +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CreditNotePreviewLinesService(StripeService): + class ListParams(TypedDict): + amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) representing the total amount of the credit note. + """ + credit_amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) representing the amount to credit the customer's balance, which will be automatically applied to their next invoice. + """ + effective_at: NotRequired["int"] + """ + The date when this credit note is in effect. Same as `created` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the credit note PDF. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice: str + """ + ID of the invoice. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + lines: NotRequired[ + "List[CreditNotePreviewLinesService.ListParamsLine]" + ] + """ + Line items that make up the credit note. + """ + memo: NotRequired["str"] + """ + The credit note's memo appears on the credit note PDF. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + out_of_band_amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) representing the amount that is credited outside of Stripe. + """ + reason: NotRequired[ + "Literal['duplicate', 'fraudulent', 'order_change', 'product_unsatisfactory']" + ] + """ + Reason for issuing this credit note, one of `duplicate`, `fraudulent`, `order_change`, or `product_unsatisfactory` + """ + refund: NotRequired["str"] + """ + ID of an existing refund to link this credit note to. + """ + refund_amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) representing the amount to refund. If set, a refund will be created for the charge associated with the invoice. + """ + shipping_cost: NotRequired[ + "CreditNotePreviewLinesService.ListParamsShippingCost" + ] + """ + When shipping_cost contains the shipping_rate from the invoice, the shipping_cost is included in the credit note. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsLine(TypedDict): + amount: NotRequired["int"] + """ + The line item amount to credit. Only valid when `type` is `invoice_line_item`. + """ + description: NotRequired["str"] + """ + The description of the credit note line item. Only valid when the `type` is `custom_line_item`. + """ + invoice_line_item: NotRequired["str"] + """ + The invoice line item to credit. Only valid when the `type` is `invoice_line_item`. + """ + quantity: NotRequired["int"] + """ + The line item quantity to credit. + """ + tax_amounts: NotRequired[ + "Literal['']|List[CreditNotePreviewLinesService.ListParamsLineTaxAmount]" + ] + """ + A list of up to 10 tax amounts for the credit note line item. Cannot be mixed with `tax_rates`. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates which apply to the credit note line item. Only valid when the `type` is `custom_line_item` and cannot be mixed with `tax_amounts`. + """ + type: Literal["custom_line_item", "invoice_line_item"] + """ + Type of the credit note line item, one of `invoice_line_item` or `custom_line_item` + """ + unit_amount: NotRequired["int"] + """ + The integer unit amount in cents (or local equivalent) of the credit note line item. This `unit_amount` will be multiplied by the quantity to get the full amount to credit for this line item. Only valid when `type` is `custom_line_item`. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class ListParamsLineTaxAmount(TypedDict): + amount: int + """ + The amount, in cents (or local equivalent), of the tax. + """ + tax_rate: str + """ + The id of the tax rate for this tax amount. The tax rate must have been automatically created by Stripe. + """ + taxable_amount: int + """ + The amount on which tax is calculated, in cents (or local equivalent). + """ + + class ListParamsShippingCost(TypedDict): + shipping_rate: NotRequired["str"] + """ + The ID of the shipping rate to use for this order. + """ + + def list( + self, + params: "CreditNotePreviewLinesService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[CreditNoteLineItem]: + """ + When retrieving a credit note preview, you'll get a lines property containing the first handful of those items. This URL you can retrieve the full (paginated) list of line items. + """ + return cast( + ListObject[CreditNoteLineItem], + self._requestor.request( + "get", + "/v1/credit_notes/preview/lines", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_credit_note_service.py b/stripe/_credit_note_service.py new file mode 100644 index 000000000..c4f9d460b --- /dev/null +++ b/stripe/_credit_note_service.py @@ -0,0 +1,444 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._credit_note import CreditNote +from stripe._credit_note_line_item_service import CreditNoteLineItemService +from stripe._credit_note_preview_lines_service import ( + CreditNotePreviewLinesService, +) +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CreditNoteService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.line_items = CreditNoteLineItemService(self._requestor) + self.preview_lines = CreditNotePreviewLinesService(self._requestor) + + class CreateParams(TypedDict): + amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) representing the total amount of the credit note. + """ + credit_amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) representing the amount to credit the customer's balance, which will be automatically applied to their next invoice. + """ + effective_at: NotRequired["int"] + """ + The date when this credit note is in effect. Same as `created` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the credit note PDF. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice: str + """ + ID of the invoice. + """ + lines: NotRequired["List[CreditNoteService.CreateParamsLine]"] + """ + Line items that make up the credit note. + """ + memo: NotRequired["str"] + """ + The credit note's memo appears on the credit note PDF. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + out_of_band_amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) representing the amount that is credited outside of Stripe. + """ + reason: NotRequired[ + "Literal['duplicate', 'fraudulent', 'order_change', 'product_unsatisfactory']" + ] + """ + Reason for issuing this credit note, one of `duplicate`, `fraudulent`, `order_change`, or `product_unsatisfactory` + """ + refund: NotRequired["str"] + """ + ID of an existing refund to link this credit note to. + """ + refund_amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) representing the amount to refund. If set, a refund will be created for the charge associated with the invoice. + """ + shipping_cost: NotRequired[ + "CreditNoteService.CreateParamsShippingCost" + ] + """ + When shipping_cost contains the shipping_rate from the invoice, the shipping_cost is included in the credit note. + """ + + class CreateParamsLine(TypedDict): + amount: NotRequired["int"] + """ + The line item amount to credit. Only valid when `type` is `invoice_line_item`. + """ + description: NotRequired["str"] + """ + The description of the credit note line item. Only valid when the `type` is `custom_line_item`. + """ + invoice_line_item: NotRequired["str"] + """ + The invoice line item to credit. Only valid when the `type` is `invoice_line_item`. + """ + quantity: NotRequired["int"] + """ + The line item quantity to credit. + """ + tax_amounts: NotRequired[ + "Literal['']|List[CreditNoteService.CreateParamsLineTaxAmount]" + ] + """ + A list of up to 10 tax amounts for the credit note line item. Cannot be mixed with `tax_rates`. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates which apply to the credit note line item. Only valid when the `type` is `custom_line_item` and cannot be mixed with `tax_amounts`. + """ + type: Literal["custom_line_item", "invoice_line_item"] + """ + Type of the credit note line item, one of `invoice_line_item` or `custom_line_item` + """ + unit_amount: NotRequired["int"] + """ + The integer unit amount in cents (or local equivalent) of the credit note line item. This `unit_amount` will be multiplied by the quantity to get the full amount to credit for this line item. Only valid when `type` is `custom_line_item`. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class CreateParamsLineTaxAmount(TypedDict): + amount: int + """ + The amount, in cents (or local equivalent), of the tax. + """ + tax_rate: str + """ + The id of the tax rate for this tax amount. The tax rate must have been automatically created by Stripe. + """ + taxable_amount: int + """ + The amount on which tax is calculated, in cents (or local equivalent). + """ + + class CreateParamsShippingCost(TypedDict): + shipping_rate: NotRequired["str"] + """ + The ID of the shipping rate to use for this order. + """ + + class ListParams(TypedDict): + customer: NotRequired["str"] + """ + Only return credit notes for the customer specified by this customer ID. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice: NotRequired["str"] + """ + Only return credit notes for the invoice specified by this invoice ID. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class PreviewParams(TypedDict): + amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) representing the total amount of the credit note. + """ + credit_amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) representing the amount to credit the customer's balance, which will be automatically applied to their next invoice. + """ + effective_at: NotRequired["int"] + """ + The date when this credit note is in effect. Same as `created` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the credit note PDF. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice: str + """ + ID of the invoice. + """ + lines: NotRequired["List[CreditNoteService.PreviewParamsLine]"] + """ + Line items that make up the credit note. + """ + memo: NotRequired["str"] + """ + The credit note's memo appears on the credit note PDF. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + out_of_band_amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) representing the amount that is credited outside of Stripe. + """ + reason: NotRequired[ + "Literal['duplicate', 'fraudulent', 'order_change', 'product_unsatisfactory']" + ] + """ + Reason for issuing this credit note, one of `duplicate`, `fraudulent`, `order_change`, or `product_unsatisfactory` + """ + refund: NotRequired["str"] + """ + ID of an existing refund to link this credit note to. + """ + refund_amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) representing the amount to refund. If set, a refund will be created for the charge associated with the invoice. + """ + shipping_cost: NotRequired[ + "CreditNoteService.PreviewParamsShippingCost" + ] + """ + When shipping_cost contains the shipping_rate from the invoice, the shipping_cost is included in the credit note. + """ + + class PreviewParamsLine(TypedDict): + amount: NotRequired["int"] + """ + The line item amount to credit. Only valid when `type` is `invoice_line_item`. + """ + description: NotRequired["str"] + """ + The description of the credit note line item. Only valid when the `type` is `custom_line_item`. + """ + invoice_line_item: NotRequired["str"] + """ + The invoice line item to credit. Only valid when the `type` is `invoice_line_item`. + """ + quantity: NotRequired["int"] + """ + The line item quantity to credit. + """ + tax_amounts: NotRequired[ + "Literal['']|List[CreditNoteService.PreviewParamsLineTaxAmount]" + ] + """ + A list of up to 10 tax amounts for the credit note line item. Cannot be mixed with `tax_rates`. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates which apply to the credit note line item. Only valid when the `type` is `custom_line_item` and cannot be mixed with `tax_amounts`. + """ + type: Literal["custom_line_item", "invoice_line_item"] + """ + Type of the credit note line item, one of `invoice_line_item` or `custom_line_item` + """ + unit_amount: NotRequired["int"] + """ + The integer unit amount in cents (or local equivalent) of the credit note line item. This `unit_amount` will be multiplied by the quantity to get the full amount to credit for this line item. Only valid when `type` is `custom_line_item`. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class PreviewParamsLineTaxAmount(TypedDict): + amount: int + """ + The amount, in cents (or local equivalent), of the tax. + """ + tax_rate: str + """ + The id of the tax rate for this tax amount. The tax rate must have been automatically created by Stripe. + """ + taxable_amount: int + """ + The amount on which tax is calculated, in cents (or local equivalent). + """ + + class PreviewParamsShippingCost(TypedDict): + shipping_rate: NotRequired["str"] + """ + The ID of the shipping rate to use for this order. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + memo: NotRequired["str"] + """ + Credit note memo. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class VoidCreditNoteParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "CreditNoteService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[CreditNote]: + """ + Returns a list of credit notes. + """ + return cast( + ListObject[CreditNote], + self._requestor.request( + "get", + "/v1/credit_notes", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "CreditNoteService.CreateParams", + options: RequestOptions = {}, + ) -> CreditNote: + """ + Issue a credit note to adjust the amount of a finalized invoice. For a status=open invoice, a credit note reduces + its amount_due. For a status=paid invoice, a credit note does not affect its amount_due. Instead, it can result + in any combination of the following: + + + Refund: create a new refund (using refund_amount) or link an existing refund (using refund). + Customer balance credit: credit the customer's balance (using credit_amount) which will be automatically applied to their next invoice when it's finalized. + Outside of Stripe credit: record the amount that is or will be credited outside of Stripe (using out_of_band_amount). + + + For post-payment credit notes the sum of the refund, credit and outside of Stripe amounts must equal the credit note total. + + You may issue multiple credit notes for an invoice. Each credit note will increment the invoice's pre_payment_credit_notes_amount + or post_payment_credit_notes_amount depending on its status at the time of credit note creation. + """ + return cast( + CreditNote, + self._requestor.request( + "post", + "/v1/credit_notes", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + id: str, + params: "CreditNoteService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> CreditNote: + """ + Retrieves the credit note object with the given identifier. + """ + return cast( + CreditNote, + self._requestor.request( + "get", + "/v1/credit_notes/{id}".format(id=_util.sanitize_id(id)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + id: str, + params: "CreditNoteService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> CreditNote: + """ + Updates an existing credit note. + """ + return cast( + CreditNote, + self._requestor.request( + "post", + "/v1/credit_notes/{id}".format(id=_util.sanitize_id(id)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def preview( + self, + params: "CreditNoteService.PreviewParams", + options: RequestOptions = {}, + ) -> CreditNote: + """ + Get a preview of a credit note without creating it. + """ + return cast( + CreditNote, + self._requestor.request( + "get", + "/v1/credit_notes/preview", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def void_credit_note( + self, + id: str, + params: "CreditNoteService.VoidCreditNoteParams" = {}, + options: RequestOptions = {}, + ) -> CreditNote: + """ + Marks a credit note as void. Learn more about [voiding credit notes](https://stripe.com/docs/billing/invoices/credit-notes#voiding). + """ + return cast( + CreditNote, + self._requestor.request( + "post", + "/v1/credit_notes/{id}/void".format(id=_util.sanitize_id(id)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_customer.py b/stripe/_customer.py index c095ce0e8..4b086ed6f 100644 --- a/stripe/_customer.py +++ b/stripe/_customer.py @@ -1382,16 +1382,7 @@ class SearchParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Customer": + def create(cls, **params: Unpack["Customer.CreateParams"]) -> "Customer": """ Creates a new customer object. """ @@ -1400,10 +1391,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -1412,12 +1399,7 @@ def create( def _cls_create_funding_instructions( cls, customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.CreateFundingInstructionsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.CreateFundingInstructionsParams"] ) -> "FundingInstructions": """ Retrieve funding instructions for a customer cash balance. If funding instructions do not yet exist for the customer, new @@ -1431,9 +1413,6 @@ def _cls_create_funding_instructions( "/v1/customers/{customer}/funding_instructions".format( customer=_util.sanitize_id(customer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1442,12 +1421,7 @@ def _cls_create_funding_instructions( @staticmethod def create_funding_instructions( customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.CreateFundingInstructionsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.CreateFundingInstructionsParams"] ) -> "FundingInstructions": """ Retrieve funding instructions for a customer cash balance. If funding instructions do not yet exist for the customer, new @@ -1458,11 +1432,7 @@ def create_funding_instructions( @overload def create_funding_instructions( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Customer.CreateFundingInstructionsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Customer.CreateFundingInstructionsParams"] ) -> "FundingInstructions": """ Retrieve funding instructions for a customer cash balance. If funding instructions do not yet exist for the customer, new @@ -1473,11 +1443,7 @@ def create_funding_instructions( @class_method_variant("_cls_create_funding_instructions") def create_funding_instructions( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Customer.CreateFundingInstructionsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Customer.CreateFundingInstructionsParams"] ) -> "FundingInstructions": """ Retrieve funding instructions for a customer cash balance. If funding instructions do not yet exist for the customer, new @@ -1491,7 +1457,6 @@ def create_funding_instructions( # pyright: ignore[reportGeneralTypeIssues] "/v1/customers/{customer}/funding_instructions".format( customer=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -1541,14 +1506,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def _cls_delete_discount( - cls, - customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.DeleteDiscountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, customer: str, **params: Unpack["Customer.DeleteDiscountParams"] ) -> "Discount": """ Removes the currently applied discount on a customer. @@ -1560,9 +1518,6 @@ def _cls_delete_discount( "/v1/customers/{customer}/discount".format( customer=_util.sanitize_id(customer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1570,13 +1525,7 @@ def _cls_delete_discount( @overload @staticmethod def delete_discount( - customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.DeleteDiscountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + customer: str, **params: Unpack["Customer.DeleteDiscountParams"] ) -> "Discount": """ Removes the currently applied discount on a customer. @@ -1585,11 +1534,7 @@ def delete_discount( @overload def delete_discount( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Customer.DeleteDiscountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Customer.DeleteDiscountParams"] ) -> "Discount": """ Removes the currently applied discount on a customer. @@ -1598,11 +1543,7 @@ def delete_discount( @class_method_variant("_cls_delete_discount") def delete_discount( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Customer.DeleteDiscountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Customer.DeleteDiscountParams"] ) -> "Discount": """ Removes the currently applied discount on a customer. @@ -1614,20 +1555,13 @@ def delete_discount( # pyright: ignore[reportGeneralTypeIssues] "/v1/customers/{customer}/discount".format( customer=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Customer.ListParams"] ) -> ListObject["Customer"]: """ Returns a list of your customers. The customers are returned sorted by creation date, with the most recent customers appearing first. @@ -1635,9 +1569,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -1653,12 +1584,7 @@ def list( def _cls_list_payment_methods( cls, customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.ListPaymentMethodsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.ListPaymentMethodsParams"] ) -> ListObject["PaymentMethod"]: """ Returns a list of PaymentMethods for a given Customer @@ -1670,9 +1596,6 @@ def _cls_list_payment_methods( "/v1/customers/{customer}/payment_methods".format( customer=_util.sanitize_id(customer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1680,13 +1603,7 @@ def _cls_list_payment_methods( @overload @staticmethod def list_payment_methods( - customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.ListPaymentMethodsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + customer: str, **params: Unpack["Customer.ListPaymentMethodsParams"] ) -> ListObject["PaymentMethod"]: """ Returns a list of PaymentMethods for a given Customer @@ -1695,11 +1612,7 @@ def list_payment_methods( @overload def list_payment_methods( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Customer.ListPaymentMethodsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Customer.ListPaymentMethodsParams"] ) -> ListObject["PaymentMethod"]: """ Returns a list of PaymentMethods for a given Customer @@ -1708,11 +1621,7 @@ def list_payment_methods( @class_method_variant("_cls_list_payment_methods") def list_payment_methods( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Customer.ListPaymentMethodsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Customer.ListPaymentMethodsParams"] ) -> ListObject["PaymentMethod"]: """ Returns a list of PaymentMethods for a given Customer @@ -1724,7 +1633,6 @@ def list_payment_methods( # pyright: ignore[reportGeneralTypeIssues] "/v1/customers/{customer}/payment_methods".format( customer=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -1760,12 +1668,7 @@ def _cls_retrieve_payment_method( cls, customer: str, payment_method: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.RetrievePaymentMethodParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.RetrievePaymentMethodParams"] ) -> "PaymentMethod": """ Retrieves a PaymentMethod object for a given Customer. @@ -1778,9 +1681,6 @@ def _cls_retrieve_payment_method( customer=_util.sanitize_id(customer), payment_method=_util.sanitize_id(payment_method), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1790,12 +1690,7 @@ def _cls_retrieve_payment_method( def retrieve_payment_method( customer: str, payment_method: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.RetrievePaymentMethodParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.RetrievePaymentMethodParams"] ) -> "PaymentMethod": """ Retrieves a PaymentMethod object for a given Customer. @@ -1806,10 +1701,7 @@ def retrieve_payment_method( def retrieve_payment_method( self, payment_method: str, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Customer.RetrievePaymentMethodParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.RetrievePaymentMethodParams"] ) -> "PaymentMethod": """ Retrieves a PaymentMethod object for a given Customer. @@ -1820,10 +1712,7 @@ def retrieve_payment_method( def retrieve_payment_method( # pyright: ignore[reportGeneralTypeIssues] self, payment_method: str, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Customer.RetrievePaymentMethodParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.RetrievePaymentMethodParams"] ) -> "PaymentMethod": """ Retrieves a PaymentMethod object for a given Customer. @@ -1836,7 +1725,6 @@ def retrieve_payment_method( # pyright: ignore[reportGeneralTypeIssues] customer=_util.sanitize_id(self.get("id")), payment_method=_util.sanitize_id(payment_method), ), - idempotency_key=idempotency_key, params=params, ), ) @@ -1863,12 +1751,7 @@ def search_auto_paging_iter( def create_balance_transaction( cls, customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.CreateBalanceTransactionParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.CreateBalanceTransactionParams"] ) -> "CustomerBalanceTransaction": """ Creates an immutable transaction that updates the customer's credit [balance](https://stripe.com/docs/billing/customer/balance). @@ -1880,9 +1763,6 @@ def create_balance_transaction( "/v1/customers/{customer}/balance_transactions".format( customer=_util.sanitize_id(customer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1892,12 +1772,7 @@ def retrieve_balance_transaction( cls, customer: str, transaction: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.RetrieveBalanceTransactionParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.RetrieveBalanceTransactionParams"] ) -> "CustomerBalanceTransaction": """ Retrieves a specific customer balance transaction that updated the customer's [balances](https://stripe.com/docs/billing/customer/balance). @@ -1910,9 +1785,6 @@ def retrieve_balance_transaction( customer=_util.sanitize_id(customer), transaction=_util.sanitize_id(transaction), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1922,12 +1794,7 @@ def modify_balance_transaction( cls, customer: str, transaction: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.ModifyBalanceTransactionParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.ModifyBalanceTransactionParams"] ) -> "CustomerBalanceTransaction": """ Most credit balance transaction fields are immutable, but you may update its description and metadata. @@ -1940,9 +1807,6 @@ def modify_balance_transaction( customer=_util.sanitize_id(customer), transaction=_util.sanitize_id(transaction), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1951,12 +1815,7 @@ def modify_balance_transaction( def list_balance_transactions( cls, customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.ListBalanceTransactionsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.ListBalanceTransactionsParams"] ) -> ListObject["CustomerBalanceTransaction"]: """ Returns a list of transactions that updated the customer's [balances](https://stripe.com/docs/billing/customer/balance). @@ -1968,9 +1827,6 @@ def list_balance_transactions( "/v1/customers/{customer}/balance_transactions".format( customer=_util.sanitize_id(customer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1980,12 +1836,7 @@ def retrieve_cash_balance_transaction( cls, customer: str, transaction: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.RetrieveCashBalanceTransactionParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.RetrieveCashBalanceTransactionParams"] ) -> "CustomerCashBalanceTransaction": """ Retrieves a specific cash balance transaction, which updated the customer's [cash balance](https://stripe.com/docs/payments/customer-balance). @@ -1998,9 +1849,6 @@ def retrieve_cash_balance_transaction( customer=_util.sanitize_id(customer), transaction=_util.sanitize_id(transaction), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2009,12 +1857,7 @@ def retrieve_cash_balance_transaction( def list_cash_balance_transactions( cls, customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.ListCashBalanceTransactionsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.ListCashBalanceTransactionsParams"] ) -> ListObject["CustomerCashBalanceTransaction"]: """ Returns a list of transactions that modified the customer's [cash balance](https://stripe.com/docs/payments/customer-balance). @@ -2026,23 +1869,13 @@ def list_cash_balance_transactions( "/v1/customers/{customer}/cash_balance_transactions".format( customer=_util.sanitize_id(customer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def create_source( - cls, - customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.CreateSourceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, customer: str, **params: Unpack["Customer.CreateSourceParams"] ) -> Union["Account", "BankAccount", "Card", "Source"]: """ When you create a new credit card, you must specify a customer or recipient on which to create it. @@ -2058,9 +1891,6 @@ def create_source( "/v1/customers/{customer}/sources".format( customer=_util.sanitize_id(customer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2070,12 +1900,7 @@ def retrieve_source( cls, customer: str, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.RetrieveSourceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.RetrieveSourceParams"] ) -> Union["Account", "BankAccount", "Card", "Source"]: """ Retrieve a specified source for a given customer. @@ -2088,9 +1913,6 @@ def retrieve_source( customer=_util.sanitize_id(customer), id=_util.sanitize_id(id), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2100,12 +1922,7 @@ def modify_source( cls, customer: str, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.ModifySourceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.ModifySourceParams"] ) -> Union["Account", "BankAccount", "Card", "Source"]: """ Update a specified source for a given customer. @@ -2118,9 +1935,6 @@ def modify_source( customer=_util.sanitize_id(customer), id=_util.sanitize_id(id), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2130,12 +1944,7 @@ def delete_source( cls, customer: str, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.DeleteSourceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.DeleteSourceParams"] ) -> Union["Account", "BankAccount", "Card", "Source"]: """ Delete a specified source for a given customer. @@ -2148,23 +1957,13 @@ def delete_source( customer=_util.sanitize_id(customer), id=_util.sanitize_id(id), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def list_sources( - cls, - customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.ListSourcesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, customer: str, **params: Unpack["Customer.ListSourcesParams"] ) -> ListObject[Union["Account", "BankAccount", "Card", "Source"]]: """ List sources for a specified customer. @@ -2176,23 +1975,13 @@ def list_sources( "/v1/customers/{customer}/sources".format( customer=_util.sanitize_id(customer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def create_tax_id( - cls, - customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.CreateTaxIdParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, customer: str, **params: Unpack["Customer.CreateTaxIdParams"] ) -> "TaxId": """ Creates a new tax_id object for a customer. @@ -2204,9 +1993,6 @@ def create_tax_id( "/v1/customers/{customer}/tax_ids".format( customer=_util.sanitize_id(customer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2216,12 +2002,7 @@ def retrieve_tax_id( cls, customer: str, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.RetrieveTaxIdParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.RetrieveTaxIdParams"] ) -> "TaxId": """ Retrieves the tax_id object with the given identifier. @@ -2234,9 +2015,6 @@ def retrieve_tax_id( customer=_util.sanitize_id(customer), id=_util.sanitize_id(id), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2246,12 +2024,7 @@ def delete_tax_id( cls, customer: str, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.DeleteTaxIdParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.DeleteTaxIdParams"] ) -> "TaxId": """ Deletes an existing tax_id object. @@ -2264,23 +2037,13 @@ def delete_tax_id( customer=_util.sanitize_id(customer), id=_util.sanitize_id(id), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def list_tax_ids( - cls, - customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.ListTaxIdsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, customer: str, **params: Unpack["Customer.ListTaxIdsParams"] ) -> ListObject["TaxId"]: """ Returns a list of tax IDs for a customer. @@ -2292,9 +2055,6 @@ def list_tax_ids( "/v1/customers/{customer}/tax_ids".format( customer=_util.sanitize_id(customer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2303,12 +2063,7 @@ def list_tax_ids( def modify_cash_balance( cls, customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.ModifyCashBalanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.ModifyCashBalanceParams"] ) -> "CashBalance": """ Changes the settings on a customer's cash balance. @@ -2320,9 +2075,6 @@ def modify_cash_balance( "/v1/customers/{customer}/cash_balance".format( customer=_util.sanitize_id(customer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2331,12 +2083,7 @@ def modify_cash_balance( def retrieve_cash_balance( cls, customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.RetrieveCashBalanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.RetrieveCashBalanceParams"] ) -> "CashBalance": """ Retrieves a customer's cash balance. @@ -2348,9 +2095,6 @@ def retrieve_cash_balance( "/v1/customers/{customer}/cash_balance".format( customer=_util.sanitize_id(customer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2362,12 +2106,7 @@ class TestHelpers(APIResourceTestHelpers["Customer"]): def _cls_fund_cash_balance( cls, customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.FundCashBalanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Customer.FundCashBalanceParams"] ) -> "CustomerCashBalanceTransaction": """ Create an incoming testmode bank transfer @@ -2379,9 +2118,6 @@ def _cls_fund_cash_balance( "/v1/test_helpers/customers/{customer}/fund_cash_balance".format( customer=_util.sanitize_id(customer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2389,13 +2125,7 @@ def _cls_fund_cash_balance( @overload @staticmethod def fund_cash_balance( - customer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Customer.FundCashBalanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + customer: str, **params: Unpack["Customer.FundCashBalanceParams"] ) -> "CustomerCashBalanceTransaction": """ Create an incoming testmode bank transfer @@ -2404,11 +2134,7 @@ def fund_cash_balance( @overload def fund_cash_balance( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Customer.FundCashBalanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Customer.FundCashBalanceParams"] ) -> "CustomerCashBalanceTransaction": """ Create an incoming testmode bank transfer @@ -2417,11 +2143,7 @@ def fund_cash_balance( @class_method_variant("_cls_fund_cash_balance") def fund_cash_balance( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Customer.FundCashBalanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Customer.FundCashBalanceParams"] ) -> "CustomerCashBalanceTransaction": """ Create an incoming testmode bank transfer @@ -2433,7 +2155,6 @@ def fund_cash_balance( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/customers/{customer}/fund_cash_balance".format( customer=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/_customer_balance_transaction.py b/stripe/_customer_balance_transaction.py index fef406002..4e08e6650 100644 --- a/stripe/_customer_balance_transaction.py +++ b/stripe/_customer_balance_transaction.py @@ -100,9 +100,7 @@ def instance_url(self): return "%s/%s/balance_transactions/%s" % (base, cust_extn, extn) @classmethod - def retrieve( - cls, id, api_key=None, **params - ) -> "CustomerBalanceTransaction": + def retrieve(cls, id, **params) -> "CustomerBalanceTransaction": raise NotImplementedError( "Can't retrieve a Customer Balance Transaction without a Customer ID. " "Use Customer.retrieve_customer_balance_transaction('cus_123', 'cbtxn_123')" diff --git a/stripe/_customer_balance_transaction_service.py b/stripe/_customer_balance_transaction_service.py new file mode 100644 index 000000000..73be56d15 --- /dev/null +++ b/stripe/_customer_balance_transaction_service.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._customer_balance_transaction import CustomerBalanceTransaction +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CustomerBalanceTransactionService(StripeService): + class CreateParams(TypedDict): + amount: int + """ + The integer amount in **cents (or local equivalent)** to apply to the customer's credit balance. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). Specifies the [`invoice_credit_balance`](https://stripe.com/docs/api/customers/object#customer_object-invoice_credit_balance) that this transaction will apply to. If the customer's `currency` is not set, it will be updated to this value. + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + def list( + self, + customer: str, + params: "CustomerBalanceTransactionService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[CustomerBalanceTransaction]: + """ + Returns a list of transactions that updated the customer's [balances](https://stripe.com/docs/billing/customer/balance). + """ + return cast( + ListObject[CustomerBalanceTransaction], + self._requestor.request( + "get", + "/v1/customers/{customer}/balance_transactions".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + customer: str, + params: "CustomerBalanceTransactionService.CreateParams", + options: RequestOptions = {}, + ) -> CustomerBalanceTransaction: + """ + Creates an immutable transaction that updates the customer's credit [balance](https://stripe.com/docs/billing/customer/balance). + """ + return cast( + CustomerBalanceTransaction, + self._requestor.request( + "post", + "/v1/customers/{customer}/balance_transactions".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + customer: str, + transaction: str, + params: "CustomerBalanceTransactionService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> CustomerBalanceTransaction: + """ + Retrieves a specific customer balance transaction that updated the customer's [balances](https://stripe.com/docs/billing/customer/balance). + """ + return cast( + CustomerBalanceTransaction, + self._requestor.request( + "get", + "/v1/customers/{customer}/balance_transactions/{transaction}".format( + customer=_util.sanitize_id(customer), + transaction=_util.sanitize_id(transaction), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + customer: str, + transaction: str, + params: "CustomerBalanceTransactionService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> CustomerBalanceTransaction: + """ + Most credit balance transaction fields are immutable, but you may update its description and metadata. + """ + return cast( + CustomerBalanceTransaction, + self._requestor.request( + "post", + "/v1/customers/{customer}/balance_transactions/{transaction}".format( + customer=_util.sanitize_id(customer), + transaction=_util.sanitize_id(transaction), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_customer_cash_balance_service.py b/stripe/_customer_cash_balance_service.py new file mode 100644 index 000000000..3bbbd7259 --- /dev/null +++ b/stripe/_customer_cash_balance_service.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._cash_balance import CashBalance +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CustomerCashBalanceService(StripeService): + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + settings: NotRequired[ + "CustomerCashBalanceService.UpdateParamsSettings" + ] + """ + A hash of settings for this cash balance. + """ + + class UpdateParamsSettings(TypedDict): + reconciliation_mode: NotRequired[ + "Literal['automatic', 'manual', 'merchant_default']" + ] + """ + Controls how funds transferred by the customer are applied to payment intents and invoices. Valid options are `automatic`, `manual`, or `merchant_default`. For more information about these reconciliation modes, see [Reconciliation](https://stripe.com/docs/payments/customer-balance/reconciliation). + """ + + def retrieve( + self, + customer: str, + params: "CustomerCashBalanceService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> CashBalance: + """ + Retrieves a customer's cash balance. + """ + return cast( + CashBalance, + self._requestor.request( + "get", + "/v1/customers/{customer}/cash_balance".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + customer: str, + params: "CustomerCashBalanceService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> CashBalance: + """ + Changes the settings on a customer's cash balance. + """ + return cast( + CashBalance, + self._requestor.request( + "post", + "/v1/customers/{customer}/cash_balance".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_customer_cash_balance_transaction.py b/stripe/_customer_cash_balance_transaction.py index 36ee4cd54..32cce2e4e 100644 --- a/stripe/_customer_cash_balance_transaction.py +++ b/stripe/_customer_cash_balance_transaction.py @@ -224,13 +224,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "CustomerCashBalanceTransaction.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["CustomerCashBalanceTransaction.ListParams"] ) -> ListObject["CustomerCashBalanceTransaction"]: """ Returns a list of transactions that modified the customer's [cash balance](https://stripe.com/docs/payments/customer-balance). @@ -238,9 +232,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_customer_cash_balance_transaction_service.py b/stripe/_customer_cash_balance_transaction_service.py new file mode 100644 index 000000000..0b23aa02f --- /dev/null +++ b/stripe/_customer_cash_balance_transaction_service.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._customer_cash_balance_transaction import ( + CustomerCashBalanceTransaction, +) +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class CustomerCashBalanceTransactionService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + customer: str, + params: "CustomerCashBalanceTransactionService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[CustomerCashBalanceTransaction]: + """ + Returns a list of transactions that modified the customer's [cash balance](https://stripe.com/docs/payments/customer-balance). + """ + return cast( + ListObject[CustomerCashBalanceTransaction], + self._requestor.request( + "get", + "/v1/customers/{customer}/cash_balance_transactions".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + customer: str, + transaction: str, + params: "CustomerCashBalanceTransactionService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> CustomerCashBalanceTransaction: + """ + Retrieves a specific cash balance transaction, which updated the customer's [cash balance](https://stripe.com/docs/payments/customer-balance). + """ + return cast( + CustomerCashBalanceTransaction, + self._requestor.request( + "get", + "/v1/customers/{customer}/cash_balance_transactions/{transaction}".format( + customer=_util.sanitize_id(customer), + transaction=_util.sanitize_id(transaction), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_customer_funding_instructions_service.py b/stripe/_customer_funding_instructions_service.py new file mode 100644 index 000000000..450ec212d --- /dev/null +++ b/stripe/_customer_funding_instructions_service.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._funding_instructions import FundingInstructions +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CustomerFundingInstructionsService(StripeService): + class CreateParams(TypedDict): + bank_transfer: "CustomerFundingInstructionsService.CreateParamsBankTransfer" + """ + Additional parameters for `bank_transfer` funding types + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + funding_type: Literal["bank_transfer"] + """ + The `funding_type` to get the instructions for. + """ + + class CreateParamsBankTransfer(TypedDict): + eu_bank_transfer: NotRequired[ + "CustomerFundingInstructionsService.CreateParamsBankTransferEuBankTransfer" + ] + """ + Configuration for eu_bank_transfer funding type. + """ + requested_address_types: NotRequired[ + "List[Literal['iban', 'sort_code', 'spei', 'zengin']]" + ] + """ + List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. + + Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. + """ + type: Literal[ + "eu_bank_transfer", + "gb_bank_transfer", + "jp_bank_transfer", + "mx_bank_transfer", + "us_bank_transfer", + ] + """ + The type of the `bank_transfer` + """ + + class CreateParamsBankTransferEuBankTransfer(TypedDict): + country: str + """ + The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + """ + + def create( + self, + customer: str, + params: "CustomerFundingInstructionsService.CreateParams", + options: RequestOptions = {}, + ) -> FundingInstructions: + """ + Retrieve funding instructions for a customer cash balance. If funding instructions do not yet exist for the customer, new + funding instructions will be created. If funding instructions have already been created for a given customer, the same + funding instructions will be retrieved. In other words, we will return the same funding instructions each time. + """ + return cast( + FundingInstructions, + self._requestor.request( + "post", + "/v1/customers/{customer}/funding_instructions".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_customer_payment_method_service.py b/stripe/_customer_payment_method_service.py new file mode 100644 index 000000000..703b6e234 --- /dev/null +++ b/stripe/_customer_payment_method_service.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._payment_method import PaymentMethod +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CustomerPaymentMethodService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + type: NotRequired[ + "Literal['acss_debit', 'affirm', 'afterpay_clearpay', 'alipay', 'au_becs_debit', 'bacs_debit', 'bancontact', 'blik', 'boleto', 'card', 'cashapp', 'customer_balance', 'eps', 'fpx', 'giropay', 'grabpay', 'ideal', 'klarna', 'konbini', 'link', 'oxxo', 'p24', 'paynow', 'paypal', 'pix', 'promptpay', 'revolut_pay', 'sepa_debit', 'sofort', 'us_bank_account', 'wechat_pay', 'zip']" + ] + """ + An optional filter on the list, based on the object `type` field. Without the filter, the list includes all current and future payment method types. If your integration expects only one type of payment method in the response, make sure to provide a type value in the request. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + customer: str, + params: "CustomerPaymentMethodService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[PaymentMethod]: + """ + Returns a list of PaymentMethods for a given Customer + """ + return cast( + ListObject[PaymentMethod], + self._requestor.request( + "get", + "/v1/customers/{customer}/payment_methods".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + customer: str, + payment_method: str, + params: "CustomerPaymentMethodService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> PaymentMethod: + """ + Retrieves a PaymentMethod object for a given Customer. + """ + return cast( + PaymentMethod, + self._requestor.request( + "get", + "/v1/customers/{customer}/payment_methods/{payment_method}".format( + customer=_util.sanitize_id(customer), + payment_method=_util.sanitize_id(payment_method), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_customer_payment_source_service.py b/stripe/_customer_payment_source_service.py new file mode 100644 index 000000000..69f9272af --- /dev/null +++ b/stripe/_customer_payment_source_service.py @@ -0,0 +1,324 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._account import Account +from stripe._bank_account import BankAccount +from stripe._card import Card +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._source import Source +from stripe._stripe_service import StripeService +from typing import Dict, List, Union, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CustomerPaymentSourceService(StripeService): + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + source: str + """ + Please refer to full [documentation](https://stripe.com/docs/api) instead. + """ + validate: NotRequired["bool"] + + class DeleteParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + object: NotRequired["str"] + """ + Filter sources according to a particular object type. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + account_holder_name: NotRequired["str"] + """ + The name of the person or business that owns the bank account. + """ + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + The type of entity that holds the account. This can be either `individual` or `company`. + """ + address_city: NotRequired["str"] + """ + City/District/Suburb/Town/Village. + """ + address_country: NotRequired["str"] + """ + Billing address country, if provided when creating card. + """ + address_line1: NotRequired["str"] + """ + Address line 1 (Street address/PO Box/Company name). + """ + address_line2: NotRequired["str"] + """ + Address line 2 (Apartment/Suite/Unit/Building). + """ + address_state: NotRequired["str"] + """ + State/County/Province/Region. + """ + address_zip: NotRequired["str"] + """ + ZIP or postal code. + """ + exp_month: NotRequired["str"] + """ + Two digit number representing the card's expiration month. + """ + exp_year: NotRequired["str"] + """ + Four digit number representing the card's expiration year. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: NotRequired["str"] + """ + Cardholder name. + """ + owner: NotRequired["CustomerPaymentSourceService.UpdateParamsOwner"] + + class UpdateParamsOwner(TypedDict): + address: NotRequired[ + "CustomerPaymentSourceService.UpdateParamsOwnerAddress" + ] + """ + Owner's address. + """ + email: NotRequired["str"] + """ + Owner's email address. + """ + name: NotRequired["str"] + """ + Owner's full name. + """ + phone: NotRequired["str"] + """ + Owner's phone number. + """ + + class UpdateParamsOwnerAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class VerifyParams(TypedDict): + amounts: NotRequired["List[int]"] + """ + Two positive integers, in *cents*, equal to the values of the microdeposits sent to the bank account. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + customer: str, + params: "CustomerPaymentSourceService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Union[Account, BankAccount, Card, Source]]: + """ + List sources for a specified customer. + """ + return cast( + ListObject[Union[Account, BankAccount, Card, Source]], + self._requestor.request( + "get", + "/v1/customers/{customer}/sources".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + customer: str, + params: "CustomerPaymentSourceService.CreateParams", + options: RequestOptions = {}, + ) -> Union[Account, BankAccount, Card, Source]: + """ + When you create a new credit card, you must specify a customer or recipient on which to create it. + + If the card's owner has no default card, then the new card will become the default. + However, if the owner already has a default, then it will not change. + To change the default, you should [update the customer](https://stripe.com/docs/api#update_customer) to have a new default_source. + """ + return cast( + Union[Account, BankAccount, Card, Source], + self._requestor.request( + "post", + "/v1/customers/{customer}/sources".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + customer: str, + id: str, + params: "CustomerPaymentSourceService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Union[Account, BankAccount, Card, Source]: + """ + Retrieve a specified source for a given customer. + """ + return cast( + Union[Account, BankAccount, Card, Source], + self._requestor.request( + "get", + "/v1/customers/{customer}/sources/{id}".format( + customer=_util.sanitize_id(customer), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + customer: str, + id: str, + params: "CustomerPaymentSourceService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Union[Account, BankAccount, Card, Source]: + """ + Update a specified source for a given customer. + """ + return cast( + Union[Account, BankAccount, Card, Source], + self._requestor.request( + "post", + "/v1/customers/{customer}/sources/{id}".format( + customer=_util.sanitize_id(customer), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def delete( + self, + customer: str, + id: str, + params: "CustomerPaymentSourceService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> Union[Account, BankAccount, Card, Source]: + """ + Delete a specified source for a given customer. + """ + return cast( + Union[Account, BankAccount, Card, Source], + self._requestor.request( + "delete", + "/v1/customers/{customer}/sources/{id}".format( + customer=_util.sanitize_id(customer), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def verify( + self, + customer: str, + id: str, + params: "CustomerPaymentSourceService.VerifyParams" = {}, + options: RequestOptions = {}, + ) -> BankAccount: + """ + Verify a specified bank account for a given customer. + """ + return cast( + BankAccount, + self._requestor.request( + "post", + "/v1/customers/{customer}/sources/{id}/verify".format( + customer=_util.sanitize_id(customer), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_customer_service.py b/stripe/_customer_service.py new file mode 100644 index 000000000..01771c31b --- /dev/null +++ b/stripe/_customer_service.py @@ -0,0 +1,798 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._customer import Customer +from stripe._customer_balance_transaction_service import ( + CustomerBalanceTransactionService, +) +from stripe._customer_cash_balance_service import CustomerCashBalanceService +from stripe._customer_cash_balance_transaction_service import ( + CustomerCashBalanceTransactionService, +) +from stripe._customer_funding_instructions_service import ( + CustomerFundingInstructionsService, +) +from stripe._customer_payment_method_service import ( + CustomerPaymentMethodService, +) +from stripe._customer_payment_source_service import ( + CustomerPaymentSourceService, +) +from stripe._customer_tax_id_service import CustomerTaxIdService +from stripe._discount import Discount +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._search_result_object import SearchResultObject +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CustomerService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.cash_balance = CustomerCashBalanceService(self._requestor) + self.balance_transactions = CustomerBalanceTransactionService( + self._requestor, + ) + self.cash_balance_transactions = CustomerCashBalanceTransactionService( + self._requestor, + ) + self.payment_sources = CustomerPaymentSourceService(self._requestor) + self.tax_ids = CustomerTaxIdService(self._requestor) + self.payment_methods = CustomerPaymentMethodService(self._requestor) + self.funding_instructions = CustomerFundingInstructionsService( + self._requestor, + ) + + class CreateParams(TypedDict): + address: NotRequired["Literal['']|CustomerService.CreateParamsAddress"] + """ + The customer's address. + """ + balance: NotRequired["int"] + """ + An integer amount in cents (or local equivalent) that represents the customer's current balance, which affect the customer's future invoices. A negative amount represents a credit that decreases the amount due on an invoice; a positive amount increases the amount due on an invoice. + """ + cash_balance: NotRequired["CustomerService.CreateParamsCashBalance"] + """ + Balance information and default balance settings for this customer. + """ + coupon: NotRequired["str"] + description: NotRequired["str"] + """ + An arbitrary string that you can attach to a customer object. It is displayed alongside the customer in the dashboard. + """ + email: NotRequired["str"] + """ + Customer's email address. It's displayed alongside the customer in your dashboard and can be useful for searching and tracking. This may be up to *512 characters*. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice_prefix: NotRequired["str"] + """ + The prefix for the customer used to generate unique invoice numbers. Must be 3–12 uppercase letters or numbers. + """ + invoice_settings: NotRequired[ + "CustomerService.CreateParamsInvoiceSettings" + ] + """ + Default invoice settings for this customer. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: NotRequired["str"] + """ + The customer's full name or business name. + """ + next_invoice_sequence: NotRequired["int"] + """ + The sequence to be used on the customer's next invoice. Defaults to 1. + """ + payment_method: NotRequired["str"] + phone: NotRequired["str"] + """ + The customer's phone number. + """ + preferred_locales: NotRequired["List[str]"] + """ + Customer's preferred languages, ordered by preference. + """ + promotion_code: NotRequired["str"] + """ + The API ID of a promotion code to apply to the customer. The customer will have a discount applied on all recurring payments. Charges you create through the API will not have the discount. + """ + shipping: NotRequired[ + "Literal['']|CustomerService.CreateParamsShipping" + ] + """ + The customer's shipping information. Appears on invoices emailed to this customer. + """ + source: NotRequired["str"] + tax: NotRequired["CustomerService.CreateParamsTax"] + """ + Tax details about the customer. + """ + tax_exempt: NotRequired[ + "Literal['']|Literal['exempt', 'none', 'reverse']" + ] + """ + The customer's tax exemption. One of `none`, `exempt`, or `reverse`. + """ + tax_id_data: NotRequired[ + "List[CustomerService.CreateParamsTaxIdDatum]" + ] + """ + The customer's tax IDs. + """ + test_clock: NotRequired["str"] + """ + ID of the test clock to attach to the customer. + """ + validate: NotRequired["bool"] + + class CreateParamsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsCashBalance(TypedDict): + settings: NotRequired[ + "CustomerService.CreateParamsCashBalanceSettings" + ] + """ + Settings controlling the behavior of the customer's cash balance, + such as reconciliation of funds received. + """ + + class CreateParamsCashBalanceSettings(TypedDict): + reconciliation_mode: NotRequired[ + "Literal['automatic', 'manual', 'merchant_default']" + ] + """ + Controls how funds transferred by the customer are applied to payment intents and invoices. Valid options are `automatic`, `manual`, or `merchant_default`. For more information about these reconciliation modes, see [Reconciliation](https://stripe.com/docs/payments/customer-balance/reconciliation). + """ + + class CreateParamsInvoiceSettings(TypedDict): + custom_fields: NotRequired[ + "Literal['']|List[CustomerService.CreateParamsInvoiceSettingsCustomField]" + ] + """ + The list of up to 4 default custom fields to be displayed on invoices for this customer. When updating, pass an empty string to remove previously-defined fields. + """ + default_payment_method: NotRequired["str"] + """ + ID of a payment method that's attached to the customer, to be used as the customer's default payment method for subscriptions and invoices. + """ + footer: NotRequired["str"] + """ + Default footer to be displayed on invoices for this customer. + """ + rendering_options: NotRequired[ + "Literal['']|CustomerService.CreateParamsInvoiceSettingsRenderingOptions" + ] + """ + Default options for invoice PDF rendering for this customer. + """ + + class CreateParamsInvoiceSettingsCustomField(TypedDict): + name: str + """ + The name of the custom field. This may be up to 30 characters. + """ + value: str + """ + The value of the custom field. This may be up to 30 characters. + """ + + class CreateParamsInvoiceSettingsRenderingOptions(TypedDict): + amount_tax_display: NotRequired[ + "Literal['']|Literal['exclude_tax', 'include_inclusive_tax']" + ] + """ + How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + """ + + class CreateParamsShipping(TypedDict): + address: "CustomerService.CreateParamsShippingAddress" + """ + Customer shipping address. + """ + name: str + """ + Customer name. + """ + phone: NotRequired["str"] + """ + Customer phone (including extension). + """ + + class CreateParamsShippingAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsTax(TypedDict): + ip_address: NotRequired["Literal['']|str"] + """ + A recent IP address of the customer used for tax reporting and tax location inference. Stripe recommends updating the IP address when a new PaymentMethod is attached or the address field on the customer is updated. We recommend against updating this field more frequently since it could result in unexpected tax location/reporting outcomes. + """ + validate_location: NotRequired["Literal['deferred', 'immediately']"] + """ + A flag that indicates when Stripe should validate the customer tax location. Defaults to `deferred`. + """ + + class CreateParamsTaxIdDatum(TypedDict): + type: Literal[ + "ad_nrt", + "ae_trn", + "ar_cuit", + "au_abn", + "au_arn", + "bg_uic", + "bo_tin", + "br_cnpj", + "br_cpf", + "ca_bn", + "ca_gst_hst", + "ca_pst_bc", + "ca_pst_mb", + "ca_pst_sk", + "ca_qst", + "ch_vat", + "cl_tin", + "cn_tin", + "co_nit", + "cr_tin", + "do_rcn", + "ec_ruc", + "eg_tin", + "es_cif", + "eu_oss_vat", + "eu_vat", + "gb_vat", + "ge_vat", + "hk_br", + "hu_tin", + "id_npwp", + "il_vat", + "in_gst", + "is_vat", + "jp_cn", + "jp_rn", + "jp_trn", + "ke_pin", + "kr_brn", + "li_uid", + "mx_rfc", + "my_frp", + "my_itn", + "my_sst", + "no_vat", + "nz_gst", + "pe_ruc", + "ph_tin", + "ro_tin", + "rs_pib", + "ru_inn", + "ru_kpp", + "sa_vat", + "sg_gst", + "sg_uen", + "si_tin", + "sv_nit", + "th_vat", + "tr_tin", + "tw_vat", + "ua_vat", + "us_ein", + "uy_ruc", + "ve_rif", + "vn_tin", + "za_vat", + ] + """ + Type of the tax ID, one of `ad_nrt`, `ae_trn`, `ar_cuit`, `au_abn`, `au_arn`, `bg_uic`, `bo_tin`, `br_cnpj`, `br_cpf`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `ch_vat`, `cl_tin`, `cn_tin`, `co_nit`, `cr_tin`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `hk_br`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kr_brn`, `li_uid`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `no_vat`, `nz_gst`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sv_nit`, `th_vat`, `tr_tin`, `tw_vat`, `ua_vat`, `us_ein`, `uy_ruc`, `ve_rif`, `vn_tin`, or `za_vat` + """ + value: str + """ + Value of the tax ID. + """ + + class DeleteDiscountParams(TypedDict): + pass + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + created: NotRequired["CustomerService.ListParamsCreated|int"] + email: NotRequired["str"] + """ + A case-sensitive filter on the list based on the customer's `email` field. The value must be a string. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + test_clock: NotRequired["str"] + """ + Provides a list of customers that are associated with the specified test clock. The response will not include customers with test clocks if this parameter is not set. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class SearchParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + page: NotRequired["str"] + """ + A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + """ + query: str + """ + The search query string. See [search query language](https://stripe.com/docs/search#search-query-language) and the list of supported [query fields for customers](https://stripe.com/docs/search#query-fields-for-customers). + """ + + class UpdateParams(TypedDict): + address: NotRequired["Literal['']|CustomerService.UpdateParamsAddress"] + """ + The customer's address. + """ + balance: NotRequired["int"] + """ + An integer amount in cents (or local equivalent) that represents the customer's current balance, which affect the customer's future invoices. A negative amount represents a credit that decreases the amount due on an invoice; a positive amount increases the amount due on an invoice. + """ + cash_balance: NotRequired["CustomerService.UpdateParamsCashBalance"] + """ + Balance information and default balance settings for this customer. + """ + coupon: NotRequired["str"] + default_source: NotRequired["str"] + """ + If you are using payment methods created via the PaymentMethods API, see the [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/update#update_customer-invoice_settings-default_payment_method) parameter. + + Provide the ID of a payment source already attached to this customer to make it this customer's default payment source. + + If you want to add a new payment source and make it the default, see the [source](https://stripe.com/docs/api/customers/update#update_customer-source) property. + """ + description: NotRequired["str"] + """ + An arbitrary string that you can attach to a customer object. It is displayed alongside the customer in the dashboard. + """ + email: NotRequired["str"] + """ + Customer's email address. It's displayed alongside the customer in your dashboard and can be useful for searching and tracking. This may be up to *512 characters*. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice_prefix: NotRequired["str"] + """ + The prefix for the customer used to generate unique invoice numbers. Must be 3–12 uppercase letters or numbers. + """ + invoice_settings: NotRequired[ + "CustomerService.UpdateParamsInvoiceSettings" + ] + """ + Default invoice settings for this customer. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: NotRequired["str"] + """ + The customer's full name or business name. + """ + next_invoice_sequence: NotRequired["int"] + """ + The sequence to be used on the customer's next invoice. Defaults to 1. + """ + phone: NotRequired["str"] + """ + The customer's phone number. + """ + preferred_locales: NotRequired["List[str]"] + """ + Customer's preferred languages, ordered by preference. + """ + promotion_code: NotRequired["str"] + """ + The API ID of a promotion code to apply to the customer. The customer will have a discount applied on all recurring payments. Charges you create through the API will not have the discount. + """ + shipping: NotRequired[ + "Literal['']|CustomerService.UpdateParamsShipping" + ] + """ + The customer's shipping information. Appears on invoices emailed to this customer. + """ + source: NotRequired["str"] + tax: NotRequired["CustomerService.UpdateParamsTax"] + """ + Tax details about the customer. + """ + tax_exempt: NotRequired[ + "Literal['']|Literal['exempt', 'none', 'reverse']" + ] + """ + The customer's tax exemption. One of `none`, `exempt`, or `reverse`. + """ + validate: NotRequired["bool"] + + class UpdateParamsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsCashBalance(TypedDict): + settings: NotRequired[ + "CustomerService.UpdateParamsCashBalanceSettings" + ] + """ + Settings controlling the behavior of the customer's cash balance, + such as reconciliation of funds received. + """ + + class UpdateParamsCashBalanceSettings(TypedDict): + reconciliation_mode: NotRequired[ + "Literal['automatic', 'manual', 'merchant_default']" + ] + """ + Controls how funds transferred by the customer are applied to payment intents and invoices. Valid options are `automatic`, `manual`, or `merchant_default`. For more information about these reconciliation modes, see [Reconciliation](https://stripe.com/docs/payments/customer-balance/reconciliation). + """ + + class UpdateParamsInvoiceSettings(TypedDict): + custom_fields: NotRequired[ + "Literal['']|List[CustomerService.UpdateParamsInvoiceSettingsCustomField]" + ] + """ + The list of up to 4 default custom fields to be displayed on invoices for this customer. When updating, pass an empty string to remove previously-defined fields. + """ + default_payment_method: NotRequired["str"] + """ + ID of a payment method that's attached to the customer, to be used as the customer's default payment method for subscriptions and invoices. + """ + footer: NotRequired["str"] + """ + Default footer to be displayed on invoices for this customer. + """ + rendering_options: NotRequired[ + "Literal['']|CustomerService.UpdateParamsInvoiceSettingsRenderingOptions" + ] + """ + Default options for invoice PDF rendering for this customer. + """ + + class UpdateParamsInvoiceSettingsCustomField(TypedDict): + name: str + """ + The name of the custom field. This may be up to 30 characters. + """ + value: str + """ + The value of the custom field. This may be up to 30 characters. + """ + + class UpdateParamsInvoiceSettingsRenderingOptions(TypedDict): + amount_tax_display: NotRequired[ + "Literal['']|Literal['exclude_tax', 'include_inclusive_tax']" + ] + """ + How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + """ + + class UpdateParamsShipping(TypedDict): + address: "CustomerService.UpdateParamsShippingAddress" + """ + Customer shipping address. + """ + name: str + """ + Customer name. + """ + phone: NotRequired["str"] + """ + Customer phone (including extension). + """ + + class UpdateParamsShippingAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsTax(TypedDict): + ip_address: NotRequired["Literal['']|str"] + """ + A recent IP address of the customer used for tax reporting and tax location inference. Stripe recommends updating the IP address when a new PaymentMethod is attached or the address field on the customer is updated. We recommend against updating this field more frequently since it could result in unexpected tax location/reporting outcomes. + """ + validate_location: NotRequired["Literal['deferred', 'immediately']"] + """ + A flag that indicates when Stripe should validate the customer tax location. Defaults to `deferred`. + """ + + def delete( + self, + customer: str, + params: "CustomerService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> Customer: + """ + Permanently deletes a customer. It cannot be undone. Also immediately cancels any active subscriptions on the customer. + """ + return cast( + Customer, + self._requestor.request( + "delete", + "/v1/customers/{customer}".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + customer: str, + params: "CustomerService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Customer: + """ + Retrieves a Customer object. + """ + return cast( + Customer, + self._requestor.request( + "get", + "/v1/customers/{customer}".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + customer: str, + params: "CustomerService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Customer: + """ + Updates the specified customer by setting the values of the parameters passed. Any parameters not provided will be left unchanged. For example, if you pass the source parameter, that becomes the customer's active source (e.g., a card) to be used for all charges in the future. When you update a customer to a new valid card source by passing the source parameter: for each of the customer's current subscriptions, if the subscription bills automatically and is in the past_due state, then the latest open invoice for the subscription with automatic collection enabled will be retried. This retry will not count as an automatic retry, and will not affect the next regularly scheduled payment for the invoice. Changing the default_source for a customer will not trigger this behavior. + + This request accepts mostly the same arguments as the customer creation call. + """ + return cast( + Customer, + self._requestor.request( + "post", + "/v1/customers/{customer}".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def delete_discount( + self, + customer: str, + params: "CustomerService.DeleteDiscountParams" = {}, + options: RequestOptions = {}, + ) -> Discount: + """ + Removes the currently applied discount on a customer. + """ + return cast( + Discount, + self._requestor.request( + "delete", + "/v1/customers/{customer}/discount".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "CustomerService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Customer]: + """ + Returns a list of your customers. The customers are returned sorted by creation date, with the most recent customers appearing first. + """ + return cast( + ListObject[Customer], + self._requestor.request( + "get", + "/v1/customers", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "CustomerService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Customer: + """ + Creates a new customer object. + """ + return cast( + Customer, + self._requestor.request( + "post", + "/v1/customers", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def search( + self, + params: "CustomerService.SearchParams", + options: RequestOptions = {}, + ) -> SearchResultObject[Customer]: + """ + Search for customers you've previously created using Stripe's [Search Query Language](https://stripe.com/docs/search#search-query-language). + Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating + conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up + to an hour behind during outages. Search functionality is not available to merchants in India. + """ + return cast( + SearchResultObject[Customer], + self._requestor.request( + "get", + "/v1/customers/search", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_customer_session.py b/stripe/_customer_session.py index b23e66c24..4d85e5763 100644 --- a/stripe/_customer_session.py +++ b/stripe/_customer_session.py @@ -124,14 +124,7 @@ class CreateParamsComponentsPricingTable(TypedDict): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "CustomerSession.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["CustomerSession.CreateParams"] ) -> "CustomerSession": """ Creates a customer session object that includes a single-use client secret that you can use on your front-end to grant client-side API access for certain customer resources. @@ -141,10 +134,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) diff --git a/stripe/_customer_session_service.py b/stripe/_customer_session_service.py new file mode 100644 index 000000000..80cd7ba74 --- /dev/null +++ b/stripe/_customer_session_service.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._customer_session import CustomerSession +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class CustomerSessionService(StripeService): + class CreateParams(TypedDict): + components: "CustomerSessionService.CreateParamsComponents" + """ + Configuration for each component. Exactly 1 component must be enabled. + """ + customer: str + """ + The ID of an existing customer for which to create the customer session. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CreateParamsComponents(TypedDict): + buy_button: NotRequired[ + "CustomerSessionService.CreateParamsComponentsBuyButton" + ] + """ + Configuration for buy button. + """ + pricing_table: NotRequired[ + "CustomerSessionService.CreateParamsComponentsPricingTable" + ] + """ + Configuration for the pricing table. + """ + + class CreateParamsComponentsBuyButton(TypedDict): + enabled: bool + """ + Whether the buy button is enabled. + """ + + class CreateParamsComponentsPricingTable(TypedDict): + enabled: bool + """ + Whether the pricing table is enabled. + """ + + def create( + self, + params: "CustomerSessionService.CreateParams", + options: RequestOptions = {}, + ) -> CustomerSession: + """ + Creates a customer session object that includes a single-use client secret that you can use on your front-end to grant client-side API access for certain customer resources. + """ + return cast( + CustomerSession, + self._requestor.request( + "post", + "/v1/customer_sessions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_customer_tax_id_service.py b/stripe/_customer_tax_id_service.py new file mode 100644 index 000000000..91442a1e2 --- /dev/null +++ b/stripe/_customer_tax_id_service.py @@ -0,0 +1,215 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe._tax_id import TaxId +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CustomerTaxIdService(StripeService): + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + type: Literal[ + "ad_nrt", + "ae_trn", + "ar_cuit", + "au_abn", + "au_arn", + "bg_uic", + "bo_tin", + "br_cnpj", + "br_cpf", + "ca_bn", + "ca_gst_hst", + "ca_pst_bc", + "ca_pst_mb", + "ca_pst_sk", + "ca_qst", + "ch_vat", + "cl_tin", + "cn_tin", + "co_nit", + "cr_tin", + "do_rcn", + "ec_ruc", + "eg_tin", + "es_cif", + "eu_oss_vat", + "eu_vat", + "gb_vat", + "ge_vat", + "hk_br", + "hu_tin", + "id_npwp", + "il_vat", + "in_gst", + "is_vat", + "jp_cn", + "jp_rn", + "jp_trn", + "ke_pin", + "kr_brn", + "li_uid", + "mx_rfc", + "my_frp", + "my_itn", + "my_sst", + "no_vat", + "nz_gst", + "pe_ruc", + "ph_tin", + "ro_tin", + "rs_pib", + "ru_inn", + "ru_kpp", + "sa_vat", + "sg_gst", + "sg_uen", + "si_tin", + "sv_nit", + "th_vat", + "tr_tin", + "tw_vat", + "ua_vat", + "us_ein", + "uy_ruc", + "ve_rif", + "vn_tin", + "za_vat", + ] + """ + Type of the tax ID, one of `ad_nrt`, `ae_trn`, `ar_cuit`, `au_abn`, `au_arn`, `bg_uic`, `bo_tin`, `br_cnpj`, `br_cpf`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `ch_vat`, `cl_tin`, `cn_tin`, `co_nit`, `cr_tin`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `hk_br`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kr_brn`, `li_uid`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `no_vat`, `nz_gst`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sv_nit`, `th_vat`, `tr_tin`, `tw_vat`, `ua_vat`, `us_ein`, `uy_ruc`, `ve_rif`, `vn_tin`, or `za_vat` + """ + value: str + """ + Value of the tax ID. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def delete( + self, + customer: str, + id: str, + params: "CustomerTaxIdService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> TaxId: + """ + Deletes an existing tax_id object. + """ + return cast( + TaxId, + self._requestor.request( + "delete", + "/v1/customers/{customer}/tax_ids/{id}".format( + customer=_util.sanitize_id(customer), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + customer: str, + id: str, + params: "CustomerTaxIdService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> TaxId: + """ + Retrieves the tax_id object with the given identifier. + """ + return cast( + TaxId, + self._requestor.request( + "get", + "/v1/customers/{customer}/tax_ids/{id}".format( + customer=_util.sanitize_id(customer), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + customer: str, + params: "CustomerTaxIdService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[TaxId]: + """ + Returns a list of tax IDs for a customer. + """ + return cast( + ListObject[TaxId], + self._requestor.request( + "get", + "/v1/customers/{customer}/tax_ids".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + customer: str, + params: "CustomerTaxIdService.CreateParams", + options: RequestOptions = {}, + ) -> TaxId: + """ + Creates a new tax_id object for a customer. + """ + return cast( + TaxId, + self._requestor.request( + "post", + "/v1/customers/{customer}/tax_ids".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_dispute.py b/stripe/_dispute.py index 1b26829c0..3ee8a41eb 100644 --- a/stripe/_dispute.py +++ b/stripe/_dispute.py @@ -442,14 +442,7 @@ class RetrieveParams(RequestOptions): @classmethod def _cls_close( - cls, - dispute: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Dispute.CloseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, dispute: str, **params: Unpack["Dispute.CloseParams"] ) -> "Dispute": """ Closing the dispute for a charge indicates that you do not have any evidence to submit and are essentially dismissing the dispute, acknowledging it as lost. @@ -463,9 +456,6 @@ def _cls_close( "/v1/disputes/{dispute}/close".format( dispute=_util.sanitize_id(dispute) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -473,13 +463,7 @@ def _cls_close( @overload @staticmethod def close( - dispute: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Dispute.CloseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + dispute: str, **params: Unpack["Dispute.CloseParams"] ) -> "Dispute": """ Closing the dispute for a charge indicates that you do not have any evidence to submit and are essentially dismissing the dispute, acknowledging it as lost. @@ -489,13 +473,7 @@ def close( ... @overload - def close( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Dispute.CloseParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Dispute": + def close(self, **params: Unpack["Dispute.CloseParams"]) -> "Dispute": """ Closing the dispute for a charge indicates that you do not have any evidence to submit and are essentially dismissing the dispute, acknowledging it as lost. @@ -505,11 +483,7 @@ def close( @class_method_variant("_cls_close") def close( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Dispute.CloseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Dispute.CloseParams"] ) -> "Dispute": """ Closing the dispute for a charge indicates that you do not have any evidence to submit and are essentially dismissing the dispute, acknowledging it as lost. @@ -523,20 +497,13 @@ def close( # pyright: ignore[reportGeneralTypeIssues] "/v1/disputes/{dispute}/close".format( dispute=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Dispute.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Dispute.ListParams"] ) -> ListObject["Dispute"]: """ Returns a list of your disputes. @@ -544,9 +511,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_dispute_service.py b/stripe/_dispute_service.py new file mode 100644 index 000000000..0b85feedf --- /dev/null +++ b/stripe/_dispute_service.py @@ -0,0 +1,289 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._dispute import Dispute +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class DisputeService(StripeService): + class CloseParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ListParams(TypedDict): + charge: NotRequired["str"] + """ + Only return disputes associated to the charge specified by this charge ID. + """ + created: NotRequired["DisputeService.ListParamsCreated|int"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + payment_intent: NotRequired["str"] + """ + Only return disputes associated to the PaymentIntent specified by this PaymentIntent ID. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + evidence: NotRequired["DisputeService.UpdateParamsEvidence"] + """ + Evidence to upload, to respond to a dispute. Updating any field in the hash will submit all fields in the hash for review. The combined character count of all fields is limited to 150,000. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + submit: NotRequired["bool"] + """ + Whether to immediately submit evidence to the bank. If `false`, evidence is staged on the dispute. Staged evidence is visible in the API and Dashboard, and can be submitted to the bank by making another request with this attribute set to `true` (the default). + """ + + class UpdateParamsEvidence(TypedDict): + access_activity_log: NotRequired["str"] + """ + Any server or activity logs showing proof that the customer accessed or downloaded the purchased digital product. This information should include IP addresses, corresponding timestamps, and any detailed recorded activity. Has a maximum character count of 20,000. + """ + billing_address: NotRequired["str"] + """ + The billing address provided by the customer. + """ + cancellation_policy: NotRequired["str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Your subscription cancellation policy, as shown to the customer. + """ + cancellation_policy_disclosure: NotRequired["str"] + """ + An explanation of how and when the customer was shown your refund policy prior to purchase. Has a maximum character count of 20,000. + """ + cancellation_rebuttal: NotRequired["str"] + """ + A justification for why the customer's subscription was not canceled. Has a maximum character count of 20,000. + """ + customer_communication: NotRequired["str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any communication with the customer that you feel is relevant to your case. Examples include emails proving that the customer received the product or service, or demonstrating their use of or satisfaction with the product or service. + """ + customer_email_address: NotRequired["str"] + """ + The email address of the customer. + """ + customer_name: NotRequired["str"] + """ + The name of the customer. + """ + customer_purchase_ip: NotRequired["str"] + """ + The IP address that the customer used when making the purchase. + """ + customer_signature: NotRequired["str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A relevant document or contract showing the customer's signature. + """ + duplicate_charge_documentation: NotRequired["str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation for the prior charge that can uniquely identify the charge, such as a receipt, shipping label, work order, etc. This document should be paired with a similar document from the disputed payment that proves the two payments are separate. + """ + duplicate_charge_explanation: NotRequired["str"] + """ + An explanation of the difference between the disputed charge versus the prior charge that appears to be a duplicate. Has a maximum character count of 20,000. + """ + duplicate_charge_id: NotRequired["str"] + """ + The Stripe ID for the prior charge which appears to be a duplicate of the disputed charge. + """ + product_description: NotRequired["str"] + """ + A description of the product or service that was sold. Has a maximum character count of 20,000. + """ + receipt: NotRequired["str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any receipt or message sent to the customer notifying them of the charge. + """ + refund_policy: NotRequired["str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Your refund policy, as shown to the customer. + """ + refund_policy_disclosure: NotRequired["str"] + """ + Documentation demonstrating that the customer was shown your refund policy prior to purchase. Has a maximum character count of 20,000. + """ + refund_refusal_explanation: NotRequired["str"] + """ + A justification for why the customer is not entitled to a refund. Has a maximum character count of 20,000. + """ + service_date: NotRequired["str"] + """ + The date on which the customer received or began receiving the purchased service, in a clear human-readable format. + """ + service_documentation: NotRequired["str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation showing proof that a service was provided to the customer. This could include a copy of a signed contract, work order, or other form of written agreement. + """ + shipping_address: NotRequired["str"] + """ + The address to which a physical product was shipped. You should try to include as complete address information as possible. + """ + shipping_carrier: NotRequired["str"] + """ + The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. If multiple carriers were used for this purchase, please separate them with commas. + """ + shipping_date: NotRequired["str"] + """ + The date on which a physical product began its route to the shipping address, in a clear human-readable format. + """ + shipping_documentation: NotRequired["str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation showing proof that a product was shipped to the customer at the same address the customer provided to you. This could include a copy of the shipment receipt, shipping label, etc. It should show the customer's full shipping address, if possible. + """ + shipping_tracking_number: NotRequired["str"] + """ + The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. + """ + uncategorized_file: NotRequired["str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any additional evidence or statements. + """ + uncategorized_text: NotRequired["str"] + """ + Any additional evidence or statements. Has a maximum character count of 20,000. + """ + + def list( + self, + params: "DisputeService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Dispute]: + """ + Returns a list of your disputes. + """ + return cast( + ListObject[Dispute], + self._requestor.request( + "get", + "/v1/disputes", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + dispute: str, + params: "DisputeService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Dispute: + """ + Retrieves the dispute with the given ID. + """ + return cast( + Dispute, + self._requestor.request( + "get", + "/v1/disputes/{dispute}".format( + dispute=_util.sanitize_id(dispute), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + dispute: str, + params: "DisputeService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Dispute: + """ + When you get a dispute, contacting your customer is always the best first step. If that doesn't work, you can submit evidence to help us resolve the dispute in your favor. You can do this in your [dashboard](https://dashboard.stripe.com/disputes), but if you prefer, you can use the API to submit evidence programmatically. + + Depending on your dispute type, different evidence fields will give you a better chance of winning your dispute. To figure out which evidence fields to provide, see our [guide to dispute types](https://stripe.com/docs/disputes/categories). + """ + return cast( + Dispute, + self._requestor.request( + "post", + "/v1/disputes/{dispute}".format( + dispute=_util.sanitize_id(dispute), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def close( + self, + dispute: str, + params: "DisputeService.CloseParams" = {}, + options: RequestOptions = {}, + ) -> Dispute: + """ + Closing the dispute for a charge indicates that you do not have any evidence to submit and are essentially dismissing the dispute, acknowledging it as lost. + + The status of the dispute will change from needs_response to lost. Closing a dispute is irreversible. + """ + return cast( + Dispute, + self._requestor.request( + "post", + "/v1/disputes/{dispute}/close".format( + dispute=_util.sanitize_id(dispute), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_encode.py b/stripe/_encode.py index 065d93b21..9552a739e 100644 --- a/stripe/_encode.py +++ b/stripe/_encode.py @@ -5,6 +5,22 @@ from typing import Generator, Tuple, Any +def _encode_datetime(dttime: datetime.datetime): + if dttime.tzinfo and dttime.tzinfo.utcoffset(dttime) is not None: + utc_timestamp = calendar.timegm(dttime.utctimetuple()) + else: + utc_timestamp = time.mktime(dttime.timetuple()) + + return int(utc_timestamp) + + +def _encode_nested_dict(key, data, fmt="%s[%s]"): + d = OrderedDict() + for subkey, subvalue in data.items(): + d[fmt % (key, subkey)] = subvalue + return d + + def _api_encode(data) -> Generator[Tuple[str, Any], None, None]: for key, value in data.items(): if value is None: @@ -27,19 +43,3 @@ def _api_encode(data) -> Generator[Tuple[str, Any], None, None]: yield (key, _encode_datetime(value)) else: yield (key, value) - - -def _encode_datetime(dttime: datetime.datetime): - if dttime.tzinfo and dttime.tzinfo.utcoffset(dttime) is not None: - utc_timestamp = calendar.timegm(dttime.utctimetuple()) - else: - utc_timestamp = time.mktime(dttime.timetuple()) - - return int(utc_timestamp) - - -def _encode_nested_dict(key, data, fmt="%s[%s]"): - d = OrderedDict() - for subkey, subvalue in data.items(): - d[fmt % (key, subkey)] = subvalue - return d diff --git a/stripe/_ephemeral_key.py b/stripe/_ephemeral_key.py index 9064511bc..4580b7e2b 100644 --- a/stripe/_ephemeral_key.py +++ b/stripe/_ephemeral_key.py @@ -1,7 +1,5 @@ # -*- coding: utf-8 -*- # File generated from our OpenAPI spec -from stripe import _util -from stripe._api_requestor import APIRequestor from stripe._deletable_api_resource import DeletableAPIResource from stripe._request_options import RequestOptions from stripe._util import class_method_variant @@ -90,27 +88,18 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] ) @classmethod - def create( - cls, - api_key=None, - idempotency_key=None, - stripe_version=None, - stripe_account=None, - **params - ): - if stripe_version is None: + def create(cls, **params): + if params.get("stripe_version") is None: raise ValueError( "stripe_version must be specified to create an ephemeral " "key" ) - requestor = APIRequestor( - api_key, api_version=stripe_version, account=stripe_account - ) - url = cls.class_url() - headers = _util.populate_headers(idempotency_key) - response, api_key = requestor.request("post", url, params, headers) - return _util.convert_to_stripe_object( - response, api_key, stripe_version, stripe_account + return cls._static_request( + "post", + url, + params=params, + base_address="api", + api_mode="V1", ) diff --git a/stripe/_ephemeral_key_service.py b/stripe/_ephemeral_key_service.py new file mode 100644 index 000000000..3973ca9be --- /dev/null +++ b/stripe/_ephemeral_key_service.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._ephemeral_key import EphemeralKey +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class EphemeralKeyService(StripeService): + class CreateParams(TypedDict): + customer: NotRequired["str"] + """ + The ID of the Customer you'd like to modify using the resulting ephemeral key. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + issuing_card: NotRequired["str"] + """ + The ID of the Issuing Card you'd like to access using the resulting ephemeral key. + """ + nonce: NotRequired["str"] + """ + A single-use token, created by Stripe.js, used for creating ephemeral keys for Issuing Cards without exchanging sensitive information. + """ + verification_session: NotRequired["str"] + """ + The ID of the Identity VerificationSession you'd like to access using the resulting ephemeral key + """ + + class DeleteParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def delete( + self, + key: str, + params: "EphemeralKeyService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> EphemeralKey: + """ + Invalidates a short-lived API key for a given resource. + """ + return cast( + EphemeralKey, + self._requestor.request( + "delete", + "/v1/ephemeral_keys/{key}".format(key=_util.sanitize_id(key)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "EphemeralKeyService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> EphemeralKey: + """ + Creates a short-lived API key for a given resource. + """ + return cast( + EphemeralKey, + self._requestor.request( + "post", + "/v1/ephemeral_keys", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_error.py b/stripe/_error.py index 714431147..aba72701d 100644 --- a/stripe/_error.py +++ b/stripe/_error.py @@ -4,9 +4,6 @@ import stripe # noqa: IMP101 from stripe._error_object import ErrorObject -from stripe import _util -import warnings - class StripeError(Exception): _message: Optional[str] @@ -71,10 +68,7 @@ def __repr__(self): self.request_id, ) - @_util.deprecated( - "For internal stripe-python use only. The public interface will be removed in a future version." - ) - def construct_error_object(self) -> Optional[ErrorObject]: + def _construct_error_object(self) -> Optional[ErrorObject]: if ( self.json_body is None or not isinstance(self.json_body, dict) @@ -83,15 +77,12 @@ def construct_error_object(self) -> Optional[ErrorObject]: ): return None - return ErrorObject.construct_from( - self.json_body["error"], stripe.api_key + return ErrorObject._construct_from( + values=self.json_body["error"], + requestor=stripe._APIRequestor._global_instance(), + api_mode="V1", ) - def _construct_error_object(self): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - return self.construct_error_object() - class APIError(StripeError): pass diff --git a/stripe/_error_object.py b/stripe/_error_object.py index 1f976bada..cd30fc325 100644 --- a/stripe/_error_object.py +++ b/stripe/_error_object.py @@ -2,6 +2,7 @@ from typing_extensions import TYPE_CHECKING from stripe._util import merge_dicts from stripe._stripe_object import StripeObject +from stripe._api_mode import ApiMode if TYPE_CHECKING: from stripe._payment_intent import PaymentIntent @@ -31,7 +32,32 @@ def refresh_from( stripe_version=None, stripe_account=None, last_response=None, + *, + api_mode: ApiMode = "V1", ): + return self._refresh_from( + values=values, + partial=partial, + last_response=last_response, + requestor=self._requestor._replace_options( + { + "api_key": api_key, + "stripe_version": stripe_version, + "stripe_account": stripe_account, + } + ), + api_mode=api_mode, + ) + + def _refresh_from( + self, + *, + values, + partial=False, + last_response=None, + requestor, + api_mode: ApiMode + ) -> None: # Unlike most other API resources, the API will omit attributes in # error objects when they have a null value. We manually set default # values here to facilitate generic error handling. @@ -51,13 +77,12 @@ def refresh_from( }, values, ) - return super(ErrorObject, self).refresh_from( - values, - api_key, - partial, - stripe_version, - stripe_account, - last_response, + return super(ErrorObject, self)._refresh_from( + values=values, + partial=partial, + last_response=last_response, + requestor=requestor, + api_mode=api_mode, ) @@ -70,18 +95,42 @@ def refresh_from( stripe_version=None, stripe_account=None, last_response=None, + *, + api_mode: ApiMode = "V1", ): + return self._refresh_from( + values=values, + partial=partial, + last_response=last_response, + requestor=self._requestor._replace_options( + { + "api_key": api_key, + "stripe_version": stripe_version, + "stripe_account": stripe_account, + } + ), + api_mode=api_mode, + ) + + def _refresh_from( + self, + *, + values, + partial=False, + last_response=None, + requestor, + api_mode: ApiMode, + ) -> None: # Unlike most other API resources, the API will omit attributes in # error objects when they have a null value. We manually set default # values here to facilitate generic error handling. values = merge_dicts( {"error": None, "error_description": None}, values ) - return super(OAuthErrorObject, self).refresh_from( - values, - api_key, - partial, - stripe_version, - stripe_account, - last_response, + return super(OAuthErrorObject, self)._refresh_from( + values=values, + partial=partial, + last_response=last_response, + requestor=requestor, + api_mode=api_mode, ) diff --git a/stripe/_event.py b/stripe/_event.py index 566d258e5..eea7e2ab7 100644 --- a/stripe/_event.py +++ b/stripe/_event.py @@ -392,24 +392,13 @@ class RetrieveParams(RequestOptions): """ @classmethod - def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Event.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> ListObject["Event"]: + def list(cls, **params: Unpack["Event.ListParams"]) -> ListObject["Event"]: """ List events, going back up to 30 days. Each event data is rendered according to Stripe API version at its creation time, specified in [event object](https://stripe.com/docs/api/events/object) api_version attribute (not according to your current Stripe API version or Stripe-Version header). """ result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_event_service.py b/stripe/_event_service.py new file mode 100644 index 000000000..b016d9b20 --- /dev/null +++ b/stripe/_event_service.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._event import Event +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class EventService(StripeService): + class ListParams(TypedDict): + created: NotRequired["EventService.ListParamsCreated|int"] + delivery_success: NotRequired["bool"] + """ + Filter events by whether all webhooks were successfully delivered. If false, events which are still pending or have failed all delivery attempts to a webhook endpoint will be returned. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + type: NotRequired["str"] + """ + A string containing a specific event name, or group of events using * as a wildcard. The list will be filtered to include only events with a matching event property. + """ + types: NotRequired["List[str]"] + """ + An array of up to 20 strings containing specific event names. The list will be filtered to include only events with a matching event property. You may pass either `type` or `types`, but not both. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "EventService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Event]: + """ + List events, going back up to 30 days. Each event data is rendered according to Stripe API version at its creation time, specified in [event object](https://stripe.com/docs/api/events/object) api_version attribute (not according to your current Stripe API version or Stripe-Version header). + """ + return cast( + ListObject[Event], + self._requestor.request( + "get", + "/v1/events", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + id: str, + params: "EventService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Event: + """ + Retrieves the details of an event. Supply the unique identifier of the event, which you might have received in a webhook. + """ + return cast( + Event, + self._requestor.request( + "get", + "/v1/events/{id}".format(id=_util.sanitize_id(id)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_exchange_rate.py b/stripe/_exchange_rate.py index 8a4fe4a79..2d00d42d0 100644 --- a/stripe/_exchange_rate.py +++ b/stripe/_exchange_rate.py @@ -3,7 +3,7 @@ from stripe._list_object import ListObject from stripe._listable_api_resource import ListableAPIResource from stripe._request_options import RequestOptions -from typing import ClassVar, Dict, List, Optional +from typing import ClassVar, Dict, List from typing_extensions import Literal, NotRequired, Unpack @@ -78,13 +78,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ExchangeRate.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ExchangeRate.ListParams"] ) -> ListObject["ExchangeRate"]: """ Returns a list of objects that contain the rates at which foreign currencies are converted to one another. Only shows the currencies for which Stripe supports. @@ -92,9 +86,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_exchange_rate_service.py b/stripe/_exchange_rate_service.py new file mode 100644 index 000000000..cb4120d9b --- /dev/null +++ b/stripe/_exchange_rate_service.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._exchange_rate import ExchangeRate +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class ExchangeRateService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is the currency that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with the exchange rate for currency X your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and total number of supported payout currencies, and the default is the max. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is the currency that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with the exchange rate for currency X, your subsequent call can include `starting_after=X` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "ExchangeRateService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[ExchangeRate]: + """ + Returns a list of objects that contain the rates at which foreign currencies are converted to one another. Only shows the currencies for which Stripe supports. + """ + return cast( + ListObject[ExchangeRate], + self._requestor.request( + "get", + "/v1/exchange_rates", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + rate_id: str, + params: "ExchangeRateService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> ExchangeRate: + """ + Retrieves the exchange rates from the given currency to every supported currency. + """ + return cast( + ExchangeRate, + self._requestor.request( + "get", + "/v1/exchange_rates/{rate_id}".format( + rate_id=_util.sanitize_id(rate_id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_file.py b/stripe/_file.py index 48b42add8..9be5619da 100644 --- a/stripe/_file.py +++ b/stripe/_file.py @@ -1,12 +1,10 @@ # -*- coding: utf-8 -*- # File generated from our OpenAPI spec -import stripe -from stripe import _util -from stripe._api_requestor import APIRequestor +from stripe._createable_api_resource import CreateableAPIResource from stripe._list_object import ListObject from stripe._listable_api_resource import ListableAPIResource from stripe._request_options import RequestOptions -from typing import ClassVar, List, Optional, cast +from typing import Any, ClassVar, Dict, List, Optional, cast from typing_extensions import ( Literal, NotRequired, @@ -19,7 +17,7 @@ from stripe._file_link import FileLink -class File(ListableAPIResource["File"]): +class File(CreateableAPIResource["File"], ListableAPIResource["File"]): """ This object represents files hosted on Stripe's servers. You can upload files with the [create file](https://stripe.com/docs/api#create_file) request @@ -32,6 +30,49 @@ class File(ListableAPIResource["File"]): OBJECT_NAME: ClassVar[Literal["file"]] = "file" + class CreateParams(RequestOptions): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + file: Any + """ + A file to upload. Make sure that the specifications follow RFC 2388, which defines file transfers for the `multipart/form-data` protocol. + """ + file_link_data: NotRequired["File.CreateParamsFileLinkData"] + """ + Optional parameters that automatically create a [file link](https://stripe.com/docs/api#file_links) for the newly created file. + """ + purpose: Literal[ + "account_requirement", + "additional_verification", + "business_icon", + "business_logo", + "customer_signature", + "dispute_evidence", + "identity_document", + "pci_document", + "tax_document_user_upload", + "terminal_reader_splashscreen", + ] + """ + The [purpose](https://stripe.com/docs/file-upload#uploading-a-file) of the uploaded file. + """ + + class CreateParamsFileLinkData(TypedDict): + create: bool + """ + Set this to `true` to create a file link for the newly created file. Creating a link is only possible when the file's `purpose` is one of the following: `business_icon`, `business_logo`, `customer_signature`, `dispute_evidence`, `pci_document`, `tax_document_user_upload`, or `terminal_reader_splashscreen`. + """ + expires_at: NotRequired["int"] + """ + The link isn't available after this future timestamp. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + class ListParams(RequestOptions): created: NotRequired["File.ListParamsCreated|int"] ending_before: NotRequired["str"] @@ -143,24 +184,31 @@ class RetrieveParams(RequestOptions): """ @classmethod - def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "File.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> ListObject["File"]: + def create(cls, **params: Unpack["File.CreateParams"]) -> "File": + """ + To upload a file to Stripe, you need to send a request of type multipart/form-data. Include the file you want to upload in the request, and the parameters for creating a file. + + All of Stripe's officially supported Client libraries support sending multipart/form-data. + """ + return cast( + "File", + cls._static_request( + "post", + cls.class_url(), + params, + base_address="files", + api_mode="V1FILES", + ), + ) + + @classmethod + def list(cls, **params: Unpack["File.ListParams"]) -> ListObject["File"]: """ Returns a list of the files that your account has access to. Stripe sorts and returns the files by their creation dates, placing the most recently created files at the top. """ result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -183,35 +231,6 @@ def retrieve( instance.refresh() return instance - @classmethod - def create( - # 'api_version' is deprecated, please use 'stripe_version' - cls, - api_key=None, - api_version=None, - stripe_version=None, - stripe_account=None, - **params - ) -> "File": - version = api_version or stripe_version - requestor = APIRequestor( - api_key, - api_base=stripe.upload_api_base, - api_version=version, - account=stripe_account, - ) - url = cls.class_url() - supplied_headers = {"Content-Type": "multipart/form-data"} - response, api_key = requestor.request( - "post", url, params=params, headers=supplied_headers - ) - return cast( - "File", - _util.convert_to_stripe_object( - response, api_key, version, stripe_account - ), - ) - # This resource can have two different object names. In latter API # versions, only `file` is used, but since stripe-python may be used with # any API version, we need to support deserializing the older diff --git a/stripe/_file_link.py b/stripe/_file_link.py index e71f1b620..ef83b0f87 100644 --- a/stripe/_file_link.py +++ b/stripe/_file_link.py @@ -154,16 +154,7 @@ class RetrieveParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "FileLink.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "FileLink": + def create(cls, **params: Unpack["FileLink.CreateParams"]) -> "FileLink": """ Creates a new file link object. """ @@ -172,23 +163,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "FileLink.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["FileLink.ListParams"] ) -> ListObject["FileLink"]: """ Returns a list of file links. @@ -196,9 +177,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_file_link_service.py b/stripe/_file_link_service.py new file mode 100644 index 000000000..442c6c7ab --- /dev/null +++ b/stripe/_file_link_service.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._file_link import FileLink +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class FileLinkService(StripeService): + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + expires_at: NotRequired["int"] + """ + The link isn't usable after this future timestamp. + """ + file: str + """ + The ID of the file. The file's `purpose` must be one of the following: `business_icon`, `business_logo`, `customer_signature`, `dispute_evidence`, `finance_report_run`, `identity_document_downloadable`, `pci_document`, `selfie`, `sigma_scheduled_query`, `tax_document_user_upload`, or `terminal_reader_splashscreen`. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class ListParams(TypedDict): + created: NotRequired["FileLinkService.ListParamsCreated|int"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + expired: NotRequired["bool"] + """ + Filter links by their expiration status. By default, Stripe returns all links. + """ + file: NotRequired["str"] + """ + Only return links for the given file. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + expires_at: NotRequired["Literal['']|Literal['now']|int"] + """ + A future timestamp after which the link will no longer be usable, or `now` to expire the link immediately. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + def list( + self, + params: "FileLinkService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[FileLink]: + """ + Returns a list of file links. + """ + return cast( + ListObject[FileLink], + self._requestor.request( + "get", + "/v1/file_links", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "FileLinkService.CreateParams", + options: RequestOptions = {}, + ) -> FileLink: + """ + Creates a new file link object. + """ + return cast( + FileLink, + self._requestor.request( + "post", + "/v1/file_links", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + link: str, + params: "FileLinkService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> FileLink: + """ + Retrieves the file link with the given ID. + """ + return cast( + FileLink, + self._requestor.request( + "get", + "/v1/file_links/{link}".format(link=_util.sanitize_id(link)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + link: str, + params: "FileLinkService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> FileLink: + """ + Updates an existing file link object. Expired links can no longer be updated. + """ + return cast( + FileLink, + self._requestor.request( + "post", + "/v1/file_links/{link}".format(link=_util.sanitize_id(link)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_file_service.py b/stripe/_file_service.py new file mode 100644 index 000000000..fa1a3ad6b --- /dev/null +++ b/stripe/_file_service.py @@ -0,0 +1,164 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._file import File +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Any, Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class FileService(StripeService): + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + file: Any + """ + A file to upload. Make sure that the specifications follow RFC 2388, which defines file transfers for the `multipart/form-data` protocol. + """ + file_link_data: NotRequired["FileService.CreateParamsFileLinkData"] + """ + Optional parameters that automatically create a [file link](https://stripe.com/docs/api#file_links) for the newly created file. + """ + purpose: Literal[ + "account_requirement", + "additional_verification", + "business_icon", + "business_logo", + "customer_signature", + "dispute_evidence", + "identity_document", + "pci_document", + "tax_document_user_upload", + "terminal_reader_splashscreen", + ] + """ + The [purpose](https://stripe.com/docs/file-upload#uploading-a-file) of the uploaded file. + """ + + class CreateParamsFileLinkData(TypedDict): + create: bool + """ + Set this to `true` to create a file link for the newly created file. Creating a link is only possible when the file's `purpose` is one of the following: `business_icon`, `business_logo`, `customer_signature`, `dispute_evidence`, `pci_document`, `tax_document_user_upload`, or `terminal_reader_splashscreen`. + """ + expires_at: NotRequired["int"] + """ + The link isn't available after this future timestamp. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class ListParams(TypedDict): + created: NotRequired["FileService.ListParamsCreated|int"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + purpose: NotRequired[ + "Literal['account_requirement', 'additional_verification', 'business_icon', 'business_logo', 'customer_signature', 'dispute_evidence', 'document_provider_identity_document', 'finance_report_run', 'identity_document', 'identity_document_downloadable', 'pci_document', 'selfie', 'sigma_scheduled_query', 'tax_document_user_upload', 'terminal_reader_splashscreen']" + ] + """ + Filter queries by the file purpose. If you don't provide a purpose, the queries return unfiltered files. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "FileService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[File]: + """ + Returns a list of the files that your account has access to. Stripe sorts and returns the files by their creation dates, placing the most recently created files at the top. + """ + return cast( + ListObject[File], + self._requestor.request( + "get", + "/v1/files", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, params: "FileService.CreateParams", options: RequestOptions = {} + ) -> File: + """ + To upload a file to Stripe, you need to send a request of type multipart/form-data. Include the file you want to upload in the request, and the parameters for creating a file. + + All of Stripe's officially supported Client libraries support sending multipart/form-data. + """ + return cast( + File, + self._requestor.request( + "post", + "/v1/files", + api_mode="V1FILES", + base_address="files", + params=params, + options=options, + ), + ) + + def retrieve( + self, + file: str, + params: "FileService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> File: + """ + Retrieves the details of an existing file object. After you supply a unique file ID, Stripe returns the corresponding file object. Learn how to [access file contents](https://stripe.com/docs/file-upload#download-file-contents). + """ + return cast( + File, + self._requestor.request( + "get", + "/v1/files/{file}".format(file=_util.sanitize_id(file)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_financial_connections_service.py b/stripe/_financial_connections_service.py new file mode 100644 index 000000000..8a9905393 --- /dev/null +++ b/stripe/_financial_connections_service.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.financial_connections._account_service import AccountService +from stripe.financial_connections._session_service import SessionService +from stripe.financial_connections._transaction_service import ( + TransactionService, +) + + +class FinancialConnectionsService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.accounts = AccountService(self._requestor) + self.sessions = SessionService(self._requestor) + self.transactions = TransactionService(self._requestor) diff --git a/stripe/_http_client.py b/stripe/_http_client.py index b9d49d77f..0929bfd7c 100644 --- a/stripe/_http_client.py +++ b/stripe/_http_client.py @@ -139,8 +139,17 @@ def __init__( self._thread_local = threading.local() - def _should_retry(self, response, api_connection_error, num_retries): - if num_retries >= self._max_network_retries(): + def _should_retry( + self, + response, + api_connection_error, + num_retries, + max_network_retries, + ): + max_network_retries = ( + max_network_retries if max_network_retries is not None else 0 + ) + if num_retries >= max_network_retries: return False if response is None: @@ -176,12 +185,6 @@ def _should_retry(self, response, api_connection_error, num_retries): return False - def _max_network_retries(self): - from stripe import max_network_retries - - # Configured retries, isolated here for tests - return max_network_retries - def _retry_after_header(self, response=None): if response is None: return None @@ -247,11 +250,18 @@ def request_with_retries( url, headers, post_data=None, + max_network_retries=None, *, - _usage: Optional[List[str]] = None + _usage: Optional[List[str]] = None, ) -> Tuple[Any, int, Any]: return self._request_with_retries_internal( - method, url, headers, post_data, is_streaming=False, _usage=_usage + method, + url, + headers, + post_data, + is_streaming=False, + max_network_retries=max_network_retries, + _usage=_usage, ) def request_stream_with_retries( @@ -260,15 +270,30 @@ def request_stream_with_retries( url, headers, post_data=None, + max_network_retries=None, *, - _usage: Optional[List[str]] = None + _usage: Optional[List[str]] = None, ) -> Tuple[Any, int, Any]: return self._request_with_retries_internal( - method, url, headers, post_data, is_streaming=True, _usage=_usage + method, + url, + headers, + post_data, + is_streaming=True, + max_network_retries=max_network_retries, + _usage=_usage, ) def _request_with_retries_internal( - self, method, url, headers, post_data, is_streaming, *, _usage=None + self, + method, + url, + headers, + post_data, + is_streaming, + max_network_retries, + *, + _usage=None, ): self._add_telemetry_header(headers) @@ -289,7 +314,9 @@ def _request_with_retries_internal( connection_error = e response = None - if self._should_retry(response, connection_error, num_retries): + if self._should_retry( + response, connection_error, num_retries, max_network_retries + ): if connection_error: _util.log_info( "Encountered a retryable error %s" diff --git a/stripe/_identity_service.py b/stripe/_identity_service.py new file mode 100644 index 000000000..a3ad4ec05 --- /dev/null +++ b/stripe/_identity_service.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.identity._verification_report_service import ( + VerificationReportService, +) +from stripe.identity._verification_session_service import ( + VerificationSessionService, +) + + +class IdentityService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.verification_reports = VerificationReportService(self._requestor) + self.verification_sessions = VerificationSessionService( + self._requestor + ) diff --git a/stripe/_invoice.py b/stripe/_invoice.py index e7eb04e4f..7f0980a9d 100644 --- a/stripe/_invoice.py +++ b/stripe/_invoice.py @@ -3729,16 +3729,7 @@ class VoidInvoiceParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Invoice": + def create(cls, **params: Unpack["Invoice.CreateParams"]) -> "Invoice": """ This endpoint creates a draft invoice for a given customer. The invoice remains a draft until you [finalize the invoice, which allows you to [pay](#pay_invoice) or send](https://stripe.com/docs/api#finalize_invoice) the invoice to your customers. """ @@ -3747,10 +3738,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -3800,14 +3787,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def _cls_finalize_invoice( - cls, - invoice: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.FinalizeInvoiceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, invoice: str, **params: Unpack["Invoice.FinalizeInvoiceParams"] ) -> "Invoice": """ Stripe automatically finalizes drafts before sending and attempting payment on invoices. However, if you'd like to finalize a draft invoice manually, you can do so using this method. @@ -3819,9 +3799,6 @@ def _cls_finalize_invoice( "/v1/invoices/{invoice}/finalize".format( invoice=_util.sanitize_id(invoice) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -3829,13 +3806,7 @@ def _cls_finalize_invoice( @overload @staticmethod def finalize_invoice( - invoice: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.FinalizeInvoiceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + invoice: str, **params: Unpack["Invoice.FinalizeInvoiceParams"] ) -> "Invoice": """ Stripe automatically finalizes drafts before sending and attempting payment on invoices. However, if you'd like to finalize a draft invoice manually, you can do so using this method. @@ -3844,11 +3815,7 @@ def finalize_invoice( @overload def finalize_invoice( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Invoice.FinalizeInvoiceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Invoice.FinalizeInvoiceParams"] ) -> "Invoice": """ Stripe automatically finalizes drafts before sending and attempting payment on invoices. However, if you'd like to finalize a draft invoice manually, you can do so using this method. @@ -3857,11 +3824,7 @@ def finalize_invoice( @class_method_variant("_cls_finalize_invoice") def finalize_invoice( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Invoice.FinalizeInvoiceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Invoice.FinalizeInvoiceParams"] ) -> "Invoice": """ Stripe automatically finalizes drafts before sending and attempting payment on invoices. However, if you'd like to finalize a draft invoice manually, you can do so using this method. @@ -3873,20 +3836,13 @@ def finalize_invoice( # pyright: ignore[reportGeneralTypeIssues] "/v1/invoices/{invoice}/finalize".format( invoice=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Invoice.ListParams"] ) -> ListObject["Invoice"]: """ You can list all invoices, or list the invoices for a specific customer. The invoices are returned sorted by creation date, with the most recently created invoices appearing first. @@ -3894,9 +3850,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -3910,14 +3863,7 @@ def list( @classmethod def _cls_mark_uncollectible( - cls, - invoice: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.MarkUncollectibleParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, invoice: str, **params: Unpack["Invoice.MarkUncollectibleParams"] ) -> "Invoice": """ Marking an invoice as uncollectible is useful for keeping track of bad debts that can be written off for accounting purposes. @@ -3929,9 +3875,6 @@ def _cls_mark_uncollectible( "/v1/invoices/{invoice}/mark_uncollectible".format( invoice=_util.sanitize_id(invoice) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -3939,13 +3882,7 @@ def _cls_mark_uncollectible( @overload @staticmethod def mark_uncollectible( - invoice: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.MarkUncollectibleParams" - ] # pyright: ignore[reportGeneralTypeIssues] + invoice: str, **params: Unpack["Invoice.MarkUncollectibleParams"] ) -> "Invoice": """ Marking an invoice as uncollectible is useful for keeping track of bad debts that can be written off for accounting purposes. @@ -3954,11 +3891,7 @@ def mark_uncollectible( @overload def mark_uncollectible( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Invoice.MarkUncollectibleParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Invoice.MarkUncollectibleParams"] ) -> "Invoice": """ Marking an invoice as uncollectible is useful for keeping track of bad debts that can be written off for accounting purposes. @@ -3967,11 +3900,7 @@ def mark_uncollectible( @class_method_variant("_cls_mark_uncollectible") def mark_uncollectible( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Invoice.MarkUncollectibleParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Invoice.MarkUncollectibleParams"] ) -> "Invoice": """ Marking an invoice as uncollectible is useful for keeping track of bad debts that can be written off for accounting purposes. @@ -3983,7 +3912,6 @@ def mark_uncollectible( # pyright: ignore[reportGeneralTypeIssues] "/v1/invoices/{invoice}/mark_uncollectible".format( invoice=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -4008,14 +3936,7 @@ def modify( @classmethod def _cls_pay( - cls, - invoice: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.PayParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, invoice: str, **params: Unpack["Invoice.PayParams"] ) -> "Invoice": """ Stripe automatically creates and then attempts to collect payment on invoices for customers on subscriptions according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to attempt payment on an invoice out of the normal collection schedule or for some other reason, you can do so. @@ -4027,37 +3948,20 @@ def _cls_pay( "/v1/invoices/{invoice}/pay".format( invoice=_util.sanitize_id(invoice) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @overload @staticmethod - def pay( - invoice: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.PayParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Invoice": + def pay(invoice: str, **params: Unpack["Invoice.PayParams"]) -> "Invoice": """ Stripe automatically creates and then attempts to collect payment on invoices for customers on subscriptions according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to attempt payment on an invoice out of the normal collection schedule or for some other reason, you can do so. """ ... @overload - def pay( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Invoice.PayParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Invoice": + def pay(self, **params: Unpack["Invoice.PayParams"]) -> "Invoice": """ Stripe automatically creates and then attempts to collect payment on invoices for customers on subscriptions according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to attempt payment on an invoice out of the normal collection schedule or for some other reason, you can do so. """ @@ -4065,11 +3969,7 @@ def pay( @class_method_variant("_cls_pay") def pay( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Invoice.PayParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Invoice.PayParams"] ) -> "Invoice": """ Stripe automatically creates and then attempts to collect payment on invoices for customers on subscriptions according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to attempt payment on an invoice out of the normal collection schedule or for some other reason, you can do so. @@ -4081,7 +3981,6 @@ def pay( # pyright: ignore[reportGeneralTypeIssues] "/v1/invoices/{invoice}/pay".format( invoice=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -4099,14 +3998,7 @@ def retrieve( @classmethod def _cls_send_invoice( - cls, - invoice: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.SendInvoiceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, invoice: str, **params: Unpack["Invoice.SendInvoiceParams"] ) -> "Invoice": """ Stripe will automatically send invoices to customers according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to manually send an invoice to your customer out of the normal schedule, you can do so. When sending invoices that have already been paid, there will be no reference to the payment in the email. @@ -4120,9 +4012,6 @@ def _cls_send_invoice( "/v1/invoices/{invoice}/send".format( invoice=_util.sanitize_id(invoice) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -4130,13 +4019,7 @@ def _cls_send_invoice( @overload @staticmethod def send_invoice( - invoice: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.SendInvoiceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + invoice: str, **params: Unpack["Invoice.SendInvoiceParams"] ) -> "Invoice": """ Stripe will automatically send invoices to customers according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to manually send an invoice to your customer out of the normal schedule, you can do so. When sending invoices that have already been paid, there will be no reference to the payment in the email. @@ -4147,11 +4030,7 @@ def send_invoice( @overload def send_invoice( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Invoice.SendInvoiceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Invoice.SendInvoiceParams"] ) -> "Invoice": """ Stripe will automatically send invoices to customers according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to manually send an invoice to your customer out of the normal schedule, you can do so. When sending invoices that have already been paid, there will be no reference to the payment in the email. @@ -4162,11 +4041,7 @@ def send_invoice( @class_method_variant("_cls_send_invoice") def send_invoice( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Invoice.SendInvoiceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Invoice.SendInvoiceParams"] ) -> "Invoice": """ Stripe will automatically send invoices to customers according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to manually send an invoice to your customer out of the normal schedule, you can do so. When sending invoices that have already been paid, there will be no reference to the payment in the email. @@ -4180,21 +4055,12 @@ def send_invoice( # pyright: ignore[reportGeneralTypeIssues] "/v1/invoices/{invoice}/send".format( invoice=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod - def upcoming( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.UpcomingParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Invoice": + def upcoming(cls, **params: Unpack["Invoice.UpcomingParams"]) -> "Invoice": """ At any time, you can preview the upcoming invoice for a customer. This will show you all the charges that are pending, including subscription renewal charges, invoice item charges, etc. It will also show you any discounts that are applicable to the invoice. @@ -4207,22 +4073,13 @@ def upcoming( cls._static_request( "get", "/v1/invoices/upcoming", - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def upcoming_lines( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.UpcomingLinesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Invoice.UpcomingLinesParams"] ) -> ListObject["InvoiceLineItem"]: """ When retrieving an upcoming invoice, you'll get a lines property containing the total count of line items and the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -4232,23 +4089,13 @@ def upcoming_lines( cls._static_request( "get", "/v1/invoices/upcoming/lines", - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def _cls_void_invoice( - cls, - invoice: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.VoidInvoiceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, invoice: str, **params: Unpack["Invoice.VoidInvoiceParams"] ) -> "Invoice": """ Mark a finalized invoice as void. This cannot be undone. Voiding an invoice is similar to [deletion](https://stripe.com/docs/api#delete_invoice), however it only applies to finalized invoices and maintains a papertrail where the invoice can still be found. @@ -4260,9 +4107,6 @@ def _cls_void_invoice( "/v1/invoices/{invoice}/void".format( invoice=_util.sanitize_id(invoice) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -4270,13 +4114,7 @@ def _cls_void_invoice( @overload @staticmethod def void_invoice( - invoice: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Invoice.VoidInvoiceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + invoice: str, **params: Unpack["Invoice.VoidInvoiceParams"] ) -> "Invoice": """ Mark a finalized invoice as void. This cannot be undone. Voiding an invoice is similar to [deletion](https://stripe.com/docs/api#delete_invoice), however it only applies to finalized invoices and maintains a papertrail where the invoice can still be found. @@ -4285,11 +4123,7 @@ def void_invoice( @overload def void_invoice( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Invoice.VoidInvoiceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Invoice.VoidInvoiceParams"] ) -> "Invoice": """ Mark a finalized invoice as void. This cannot be undone. Voiding an invoice is similar to [deletion](https://stripe.com/docs/api#delete_invoice), however it only applies to finalized invoices and maintains a papertrail where the invoice can still be found. @@ -4298,11 +4132,7 @@ def void_invoice( @class_method_variant("_cls_void_invoice") def void_invoice( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Invoice.VoidInvoiceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Invoice.VoidInvoiceParams"] ) -> "Invoice": """ Mark a finalized invoice as void. This cannot be undone. Voiding an invoice is similar to [deletion](https://stripe.com/docs/api#delete_invoice), however it only applies to finalized invoices and maintains a papertrail where the invoice can still be found. @@ -4314,7 +4144,6 @@ def void_invoice( # pyright: ignore[reportGeneralTypeIssues] "/v1/invoices/{invoice}/void".format( invoice=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/_invoice_item.py b/stripe/_invoice_item.py index 040314c80..d1a2a0756 100644 --- a/stripe/_invoice_item.py +++ b/stripe/_invoice_item.py @@ -452,14 +452,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "InvoiceItem.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["InvoiceItem.CreateParams"] ) -> "InvoiceItem": """ Creates an item to be added to a draft invoice (up to 250 items per invoice). If no invoice is specified, the item will be on the next invoice created for the customer specified. @@ -469,10 +462,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -524,13 +513,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "InvoiceItem.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["InvoiceItem.ListParams"] ) -> ListObject["InvoiceItem"]: """ Returns a list of your invoice items. Invoice items are returned sorted by creation date, with the most recently created invoice items appearing first. @@ -538,9 +521,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_invoice_item_service.py b/stripe/_invoice_item_service.py new file mode 100644 index 000000000..7448e37fa --- /dev/null +++ b/stripe/_invoice_item_service.py @@ -0,0 +1,414 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._invoice_item import InvoiceItem +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class InvoiceItemService(StripeService): + class CreateParams(TypedDict): + amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. Passing in a negative `amount` will reduce the `amount_due` on the invoice. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + customer: str + """ + The ID of the customer who will be billed when this invoice item is billed. + """ + description: NotRequired["str"] + """ + An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. + """ + discountable: NotRequired["bool"] + """ + Controls whether discounts apply to this invoice item. Defaults to false for prorations or negative invoice items, and true for all other invoice items. + """ + discounts: NotRequired[ + "Literal['']|List[InvoiceItemService.CreateParamsDiscount]" + ] + """ + The coupons to redeem into discounts for the invoice item or invoice line item. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice: NotRequired["str"] + """ + The ID of an existing invoice to add this invoice item to. When left blank, the invoice item will be added to the next upcoming scheduled invoice. This is useful when adding invoice items in response to an invoice.created webhook. You can only add invoice items to draft invoices and there is a maximum of 250 items per invoice. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + period: NotRequired["InvoiceItemService.CreateParamsPeriod"] + """ + The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. + """ + price: NotRequired["str"] + """ + The ID of the price object. + """ + price_data: NotRequired["InvoiceItemService.CreateParamsPriceData"] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Non-negative integer. The quantity of units for the invoice item. + """ + subscription: NotRequired["str"] + """ + The ID of a subscription to add this invoice item to. When left blank, the invoice item will be be added to the next upcoming scheduled invoice. When set, scheduled invoices for subscriptions other than the specified subscription will ignore the invoice item. Use this when you want to express that an invoice item has been accrued within the context of a particular subscription. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + tax_code: NotRequired["Literal['']|str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + """ + tax_rates: NotRequired["List[str]"] + """ + The tax rates which apply to the invoice item. When set, the `default_tax_rates` on the invoice do not apply to this invoice item. + """ + unit_amount: NotRequired["int"] + """ + The integer unit amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. This `unit_amount` will be multiplied by the quantity to get the full amount. Passing in a negative `unit_amount` will reduce the `amount_due` on the invoice. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class CreateParamsDiscount(TypedDict): + coupon: NotRequired["str"] + """ + ID of the coupon to create a new discount for. + """ + discount: NotRequired["str"] + """ + ID of an existing discount on the object (or one of its ancestors) to reuse. + """ + + class CreateParamsPeriod(TypedDict): + end: int + """ + The end of the period, which must be greater than or equal to the start. This value is inclusive. + """ + start: int + """ + The start of the period. This value is inclusive. + """ + + class CreateParamsPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + created: NotRequired["InvoiceItemService.ListParamsCreated|int"] + customer: NotRequired["str"] + """ + The identifier of the customer whose invoice items to return. If none is provided, all invoice items will be returned. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice: NotRequired["str"] + """ + Only return invoice items belonging to this invoice. If none is provided, all invoice items will be returned. If specifying an invoice, no customer identifier is needed. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + pending: NotRequired["bool"] + """ + Set to `true` to only show pending invoice items, which are not yet attached to any invoices. Set to `false` to only show invoice items already attached to invoices. If unspecified, no filter is applied. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. If you want to apply a credit to the customer's account, pass a negative amount. + """ + description: NotRequired["str"] + """ + An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. + """ + discountable: NotRequired["bool"] + """ + Controls whether discounts apply to this invoice item. Defaults to false for prorations or negative invoice items, and true for all other invoice items. Cannot be set to true for prorations. + """ + discounts: NotRequired[ + "Literal['']|List[InvoiceItemService.UpdateParamsDiscount]" + ] + """ + The coupons & existing discounts which apply to the invoice item or invoice line item. Item discounts are applied before invoice discounts. Pass an empty string to remove previously-defined discounts. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + period: NotRequired["InvoiceItemService.UpdateParamsPeriod"] + """ + The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. + """ + price: NotRequired["str"] + """ + The ID of the price object. + """ + price_data: NotRequired["InvoiceItemService.UpdateParamsPriceData"] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Non-negative integer. The quantity of units for the invoice item. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + tax_code: NotRequired["Literal['']|str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates which apply to the invoice item. When set, the `default_tax_rates` on the invoice do not apply to this invoice item. Pass an empty string to remove previously-defined tax rates. + """ + unit_amount: NotRequired["int"] + """ + The integer unit amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. This unit_amount will be multiplied by the quantity to get the full amount. If you want to apply a credit to the customer's account, pass a negative unit_amount. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class UpdateParamsDiscount(TypedDict): + coupon: NotRequired["str"] + """ + ID of the coupon to create a new discount for. + """ + discount: NotRequired["str"] + """ + ID of an existing discount on the object (or one of its ancestors) to reuse. + """ + + class UpdateParamsPeriod(TypedDict): + end: int + """ + The end of the period, which must be greater than or equal to the start. This value is inclusive. + """ + start: int + """ + The start of the period. This value is inclusive. + """ + + class UpdateParamsPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + def delete( + self, + invoiceitem: str, + params: "InvoiceItemService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> InvoiceItem: + """ + Deletes an invoice item, removing it from an invoice. Deleting invoice items is only possible when they're not attached to invoices, or if it's attached to a draft invoice. + """ + return cast( + InvoiceItem, + self._requestor.request( + "delete", + "/v1/invoiceitems/{invoiceitem}".format( + invoiceitem=_util.sanitize_id(invoiceitem), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + invoiceitem: str, + params: "InvoiceItemService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> InvoiceItem: + """ + Retrieves the invoice item with the given ID. + """ + return cast( + InvoiceItem, + self._requestor.request( + "get", + "/v1/invoiceitems/{invoiceitem}".format( + invoiceitem=_util.sanitize_id(invoiceitem), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + invoiceitem: str, + params: "InvoiceItemService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> InvoiceItem: + """ + Updates the amount or description of an invoice item on an upcoming invoice. Updating an invoice item is only possible before the invoice it's attached to is closed. + """ + return cast( + InvoiceItem, + self._requestor.request( + "post", + "/v1/invoiceitems/{invoiceitem}".format( + invoiceitem=_util.sanitize_id(invoiceitem), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "InvoiceItemService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[InvoiceItem]: + """ + Returns a list of your invoice items. Invoice items are returned sorted by creation date, with the most recently created invoice items appearing first. + """ + return cast( + ListObject[InvoiceItem], + self._requestor.request( + "get", + "/v1/invoiceitems", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "InvoiceItemService.CreateParams", + options: RequestOptions = {}, + ) -> InvoiceItem: + """ + Creates an item to be added to a draft invoice (up to 250 items per invoice). If no invoice is specified, the item will be on the next invoice created for the customer specified. + """ + return cast( + InvoiceItem, + self._requestor.request( + "post", + "/v1/invoiceitems", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_invoice_line_item_service.py b/stripe/_invoice_line_item_service.py new file mode 100644 index 000000000..6a58e23e7 --- /dev/null +++ b/stripe/_invoice_line_item_service.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._invoice_line_item import InvoiceLineItem +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class InvoiceLineItemService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + def list( + self, + invoice: str, + params: "InvoiceLineItemService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[InvoiceLineItem]: + """ + When retrieving an invoice, you'll get a lines property containing the total count of line items and the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. + """ + return cast( + ListObject[InvoiceLineItem], + self._requestor.request( + "get", + "/v1/invoices/{invoice}/lines".format( + invoice=_util.sanitize_id(invoice), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_invoice_service.py b/stripe/_invoice_service.py new file mode 100644 index 000000000..21aa70ddf --- /dev/null +++ b/stripe/_invoice_service.py @@ -0,0 +1,2171 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._invoice import Invoice +from stripe._invoice_line_item_service import InvoiceLineItemService +from stripe._invoice_upcoming_lines_service import InvoiceUpcomingLinesService +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._search_result_object import SearchResultObject +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class InvoiceService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.line_items = InvoiceLineItemService(self._requestor) + self.upcoming_lines = InvoiceUpcomingLinesService(self._requestor) + + class CreateParams(TypedDict): + account_tax_ids: NotRequired["Literal['']|List[str]"] + """ + The account tax IDs associated with the invoice. Only editable when the invoice is a draft. + """ + application_fee_amount: NotRequired["int"] + """ + A fee in cents (or local equivalent) that will be applied to the invoice and transferred to the application owner's Stripe account. The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. For more information, see the application fees [documentation](https://stripe.com/docs/billing/invoices/connect#collecting-fees). + """ + auto_advance: NotRequired["bool"] + """ + Controls whether Stripe performs [automatic collection](https://stripe.com/docs/invoicing/integration/automatic-advancement-collection) of the invoice. If `false`, the invoice's state doesn't automatically advance without an explicit action. + """ + automatic_tax: NotRequired["InvoiceService.CreateParamsAutomaticTax"] + """ + Settings for automatic tax lookup for this invoice. + """ + collection_method: NotRequired[ + "Literal['charge_automatically', 'send_invoice']" + ] + """ + Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. When sending an invoice, Stripe will email this invoice to the customer with payment instructions. Defaults to `charge_automatically`. + """ + currency: NotRequired["str"] + """ + The currency to create this invoice in. Defaults to that of `customer` if not specified. + """ + custom_fields: NotRequired[ + "Literal['']|List[InvoiceService.CreateParamsCustomField]" + ] + """ + A list of up to 4 custom fields to be displayed on the invoice. + """ + customer: NotRequired["str"] + """ + The ID of the customer who will be billed. + """ + days_until_due: NotRequired["int"] + """ + The number of days from when the invoice is created until it is due. Valid only for invoices where `collection_method=send_invoice`. + """ + default_payment_method: NotRequired["str"] + """ + ID of the default payment method for the invoice. It must belong to the customer associated with the invoice. If not set, defaults to the subscription's default payment method, if any, or to the default payment method in the customer's invoice settings. + """ + default_source: NotRequired["str"] + """ + ID of the default payment source for the invoice. It must belong to the customer associated with the invoice and be in a chargeable state. If not set, defaults to the subscription's default source, if any, or to the customer's default source. + """ + default_tax_rates: NotRequired["List[str]"] + """ + The tax rates that will apply to any line item that does not have `tax_rates` set. + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. Referenced as 'memo' in the Dashboard. + """ + discounts: NotRequired[ + "Literal['']|List[InvoiceService.CreateParamsDiscount]" + ] + """ + The coupons to redeem into discounts for the invoice. If not specified, inherits the discount from the invoice's customer. Pass an empty string to avoid inheriting any discounts. + """ + due_date: NotRequired["int"] + """ + The date on which payment for this invoice is due. Valid only for invoices where `collection_method=send_invoice`. + """ + effective_at: NotRequired["int"] + """ + The date when this invoice is in effect. Same as `finalized_at` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the invoice PDF and receipt. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + footer: NotRequired["str"] + """ + Footer to be displayed on the invoice. + """ + from_invoice: NotRequired["InvoiceService.CreateParamsFromInvoice"] + """ + Revise an existing invoice. The new invoice will be created in `status=draft`. See the [revision documentation](https://stripe.com/docs/invoicing/invoice-revisions) for more details. + """ + issuer: NotRequired["InvoiceService.CreateParamsIssuer"] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + on_behalf_of: NotRequired["str"] + """ + The account (if any) for which the funds of the invoice payment are intended. If set, the invoice will be presented with the branding and support information of the specified account. See the [Invoices with Connect](https://stripe.com/docs/billing/invoices/connect) documentation for details. + """ + payment_settings: NotRequired[ + "InvoiceService.CreateParamsPaymentSettings" + ] + """ + Configuration settings for the PaymentIntent that is generated when the invoice is finalized. + """ + pending_invoice_items_behavior: NotRequired[ + "Literal['exclude', 'include', 'include_and_require']" + ] + """ + How to handle pending invoice items on invoice creation. One of `include` or `exclude`. `include` will include any pending invoice items, and will create an empty draft invoice if no pending invoice items exist. `exclude` will always create an empty invoice draft regardless if there are pending invoice items or not. Defaults to `exclude` if the parameter is omitted. + """ + rendering: NotRequired["InvoiceService.CreateParamsRendering"] + """ + The rendering-related settings that control how the invoice is displayed on customer-facing surfaces such as PDF and Hosted Invoice Page. + """ + rendering_options: NotRequired[ + "Literal['']|InvoiceService.CreateParamsRenderingOptions" + ] + """ + This is a legacy field that will be removed soon. For details about `rendering_options`, refer to `rendering` instead. Options for invoice PDF rendering. + """ + shipping_cost: NotRequired["InvoiceService.CreateParamsShippingCost"] + """ + Settings for the cost of shipping for this invoice. + """ + shipping_details: NotRequired[ + "InvoiceService.CreateParamsShippingDetails" + ] + """ + Shipping details for the invoice. The Invoice PDF will use the `shipping_details` value if it is set, otherwise the PDF will render the shipping address from the customer. + """ + statement_descriptor: NotRequired["str"] + """ + Extra information about a charge for the customer's credit card statement. It must contain at least one letter. If not specified and this invoice is part of a subscription, the default `statement_descriptor` will be set to the first subscription item's product's `statement_descriptor`. + """ + subscription: NotRequired["str"] + """ + The ID of the subscription to invoice, if any. If set, the created invoice will only include pending invoice items for that subscription. The subscription's billing cycle and regular subscription events won't be affected. + """ + transfer_data: NotRequired["InvoiceService.CreateParamsTransferData"] + """ + If specified, the funds from the invoice will be transferred to the destination and the ID of the resulting transfer will be found on the invoice's charge. + """ + + class CreateParamsAutomaticTax(TypedDict): + enabled: bool + """ + Whether Stripe automatically computes tax on this invoice. Note that incompatible invoice items (invoice items with manually specified [tax rates](https://stripe.com/docs/api/tax_rates), negative amounts, or `tax_behavior=unspecified`) cannot be added to automatic tax invoices. + """ + liability: NotRequired[ + "InvoiceService.CreateParamsAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class CreateParamsAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsCustomField(TypedDict): + name: str + """ + The name of the custom field. This may be up to 30 characters. + """ + value: str + """ + The value of the custom field. This may be up to 30 characters. + """ + + class CreateParamsDiscount(TypedDict): + coupon: NotRequired["str"] + """ + ID of the coupon to create a new discount for. + """ + discount: NotRequired["str"] + """ + ID of an existing discount on the object (or one of its ancestors) to reuse. + """ + + class CreateParamsFromInvoice(TypedDict): + action: Literal["revision"] + """ + The relation between the new invoice and the original invoice. Currently, only 'revision' is permitted + """ + invoice: str + """ + The `id` of the invoice that will be cloned. + """ + + class CreateParamsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsPaymentSettings(TypedDict): + default_mandate: NotRequired["Literal['']|str"] + """ + ID of the mandate to be used for this invoice. It must correspond to the payment method used to pay the invoice, including the invoice's default_payment_method or default_source, if set. + """ + payment_method_options: NotRequired[ + "InvoiceService.CreateParamsPaymentSettingsPaymentMethodOptions" + ] + """ + Payment-method-specific configuration to provide to the invoice's PaymentIntent. + """ + payment_method_types: NotRequired[ + "Literal['']|List[Literal['ach_credit_transfer', 'ach_debit', 'acss_debit', 'au_becs_debit', 'bacs_debit', 'bancontact', 'boleto', 'card', 'cashapp', 'customer_balance', 'eps', 'fpx', 'giropay', 'grabpay', 'ideal', 'konbini', 'link', 'p24', 'paynow', 'paypal', 'promptpay', 'sepa_credit_transfer', 'sepa_debit', 'sofort', 'us_bank_account', 'wechat_pay']]" + ] + """ + The list of payment method types (e.g. card) to provide to the invoice's PaymentIntent. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). + """ + + class CreateParamsPaymentSettingsPaymentMethodOptions(TypedDict): + acss_debit: NotRequired[ + "Literal['']|InvoiceService.CreateParamsPaymentSettingsPaymentMethodOptionsAcssDebit" + ] + """ + If paying by `acss_debit`, this sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. + """ + bancontact: NotRequired[ + "Literal['']|InvoiceService.CreateParamsPaymentSettingsPaymentMethodOptionsBancontact" + ] + """ + If paying by `bancontact`, this sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. + """ + card: NotRequired[ + "Literal['']|InvoiceService.CreateParamsPaymentSettingsPaymentMethodOptionsCard" + ] + """ + If paying by `card`, this sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. + """ + customer_balance: NotRequired[ + "Literal['']|InvoiceService.CreateParamsPaymentSettingsPaymentMethodOptionsCustomerBalance" + ] + """ + If paying by `customer_balance`, this sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. + """ + konbini: NotRequired[ + "Literal['']|InvoiceService.CreateParamsPaymentSettingsPaymentMethodOptionsKonbini" + ] + """ + If paying by `konbini`, this sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. + """ + us_bank_account: NotRequired[ + "Literal['']|InvoiceService.CreateParamsPaymentSettingsPaymentMethodOptionsUsBankAccount" + ] + """ + If paying by `us_bank_account`, this sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsAcssDebit(TypedDict): + mandate_options: NotRequired[ + "InvoiceService.CreateParamsPaymentSettingsPaymentMethodOptionsAcssDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Verification method for the intent + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsAcssDebitMandateOptions( + TypedDict, + ): + transaction_type: NotRequired["Literal['business', 'personal']"] + """ + Transaction type of the mandate. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsBancontact(TypedDict): + preferred_language: NotRequired["Literal['de', 'en', 'fr', 'nl']"] + """ + Preferred language of the Bancontact authorization page that the customer is redirected to. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsCard(TypedDict): + installments: NotRequired[ + "InvoiceService.CreateParamsPaymentSettingsPaymentMethodOptionsCardInstallments" + ] + """ + Installment configuration for payments attempted on this invoice (Mexico Only). + + For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + """ + request_three_d_secure: NotRequired[ + "Literal['any', 'automatic', 'challenge']" + ] + """ + We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsCardInstallments( + TypedDict, + ): + enabled: NotRequired["bool"] + """ + Setting to true enables installments for this invoice. + Setting to false will prevent any selected plan from applying to a payment. + """ + plan: NotRequired[ + "Literal['']|InvoiceService.CreateParamsPaymentSettingsPaymentMethodOptionsCardInstallmentsPlan" + ] + """ + The selected installment plan to use for this invoice. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsCardInstallmentsPlan( + TypedDict, + ): + count: int + """ + For `fixed_count` installment plans, this is the number of installment payments your customer will make to their credit card. + """ + interval: Literal["month"] + """ + For `fixed_count` installment plans, this is the interval between installment payments your customer will make to their credit card. + One of `month`. + """ + type: Literal["fixed_count"] + """ + Type of installment plan, one of `fixed_count`. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsCustomerBalance( + TypedDict, + ): + bank_transfer: NotRequired[ + "InvoiceService.CreateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer" + ] + """ + Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + """ + funding_type: NotRequired["str"] + """ + The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer( + TypedDict, + ): + eu_bank_transfer: NotRequired[ + "InvoiceService.CreateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer" + ] + """ + Configuration for eu_bank_transfer funding type. + """ + type: NotRequired["str"] + """ + The bank transfer type that can be used for funding. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer( + TypedDict, + ): + country: str + """ + The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsKonbini(TypedDict): + pass + + class CreateParamsPaymentSettingsPaymentMethodOptionsUsBankAccount( + TypedDict, + ): + financial_connections: NotRequired[ + "InvoiceService.CreateParamsPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnections" + ] + """ + Additional fields for Financial Connections Session creation + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Verification method for the intent + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnections( + TypedDict, + ): + permissions: NotRequired[ + "List[Literal['balances', 'ownership', 'payment_method', 'transactions']]" + ] + """ + The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + """ + prefetch: NotRequired["List[Literal['balances', 'transactions']]"] + """ + List of data features that you would like to retrieve upon account creation. + """ + + class CreateParamsRendering(TypedDict): + amount_tax_display: NotRequired[ + "Literal['']|Literal['exclude_tax', 'include_inclusive_tax']" + ] + """ + How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + """ + pdf: NotRequired["InvoiceService.CreateParamsRenderingPdf"] + """ + Invoice pdf rendering options + """ + + class CreateParamsRenderingOptions(TypedDict): + amount_tax_display: NotRequired[ + "Literal['']|Literal['exclude_tax', 'include_inclusive_tax']" + ] + """ + How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + """ + + class CreateParamsRenderingPdf(TypedDict): + page_size: NotRequired["Literal['a4', 'auto', 'letter']"] + """ + Page size for invoice PDF. Can be set to `a4`, `letter`, or `auto`. + If set to `auto`, invoice PDF page size defaults to `a4` for customers with + Japanese locale and `letter` for customers with other locales. + """ + + class CreateParamsShippingCost(TypedDict): + shipping_rate: NotRequired["str"] + """ + The ID of the shipping rate to use for this order. + """ + shipping_rate_data: NotRequired[ + "InvoiceService.CreateParamsShippingCostShippingRateData" + ] + """ + Parameters to create a new ad-hoc shipping rate for this order. + """ + + class CreateParamsShippingCostShippingRateData(TypedDict): + delivery_estimate: NotRequired[ + "InvoiceService.CreateParamsShippingCostShippingRateDataDeliveryEstimate" + ] + """ + The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. + """ + display_name: str + """ + The name of the shipping rate, meant to be displayable to the customer. This will appear on CheckoutSessions. + """ + fixed_amount: NotRequired[ + "InvoiceService.CreateParamsShippingCostShippingRateDataFixedAmount" + ] + """ + Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + """ + tax_code: NotRequired["str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. The Shipping tax code is `txcd_92010001`. + """ + type: NotRequired["Literal['fixed_amount']"] + """ + The type of calculation to use on the shipping rate. Can only be `fixed_amount` for now. + """ + + class CreateParamsShippingCostShippingRateDataDeliveryEstimate(TypedDict): + maximum: NotRequired[ + "InvoiceService.CreateParamsShippingCostShippingRateDataDeliveryEstimateMaximum" + ] + """ + The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. + """ + minimum: NotRequired[ + "InvoiceService.CreateParamsShippingCostShippingRateDataDeliveryEstimateMinimum" + ] + """ + The lower bound of the estimated range. If empty, represents no lower bound. + """ + + class CreateParamsShippingCostShippingRateDataDeliveryEstimateMaximum( + TypedDict, + ): + unit: Literal["business_day", "day", "hour", "month", "week"] + """ + A unit of time. + """ + value: int + """ + Must be greater than 0. + """ + + class CreateParamsShippingCostShippingRateDataDeliveryEstimateMinimum( + TypedDict, + ): + unit: Literal["business_day", "day", "hour", "month", "week"] + """ + A unit of time. + """ + value: int + """ + Must be greater than 0. + """ + + class CreateParamsShippingCostShippingRateDataFixedAmount(TypedDict): + amount: int + """ + A non-negative integer in cents representing how much to charge. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + currency_options: NotRequired[ + "Dict[str, InvoiceService.CreateParamsShippingCostShippingRateDataFixedAmountCurrencyOptions]" + ] + """ + Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + """ + + class CreateParamsShippingCostShippingRateDataFixedAmountCurrencyOptions( + TypedDict, + ): + amount: int + """ + A non-negative integer in cents representing how much to charge. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + """ + + class CreateParamsShippingDetails(TypedDict): + address: "InvoiceService.CreateParamsShippingDetailsAddress" + """ + Shipping address + """ + name: str + """ + Recipient name. + """ + phone: NotRequired["Literal['']|str"] + """ + Recipient phone (including extension) + """ + + class CreateParamsShippingDetailsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsTransferData(TypedDict): + amount: NotRequired["int"] + """ + The amount that will be transferred automatically when the invoice is paid. If no amount is set, the full amount is transferred. + """ + destination: str + """ + ID of an existing, connected Stripe account. + """ + + class DeleteParams(TypedDict): + pass + + class FinalizeInvoiceParams(TypedDict): + auto_advance: NotRequired["bool"] + """ + Controls whether Stripe performs [automatic collection](https://stripe.com/docs/invoicing/integration/automatic-advancement-collection) of the invoice. If `false`, the invoice's state doesn't automatically advance without an explicit action. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ListParams(TypedDict): + collection_method: NotRequired[ + "Literal['charge_automatically', 'send_invoice']" + ] + """ + The collection method of the invoice to retrieve. Either `charge_automatically` or `send_invoice`. + """ + created: NotRequired["InvoiceService.ListParamsCreated|int"] + customer: NotRequired["str"] + """ + Only return invoices for the customer specified by this customer ID. + """ + due_date: NotRequired["InvoiceService.ListParamsDueDate|int"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired[ + "Literal['draft', 'open', 'paid', 'uncollectible', 'void']" + ] + """ + The status of the invoice, one of `draft`, `open`, `paid`, `uncollectible`, or `void`. [Learn more](https://stripe.com/docs/billing/invoices/workflow#workflow-overview) + """ + subscription: NotRequired["str"] + """ + Only return invoices for the subscription specified by this subscription ID. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ListParamsDueDate(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class MarkUncollectibleParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class PayParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + forgive: NotRequired["bool"] + """ + In cases where the source used to pay the invoice has insufficient funds, passing `forgive=true` controls whether a charge should be attempted for the full amount available on the source, up to the amount to fully pay the invoice. This effectively forgives the difference between the amount available on the source and the amount due. + + Passing `forgive=false` will fail the charge if the source hasn't been pre-funded with the right amount. An example for this case is with ACH Credit Transfers and wires: if the amount wired is less than the amount due by a small amount, you might want to forgive the difference. Defaults to `false`. + """ + mandate: NotRequired["Literal['']|str"] + """ + ID of the mandate to be used for this invoice. It must correspond to the payment method used to pay the invoice, including the payment_method param or the invoice's default_payment_method or default_source, if set. + """ + off_session: NotRequired["bool"] + """ + Indicates if a customer is on or off-session while an invoice payment is attempted. Defaults to `true` (off-session). + """ + paid_out_of_band: NotRequired["bool"] + """ + Boolean representing whether an invoice is paid outside of Stripe. This will result in no charge being made. Defaults to `false`. + """ + payment_method: NotRequired["str"] + """ + A PaymentMethod to be charged. The PaymentMethod must be the ID of a PaymentMethod belonging to the customer associated with the invoice being paid. + """ + source: NotRequired["str"] + """ + A payment source to be charged. The source must be the ID of a source belonging to the customer associated with the invoice being paid. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class SearchParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + page: NotRequired["str"] + """ + A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + """ + query: str + """ + The search query string. See [search query language](https://stripe.com/docs/search#search-query-language) and the list of supported [query fields for invoices](https://stripe.com/docs/search#query-fields-for-invoices). + """ + + class SendInvoiceParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpcomingParams(TypedDict): + automatic_tax: NotRequired["InvoiceService.UpcomingParamsAutomaticTax"] + """ + Settings for automatic tax lookup for this invoice preview. + """ + coupon: NotRequired["str"] + """ + The code of the coupon to apply. If `subscription` or `subscription_items` is provided, the invoice returned will preview updating or creating a subscription with that coupon. Otherwise, it will preview applying that coupon to the customer for the next upcoming invoice from among the customer's subscriptions. The invoice can be previewed without a coupon by passing this value as an empty string. + """ + currency: NotRequired["str"] + """ + The currency to preview this invoice in. Defaults to that of `customer` if not specified. + """ + customer: NotRequired["str"] + """ + The identifier of the customer whose upcoming invoice you'd like to retrieve. If `automatic_tax` is enabled then one of `customer`, `customer_details`, `subscription`, or `schedule` must be set. + """ + customer_details: NotRequired[ + "InvoiceService.UpcomingParamsCustomerDetails" + ] + """ + Details about the customer you want to invoice or overrides for an existing customer. If `automatic_tax` is enabled then one of `customer`, `customer_details`, `subscription`, or `schedule` must be set. + """ + discounts: NotRequired[ + "Literal['']|List[InvoiceService.UpcomingParamsDiscount]" + ] + """ + The coupons to redeem into discounts for the invoice preview. If not specified, inherits the discount from the customer or subscription. This only works for coupons directly applied to the invoice. To apply a coupon to a subscription, you must use the `coupon` parameter instead. Pass an empty string to avoid inheriting any discounts. To preview the upcoming invoice for a subscription that hasn't been created, use `coupon` instead. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice_items: NotRequired[ + "List[InvoiceService.UpcomingParamsInvoiceItem]" + ] + """ + List of invoice items to add or update in the upcoming invoice preview. + """ + issuer: NotRequired["InvoiceService.UpcomingParamsIssuer"] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + on_behalf_of: NotRequired["Literal['']|str"] + """ + The account (if any) for which the funds of the invoice payment are intended. If set, the invoice will be presented with the branding and support information of the specified account. See the [Invoices with Connect](https://stripe.com/docs/billing/invoices/connect) documentation for details. + """ + schedule: NotRequired["str"] + """ + The identifier of the schedule whose upcoming invoice you'd like to retrieve. Cannot be used with subscription or subscription fields. + """ + subscription: NotRequired["str"] + """ + The identifier of the subscription for which you'd like to retrieve the upcoming invoice. If not provided, but a `subscription_items` is provided, you will preview creating a subscription with those items. If neither `subscription` nor `subscription_items` is provided, you will retrieve the next upcoming invoice from among the customer's subscriptions. + """ + subscription_billing_cycle_anchor: NotRequired[ + "Literal['now', 'unchanged']|int" + ] + """ + For new subscriptions, a future timestamp to anchor the subscription's [billing cycle](https://stripe.com/docs/subscriptions/billing-cycle). This is used to determine the date of the first full invoice, and, for plans with `month` or `year` intervals, the day of the month for subsequent invoices. For existing subscriptions, the value can only be set to `now` or `unchanged`. + """ + subscription_cancel_at: NotRequired["Literal['']|int"] + """ + A timestamp at which the subscription should cancel. If set to a date before the current period ends, this will cause a proration if prorations have been enabled using `proration_behavior`. If set during a future period, this will always cause a proration for that period. + """ + subscription_cancel_at_period_end: NotRequired["bool"] + """ + Boolean indicating whether this subscription should cancel at the end of the current period. + """ + subscription_cancel_now: NotRequired["bool"] + """ + This simulates the subscription being canceled or expired immediately. + """ + subscription_default_tax_rates: NotRequired["Literal['']|List[str]"] + """ + If provided, the invoice returned will preview updating or creating a subscription with these default tax rates. The default tax rates will apply to any line item that does not have `tax_rates` set. + """ + subscription_items: NotRequired[ + "List[InvoiceService.UpcomingParamsSubscriptionItem]" + ] + """ + A list of up to 20 subscription items, each with an attached price. + """ + subscription_proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + """ + subscription_proration_date: NotRequired["int"] + """ + If previewing an update to a subscription, and doing proration, `subscription_proration_date` forces the proration to be calculated as though the update was done at the specified time. The time given must be within the current subscription period and within the current phase of the schedule backing this subscription, if the schedule exists. If set, `subscription`, and one of `subscription_items`, or `subscription_trial_end` are required. Also, `subscription_proration_behavior` cannot be set to 'none'. + """ + subscription_resume_at: NotRequired["Literal['now']"] + """ + For paused subscriptions, setting `subscription_resume_at` to `now` will preview the invoice that will be generated if the subscription is resumed. + """ + subscription_start_date: NotRequired["int"] + """ + Date a subscription is intended to start (can be future or past). + """ + subscription_trial_end: NotRequired["Literal['now']|int"] + """ + If provided, the invoice returned will preview updating or creating a subscription with that trial end. If set, one of `subscription_items` or `subscription` is required. + """ + subscription_trial_from_plan: NotRequired["bool"] + """ + Indicates if a plan's `trial_period_days` should be applied to the subscription. Setting `subscription_trial_end` per subscription is preferred, and this defaults to `false`. Setting this flag to `true` together with `subscription_trial_end` is not allowed. See [Using trial periods on subscriptions](https://stripe.com/docs/billing/subscriptions/trials) to learn more. + """ + + class UpcomingParamsAutomaticTax(TypedDict): + enabled: bool + """ + Whether Stripe automatically computes tax on this invoice. Note that incompatible invoice items (invoice items with manually specified [tax rates](https://stripe.com/docs/api/tax_rates), negative amounts, or `tax_behavior=unspecified`) cannot be added to automatic tax invoices. + """ + liability: NotRequired[ + "InvoiceService.UpcomingParamsAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class UpcomingParamsAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpcomingParamsCustomerDetails(TypedDict): + address: NotRequired[ + "Literal['']|InvoiceService.UpcomingParamsCustomerDetailsAddress" + ] + """ + The customer's address. + """ + shipping: NotRequired[ + "Literal['']|InvoiceService.UpcomingParamsCustomerDetailsShipping" + ] + """ + The customer's shipping information. Appears on invoices emailed to this customer. + """ + tax: NotRequired["InvoiceService.UpcomingParamsCustomerDetailsTax"] + """ + Tax details about the customer. + """ + tax_exempt: NotRequired[ + "Literal['']|Literal['exempt', 'none', 'reverse']" + ] + """ + The customer's tax exemption. One of `none`, `exempt`, or `reverse`. + """ + tax_ids: NotRequired[ + "List[InvoiceService.UpcomingParamsCustomerDetailsTaxId]" + ] + """ + The customer's tax IDs. + """ + + class UpcomingParamsCustomerDetailsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpcomingParamsCustomerDetailsShipping(TypedDict): + address: "InvoiceService.UpcomingParamsCustomerDetailsShippingAddress" + """ + Customer shipping address. + """ + name: str + """ + Customer name. + """ + phone: NotRequired["str"] + """ + Customer phone (including extension). + """ + + class UpcomingParamsCustomerDetailsShippingAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpcomingParamsCustomerDetailsTax(TypedDict): + ip_address: NotRequired["Literal['']|str"] + """ + A recent IP address of the customer used for tax reporting and tax location inference. Stripe recommends updating the IP address when a new PaymentMethod is attached or the address field on the customer is updated. We recommend against updating this field more frequently since it could result in unexpected tax location/reporting outcomes. + """ + + class UpcomingParamsCustomerDetailsTaxId(TypedDict): + type: Literal[ + "ad_nrt", + "ae_trn", + "ar_cuit", + "au_abn", + "au_arn", + "bg_uic", + "bo_tin", + "br_cnpj", + "br_cpf", + "ca_bn", + "ca_gst_hst", + "ca_pst_bc", + "ca_pst_mb", + "ca_pst_sk", + "ca_qst", + "ch_vat", + "cl_tin", + "cn_tin", + "co_nit", + "cr_tin", + "do_rcn", + "ec_ruc", + "eg_tin", + "es_cif", + "eu_oss_vat", + "eu_vat", + "gb_vat", + "ge_vat", + "hk_br", + "hu_tin", + "id_npwp", + "il_vat", + "in_gst", + "is_vat", + "jp_cn", + "jp_rn", + "jp_trn", + "ke_pin", + "kr_brn", + "li_uid", + "mx_rfc", + "my_frp", + "my_itn", + "my_sst", + "no_vat", + "nz_gst", + "pe_ruc", + "ph_tin", + "ro_tin", + "rs_pib", + "ru_inn", + "ru_kpp", + "sa_vat", + "sg_gst", + "sg_uen", + "si_tin", + "sv_nit", + "th_vat", + "tr_tin", + "tw_vat", + "ua_vat", + "us_ein", + "uy_ruc", + "ve_rif", + "vn_tin", + "za_vat", + ] + """ + Type of the tax ID, one of `ad_nrt`, `ae_trn`, `ar_cuit`, `au_abn`, `au_arn`, `bg_uic`, `bo_tin`, `br_cnpj`, `br_cpf`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `ch_vat`, `cl_tin`, `cn_tin`, `co_nit`, `cr_tin`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `hk_br`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kr_brn`, `li_uid`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `no_vat`, `nz_gst`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sv_nit`, `th_vat`, `tr_tin`, `tw_vat`, `ua_vat`, `us_ein`, `uy_ruc`, `ve_rif`, `vn_tin`, or `za_vat` + """ + value: str + """ + Value of the tax ID. + """ + + class UpcomingParamsDiscount(TypedDict): + coupon: NotRequired["str"] + """ + ID of the coupon to create a new discount for. + """ + discount: NotRequired["str"] + """ + ID of an existing discount on the object (or one of its ancestors) to reuse. + """ + promotion_code: NotRequired["str"] + """ + ID of the promotion code to create a new discount for. + """ + + class UpcomingParamsInvoiceItem(TypedDict): + amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) of previewed invoice item. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). Only applicable to new invoice items. + """ + description: NotRequired["str"] + """ + An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. + """ + discountable: NotRequired["bool"] + """ + Explicitly controls whether discounts apply to this invoice item. Defaults to true, except for negative invoice items. + """ + discounts: NotRequired[ + "Literal['']|List[InvoiceService.UpcomingParamsInvoiceItemDiscount]" + ] + """ + The coupons to redeem into discounts for the invoice item in the preview. + """ + invoiceitem: NotRequired["str"] + """ + The ID of the invoice item to update in preview. If not specified, a new invoice item will be added to the preview of the upcoming invoice. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + period: NotRequired["InvoiceService.UpcomingParamsInvoiceItemPeriod"] + """ + The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. + """ + price: NotRequired["str"] + """ + The ID of the price object. + """ + price_data: NotRequired[ + "InvoiceService.UpcomingParamsInvoiceItemPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Non-negative integer. The quantity of units for the invoice item. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + tax_code: NotRequired["Literal['']|str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates that apply to the item. When set, any `default_tax_rates` do not apply to this item. + """ + unit_amount: NotRequired["int"] + """ + The integer unit amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. This unit_amount will be multiplied by the quantity to get the full amount. If you want to apply a credit to the customer's account, pass a negative unit_amount. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class UpcomingParamsInvoiceItemDiscount(TypedDict): + coupon: NotRequired["str"] + """ + ID of the coupon to create a new discount for. + """ + discount: NotRequired["str"] + """ + ID of an existing discount on the object (or one of its ancestors) to reuse. + """ + promotion_code: NotRequired["str"] + """ + ID of the promotion code to create a new discount for. + """ + + class UpcomingParamsInvoiceItemPeriod(TypedDict): + end: int + """ + The end of the period, which must be greater than or equal to the start. This value is inclusive. + """ + start: int + """ + The start of the period. This value is inclusive. + """ + + class UpcomingParamsInvoiceItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class UpcomingParamsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpcomingParamsSubscriptionItem(TypedDict): + billing_thresholds: NotRequired[ + "Literal['']|InvoiceService.UpcomingParamsSubscriptionItemBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. + """ + clear_usage: NotRequired["bool"] + """ + Delete all usage for a given subscription item. Allowed only when `deleted` is set to `true` and the current plan's `usage_type` is `metered`. + """ + deleted: NotRequired["bool"] + """ + A flag that, if set to `true`, will delete the specified item. + """ + id: NotRequired["str"] + """ + Subscription item to update. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + plan: NotRequired["str"] + """ + Plan ID for this item, as a string. + """ + price: NotRequired["str"] + """ + The ID of the price object. When changing a subscription item's price, `quantity` is set to 1 unless a `quantity` parameter is provided. + """ + price_data: NotRequired[ + "InvoiceService.UpcomingParamsSubscriptionItemPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Quantity for this item. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + """ + + class UpcomingParamsSubscriptionItemBillingThresholds(TypedDict): + usage_gte: int + """ + Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + """ + + class UpcomingParamsSubscriptionItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + recurring: "InvoiceService.UpcomingParamsSubscriptionItemPriceDataRecurring" + """ + The recurring components of a price such as `interval` and `interval_count`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class UpcomingParamsSubscriptionItemPriceDataRecurring(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + + class UpdateParams(TypedDict): + account_tax_ids: NotRequired["Literal['']|List[str]"] + """ + The account tax IDs associated with the invoice. Only editable when the invoice is a draft. + """ + application_fee_amount: NotRequired["int"] + """ + A fee in cents (or local equivalent) that will be applied to the invoice and transferred to the application owner's Stripe account. The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. For more information, see the application fees [documentation](https://stripe.com/docs/billing/invoices/connect#collecting-fees). + """ + auto_advance: NotRequired["bool"] + """ + Controls whether Stripe performs [automatic collection](https://stripe.com/docs/invoicing/integration/automatic-advancement-collection) of the invoice. + """ + automatic_tax: NotRequired["InvoiceService.UpdateParamsAutomaticTax"] + """ + Settings for automatic tax lookup for this invoice. + """ + collection_method: NotRequired[ + "Literal['charge_automatically', 'send_invoice']" + ] + """ + Either `charge_automatically` or `send_invoice`. This field can be updated only on `draft` invoices. + """ + custom_fields: NotRequired[ + "Literal['']|List[InvoiceService.UpdateParamsCustomField]" + ] + """ + A list of up to 4 custom fields to be displayed on the invoice. If a value for `custom_fields` is specified, the list specified will replace the existing custom field list on this invoice. Pass an empty string to remove previously-defined fields. + """ + days_until_due: NotRequired["int"] + """ + The number of days from which the invoice is created until it is due. Only valid for invoices where `collection_method=send_invoice`. This field can only be updated on `draft` invoices. + """ + default_payment_method: NotRequired["str"] + """ + ID of the default payment method for the invoice. It must belong to the customer associated with the invoice. If not set, defaults to the subscription's default payment method, if any, or to the default payment method in the customer's invoice settings. + """ + default_source: NotRequired["Literal['']|str"] + """ + ID of the default payment source for the invoice. It must belong to the customer associated with the invoice and be in a chargeable state. If not set, defaults to the subscription's default source, if any, or to the customer's default source. + """ + default_tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates that will apply to any line item that does not have `tax_rates` set. Pass an empty string to remove previously-defined tax rates. + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. Referenced as 'memo' in the Dashboard. + """ + discounts: NotRequired[ + "Literal['']|List[InvoiceService.UpdateParamsDiscount]" + ] + """ + The discounts that will apply to the invoice. Pass an empty string to remove previously-defined discounts. + """ + due_date: NotRequired["int"] + """ + The date on which payment for this invoice is due. Only valid for invoices where `collection_method=send_invoice`. This field can only be updated on `draft` invoices. + """ + effective_at: NotRequired["Literal['']|int"] + """ + The date when this invoice is in effect. Same as `finalized_at` unless overwritten. When defined, this value replaces the system-generated 'Date of issue' printed on the invoice PDF and receipt. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + footer: NotRequired["str"] + """ + Footer to be displayed on the invoice. + """ + issuer: NotRequired["InvoiceService.UpdateParamsIssuer"] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + on_behalf_of: NotRequired["Literal['']|str"] + """ + The account (if any) for which the funds of the invoice payment are intended. If set, the invoice will be presented with the branding and support information of the specified account. See the [Invoices with Connect](https://stripe.com/docs/billing/invoices/connect) documentation for details. + """ + payment_settings: NotRequired[ + "InvoiceService.UpdateParamsPaymentSettings" + ] + """ + Configuration settings for the PaymentIntent that is generated when the invoice is finalized. + """ + rendering: NotRequired["InvoiceService.UpdateParamsRendering"] + """ + The rendering-related settings that control how the invoice is displayed on customer-facing surfaces such as PDF and Hosted Invoice Page. + """ + rendering_options: NotRequired[ + "Literal['']|InvoiceService.UpdateParamsRenderingOptions" + ] + """ + This is a legacy field that will be removed soon. For details about `rendering_options`, refer to `rendering` instead. Options for invoice PDF rendering. + """ + shipping_cost: NotRequired[ + "Literal['']|InvoiceService.UpdateParamsShippingCost" + ] + """ + Settings for the cost of shipping for this invoice. + """ + shipping_details: NotRequired[ + "Literal['']|InvoiceService.UpdateParamsShippingDetails" + ] + """ + Shipping details for the invoice. The Invoice PDF will use the `shipping_details` value if it is set, otherwise the PDF will render the shipping address from the customer. + """ + statement_descriptor: NotRequired["str"] + """ + Extra information about a charge for the customer's credit card statement. It must contain at least one letter. If not specified and this invoice is part of a subscription, the default `statement_descriptor` will be set to the first subscription item's product's `statement_descriptor`. + """ + transfer_data: NotRequired[ + "Literal['']|InvoiceService.UpdateParamsTransferData" + ] + """ + If specified, the funds from the invoice will be transferred to the destination and the ID of the resulting transfer will be found on the invoice's charge. This will be unset if you POST an empty value. + """ + + class UpdateParamsAutomaticTax(TypedDict): + enabled: bool + """ + Whether Stripe automatically computes tax on this invoice. Note that incompatible invoice items (invoice items with manually specified [tax rates](https://stripe.com/docs/api/tax_rates), negative amounts, or `tax_behavior=unspecified`) cannot be added to automatic tax invoices. + """ + liability: NotRequired[ + "InvoiceService.UpdateParamsAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class UpdateParamsAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpdateParamsCustomField(TypedDict): + name: str + """ + The name of the custom field. This may be up to 30 characters. + """ + value: str + """ + The value of the custom field. This may be up to 30 characters. + """ + + class UpdateParamsDiscount(TypedDict): + coupon: NotRequired["str"] + """ + ID of the coupon to create a new discount for. + """ + discount: NotRequired["str"] + """ + ID of an existing discount on the object (or one of its ancestors) to reuse. + """ + + class UpdateParamsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpdateParamsPaymentSettings(TypedDict): + default_mandate: NotRequired["Literal['']|str"] + """ + ID of the mandate to be used for this invoice. It must correspond to the payment method used to pay the invoice, including the invoice's default_payment_method or default_source, if set. + """ + payment_method_options: NotRequired[ + "InvoiceService.UpdateParamsPaymentSettingsPaymentMethodOptions" + ] + """ + Payment-method-specific configuration to provide to the invoice's PaymentIntent. + """ + payment_method_types: NotRequired[ + "Literal['']|List[Literal['ach_credit_transfer', 'ach_debit', 'acss_debit', 'au_becs_debit', 'bacs_debit', 'bancontact', 'boleto', 'card', 'cashapp', 'customer_balance', 'eps', 'fpx', 'giropay', 'grabpay', 'ideal', 'konbini', 'link', 'p24', 'paynow', 'paypal', 'promptpay', 'sepa_credit_transfer', 'sepa_debit', 'sofort', 'us_bank_account', 'wechat_pay']]" + ] + """ + The list of payment method types (e.g. card) to provide to the invoice's PaymentIntent. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptions(TypedDict): + acss_debit: NotRequired[ + "Literal['']|InvoiceService.UpdateParamsPaymentSettingsPaymentMethodOptionsAcssDebit" + ] + """ + If paying by `acss_debit`, this sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. + """ + bancontact: NotRequired[ + "Literal['']|InvoiceService.UpdateParamsPaymentSettingsPaymentMethodOptionsBancontact" + ] + """ + If paying by `bancontact`, this sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. + """ + card: NotRequired[ + "Literal['']|InvoiceService.UpdateParamsPaymentSettingsPaymentMethodOptionsCard" + ] + """ + If paying by `card`, this sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. + """ + customer_balance: NotRequired[ + "Literal['']|InvoiceService.UpdateParamsPaymentSettingsPaymentMethodOptionsCustomerBalance" + ] + """ + If paying by `customer_balance`, this sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. + """ + konbini: NotRequired[ + "Literal['']|InvoiceService.UpdateParamsPaymentSettingsPaymentMethodOptionsKonbini" + ] + """ + If paying by `konbini`, this sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. + """ + us_bank_account: NotRequired[ + "Literal['']|InvoiceService.UpdateParamsPaymentSettingsPaymentMethodOptionsUsBankAccount" + ] + """ + If paying by `us_bank_account`, this sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsAcssDebit(TypedDict): + mandate_options: NotRequired[ + "InvoiceService.UpdateParamsPaymentSettingsPaymentMethodOptionsAcssDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Verification method for the intent + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsAcssDebitMandateOptions( + TypedDict, + ): + transaction_type: NotRequired["Literal['business', 'personal']"] + """ + Transaction type of the mandate. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsBancontact(TypedDict): + preferred_language: NotRequired["Literal['de', 'en', 'fr', 'nl']"] + """ + Preferred language of the Bancontact authorization page that the customer is redirected to. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsCard(TypedDict): + installments: NotRequired[ + "InvoiceService.UpdateParamsPaymentSettingsPaymentMethodOptionsCardInstallments" + ] + """ + Installment configuration for payments attempted on this invoice (Mexico Only). + + For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + """ + request_three_d_secure: NotRequired[ + "Literal['any', 'automatic', 'challenge']" + ] + """ + We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsCardInstallments( + TypedDict, + ): + enabled: NotRequired["bool"] + """ + Setting to true enables installments for this invoice. + Setting to false will prevent any selected plan from applying to a payment. + """ + plan: NotRequired[ + "Literal['']|InvoiceService.UpdateParamsPaymentSettingsPaymentMethodOptionsCardInstallmentsPlan" + ] + """ + The selected installment plan to use for this invoice. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsCardInstallmentsPlan( + TypedDict, + ): + count: int + """ + For `fixed_count` installment plans, this is the number of installment payments your customer will make to their credit card. + """ + interval: Literal["month"] + """ + For `fixed_count` installment plans, this is the interval between installment payments your customer will make to their credit card. + One of `month`. + """ + type: Literal["fixed_count"] + """ + Type of installment plan, one of `fixed_count`. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsCustomerBalance( + TypedDict, + ): + bank_transfer: NotRequired[ + "InvoiceService.UpdateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer" + ] + """ + Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + """ + funding_type: NotRequired["str"] + """ + The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer( + TypedDict, + ): + eu_bank_transfer: NotRequired[ + "InvoiceService.UpdateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer" + ] + """ + Configuration for eu_bank_transfer funding type. + """ + type: NotRequired["str"] + """ + The bank transfer type that can be used for funding. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer( + TypedDict, + ): + country: str + """ + The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsKonbini(TypedDict): + pass + + class UpdateParamsPaymentSettingsPaymentMethodOptionsUsBankAccount( + TypedDict, + ): + financial_connections: NotRequired[ + "InvoiceService.UpdateParamsPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnections" + ] + """ + Additional fields for Financial Connections Session creation + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Verification method for the intent + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnections( + TypedDict, + ): + permissions: NotRequired[ + "List[Literal['balances', 'ownership', 'payment_method', 'transactions']]" + ] + """ + The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + """ + prefetch: NotRequired["List[Literal['balances', 'transactions']]"] + """ + List of data features that you would like to retrieve upon account creation. + """ + + class UpdateParamsRendering(TypedDict): + amount_tax_display: NotRequired[ + "Literal['']|Literal['exclude_tax', 'include_inclusive_tax']" + ] + """ + How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + """ + pdf: NotRequired["InvoiceService.UpdateParamsRenderingPdf"] + """ + Invoice pdf rendering options + """ + + class UpdateParamsRenderingOptions(TypedDict): + amount_tax_display: NotRequired[ + "Literal['']|Literal['exclude_tax', 'include_inclusive_tax']" + ] + """ + How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + """ + + class UpdateParamsRenderingPdf(TypedDict): + page_size: NotRequired["Literal['a4', 'auto', 'letter']"] + """ + Page size for invoice PDF. Can be set to `a4`, `letter`, or `auto`. + If set to `auto`, invoice PDF page size defaults to `a4` for customers with + Japanese locale and `letter` for customers with other locales. + """ + + class UpdateParamsShippingCost(TypedDict): + shipping_rate: NotRequired["str"] + """ + The ID of the shipping rate to use for this order. + """ + shipping_rate_data: NotRequired[ + "InvoiceService.UpdateParamsShippingCostShippingRateData" + ] + """ + Parameters to create a new ad-hoc shipping rate for this order. + """ + + class UpdateParamsShippingCostShippingRateData(TypedDict): + delivery_estimate: NotRequired[ + "InvoiceService.UpdateParamsShippingCostShippingRateDataDeliveryEstimate" + ] + """ + The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. + """ + display_name: str + """ + The name of the shipping rate, meant to be displayable to the customer. This will appear on CheckoutSessions. + """ + fixed_amount: NotRequired[ + "InvoiceService.UpdateParamsShippingCostShippingRateDataFixedAmount" + ] + """ + Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + """ + tax_code: NotRequired["str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. The Shipping tax code is `txcd_92010001`. + """ + type: NotRequired["Literal['fixed_amount']"] + """ + The type of calculation to use on the shipping rate. Can only be `fixed_amount` for now. + """ + + class UpdateParamsShippingCostShippingRateDataDeliveryEstimate(TypedDict): + maximum: NotRequired[ + "InvoiceService.UpdateParamsShippingCostShippingRateDataDeliveryEstimateMaximum" + ] + """ + The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. + """ + minimum: NotRequired[ + "InvoiceService.UpdateParamsShippingCostShippingRateDataDeliveryEstimateMinimum" + ] + """ + The lower bound of the estimated range. If empty, represents no lower bound. + """ + + class UpdateParamsShippingCostShippingRateDataDeliveryEstimateMaximum( + TypedDict, + ): + unit: Literal["business_day", "day", "hour", "month", "week"] + """ + A unit of time. + """ + value: int + """ + Must be greater than 0. + """ + + class UpdateParamsShippingCostShippingRateDataDeliveryEstimateMinimum( + TypedDict, + ): + unit: Literal["business_day", "day", "hour", "month", "week"] + """ + A unit of time. + """ + value: int + """ + Must be greater than 0. + """ + + class UpdateParamsShippingCostShippingRateDataFixedAmount(TypedDict): + amount: int + """ + A non-negative integer in cents representing how much to charge. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + currency_options: NotRequired[ + "Dict[str, InvoiceService.UpdateParamsShippingCostShippingRateDataFixedAmountCurrencyOptions]" + ] + """ + Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + """ + + class UpdateParamsShippingCostShippingRateDataFixedAmountCurrencyOptions( + TypedDict, + ): + amount: int + """ + A non-negative integer in cents representing how much to charge. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + """ + + class UpdateParamsShippingDetails(TypedDict): + address: "InvoiceService.UpdateParamsShippingDetailsAddress" + """ + Shipping address + """ + name: str + """ + Recipient name. + """ + phone: NotRequired["Literal['']|str"] + """ + Recipient phone (including extension) + """ + + class UpdateParamsShippingDetailsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsTransferData(TypedDict): + amount: NotRequired["int"] + """ + The amount that will be transferred automatically when the invoice is paid. If no amount is set, the full amount is transferred. + """ + destination: str + """ + ID of an existing, connected Stripe account. + """ + + class VoidInvoiceParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def delete( + self, + invoice: str, + params: "InvoiceService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> Invoice: + """ + Permanently deletes a one-off invoice draft. This cannot be undone. Attempts to delete invoices that are no longer in a draft state will fail; once an invoice has been finalized or if an invoice is for a subscription, it must be [voided](https://stripe.com/docs/api#void_invoice). + """ + return cast( + Invoice, + self._requestor.request( + "delete", + "/v1/invoices/{invoice}".format( + invoice=_util.sanitize_id(invoice), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + invoice: str, + params: "InvoiceService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Invoice: + """ + Retrieves the invoice with the given ID. + """ + return cast( + Invoice, + self._requestor.request( + "get", + "/v1/invoices/{invoice}".format( + invoice=_util.sanitize_id(invoice), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + invoice: str, + params: "InvoiceService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Invoice: + """ + Draft invoices are fully editable. Once an invoice is [finalized](https://stripe.com/docs/billing/invoices/workflow#finalized), + monetary values, as well as collection_method, become uneditable. + + If you would like to stop the Stripe Billing engine from automatically finalizing, reattempting payments on, + sending reminders for, or [automatically reconciling](https://stripe.com/docs/billing/invoices/reconciliation) invoices, pass + auto_advance=false. + """ + return cast( + Invoice, + self._requestor.request( + "post", + "/v1/invoices/{invoice}".format( + invoice=_util.sanitize_id(invoice), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "InvoiceService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Invoice]: + """ + You can list all invoices, or list the invoices for a specific customer. The invoices are returned sorted by creation date, with the most recently created invoices appearing first. + """ + return cast( + ListObject[Invoice], + self._requestor.request( + "get", + "/v1/invoices", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "InvoiceService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Invoice: + """ + This endpoint creates a draft invoice for a given customer. The invoice remains a draft until you [finalize the invoice, which allows you to [pay](#pay_invoice) or send](https://stripe.com/docs/api#finalize_invoice) the invoice to your customers. + """ + return cast( + Invoice, + self._requestor.request( + "post", + "/v1/invoices", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def search( + self, + params: "InvoiceService.SearchParams", + options: RequestOptions = {}, + ) -> SearchResultObject[Invoice]: + """ + Search for invoices you've previously created using Stripe's [Search Query Language](https://stripe.com/docs/search#search-query-language). + Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating + conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up + to an hour behind during outages. Search functionality is not available to merchants in India. + """ + return cast( + SearchResultObject[Invoice], + self._requestor.request( + "get", + "/v1/invoices/search", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def upcoming( + self, + params: "InvoiceService.UpcomingParams" = {}, + options: RequestOptions = {}, + ) -> Invoice: + """ + At any time, you can preview the upcoming invoice for a customer. This will show you all the charges that are pending, including subscription renewal charges, invoice item charges, etc. It will also show you any discounts that are applicable to the invoice. + + Note that when you are viewing an upcoming invoice, you are simply viewing a preview – the invoice has not yet been created. As such, the upcoming invoice will not show up in invoice listing calls, and you cannot use the API to pay or edit the invoice. If you want to change the amount that your customer will be billed, you can add, remove, or update pending invoice items, or update the customer's discount. + + You can preview the effects of updating a subscription, including a preview of what proration will take place. To ensure that the actual proration is calculated exactly the same as the previewed proration, you should pass a proration_date parameter when doing the actual subscription update. The value passed in should be the same as the subscription_proration_date returned on the upcoming invoice resource. The recommended way to get only the prorations being previewed is to consider only proration line items where period[start] is equal to the subscription_proration_date on the upcoming invoice resource. + """ + return cast( + Invoice, + self._requestor.request( + "get", + "/v1/invoices/upcoming", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def finalize_invoice( + self, + invoice: str, + params: "InvoiceService.FinalizeInvoiceParams" = {}, + options: RequestOptions = {}, + ) -> Invoice: + """ + Stripe automatically finalizes drafts before sending and attempting payment on invoices. However, if you'd like to finalize a draft invoice manually, you can do so using this method. + """ + return cast( + Invoice, + self._requestor.request( + "post", + "/v1/invoices/{invoice}/finalize".format( + invoice=_util.sanitize_id(invoice), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def mark_uncollectible( + self, + invoice: str, + params: "InvoiceService.MarkUncollectibleParams" = {}, + options: RequestOptions = {}, + ) -> Invoice: + """ + Marking an invoice as uncollectible is useful for keeping track of bad debts that can be written off for accounting purposes. + """ + return cast( + Invoice, + self._requestor.request( + "post", + "/v1/invoices/{invoice}/mark_uncollectible".format( + invoice=_util.sanitize_id(invoice), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def pay( + self, + invoice: str, + params: "InvoiceService.PayParams" = {}, + options: RequestOptions = {}, + ) -> Invoice: + """ + Stripe automatically creates and then attempts to collect payment on invoices for customers on subscriptions according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to attempt payment on an invoice out of the normal collection schedule or for some other reason, you can do so. + """ + return cast( + Invoice, + self._requestor.request( + "post", + "/v1/invoices/{invoice}/pay".format( + invoice=_util.sanitize_id(invoice), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def send_invoice( + self, + invoice: str, + params: "InvoiceService.SendInvoiceParams" = {}, + options: RequestOptions = {}, + ) -> Invoice: + """ + Stripe will automatically send invoices to customers according to your [subscriptions settings](https://dashboard.stripe.com/account/billing/automatic). However, if you'd like to manually send an invoice to your customer out of the normal schedule, you can do so. When sending invoices that have already been paid, there will be no reference to the payment in the email. + + Requests made in test-mode result in no emails being sent, despite sending an invoice.sent event. + """ + return cast( + Invoice, + self._requestor.request( + "post", + "/v1/invoices/{invoice}/send".format( + invoice=_util.sanitize_id(invoice), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def void_invoice( + self, + invoice: str, + params: "InvoiceService.VoidInvoiceParams" = {}, + options: RequestOptions = {}, + ) -> Invoice: + """ + Mark a finalized invoice as void. This cannot be undone. Voiding an invoice is similar to [deletion](https://stripe.com/docs/api#delete_invoice), however it only applies to finalized invoices and maintains a papertrail where the invoice can still be found. + """ + return cast( + Invoice, + self._requestor.request( + "post", + "/v1/invoices/{invoice}/void".format( + invoice=_util.sanitize_id(invoice), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_invoice_upcoming_lines_service.py b/stripe/_invoice_upcoming_lines_service.py new file mode 100644 index 000000000..3af980986 --- /dev/null +++ b/stripe/_invoice_upcoming_lines_service.py @@ -0,0 +1,593 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._invoice_line_item import InvoiceLineItem +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class InvoiceUpcomingLinesService(StripeService): + class ListParams(TypedDict): + automatic_tax: NotRequired[ + "InvoiceUpcomingLinesService.ListParamsAutomaticTax" + ] + """ + Settings for automatic tax lookup for this invoice preview. + """ + coupon: NotRequired["str"] + """ + The code of the coupon to apply. If `subscription` or `subscription_items` is provided, the invoice returned will preview updating or creating a subscription with that coupon. Otherwise, it will preview applying that coupon to the customer for the next upcoming invoice from among the customer's subscriptions. The invoice can be previewed without a coupon by passing this value as an empty string. + """ + currency: NotRequired["str"] + """ + The currency to preview this invoice in. Defaults to that of `customer` if not specified. + """ + customer: NotRequired["str"] + """ + The identifier of the customer whose upcoming invoice you'd like to retrieve. If `automatic_tax` is enabled then one of `customer`, `customer_details`, `subscription`, or `schedule` must be set. + """ + customer_details: NotRequired[ + "InvoiceUpcomingLinesService.ListParamsCustomerDetails" + ] + """ + Details about the customer you want to invoice or overrides for an existing customer. If `automatic_tax` is enabled then one of `customer`, `customer_details`, `subscription`, or `schedule` must be set. + """ + discounts: NotRequired[ + "Literal['']|List[InvoiceUpcomingLinesService.ListParamsDiscount]" + ] + """ + The coupons to redeem into discounts for the invoice preview. If not specified, inherits the discount from the customer or subscription. This only works for coupons directly applied to the invoice. To apply a coupon to a subscription, you must use the `coupon` parameter instead. Pass an empty string to avoid inheriting any discounts. To preview the upcoming invoice for a subscription that hasn't been created, use `coupon` instead. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice_items: NotRequired[ + "List[InvoiceUpcomingLinesService.ListParamsInvoiceItem]" + ] + """ + List of invoice items to add or update in the upcoming invoice preview. + """ + issuer: NotRequired["InvoiceUpcomingLinesService.ListParamsIssuer"] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + on_behalf_of: NotRequired["Literal['']|str"] + """ + The account (if any) for which the funds of the invoice payment are intended. If set, the invoice will be presented with the branding and support information of the specified account. See the [Invoices with Connect](https://stripe.com/docs/billing/invoices/connect) documentation for details. + """ + schedule: NotRequired["str"] + """ + The identifier of the schedule whose upcoming invoice you'd like to retrieve. Cannot be used with subscription or subscription fields. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + subscription: NotRequired["str"] + """ + The identifier of the subscription for which you'd like to retrieve the upcoming invoice. If not provided, but a `subscription_items` is provided, you will preview creating a subscription with those items. If neither `subscription` nor `subscription_items` is provided, you will retrieve the next upcoming invoice from among the customer's subscriptions. + """ + subscription_billing_cycle_anchor: NotRequired[ + "Literal['now', 'unchanged']|int" + ] + """ + For new subscriptions, a future timestamp to anchor the subscription's [billing cycle](https://stripe.com/docs/subscriptions/billing-cycle). This is used to determine the date of the first full invoice, and, for plans with `month` or `year` intervals, the day of the month for subsequent invoices. For existing subscriptions, the value can only be set to `now` or `unchanged`. + """ + subscription_cancel_at: NotRequired["Literal['']|int"] + """ + A timestamp at which the subscription should cancel. If set to a date before the current period ends, this will cause a proration if prorations have been enabled using `proration_behavior`. If set during a future period, this will always cause a proration for that period. + """ + subscription_cancel_at_period_end: NotRequired["bool"] + """ + Boolean indicating whether this subscription should cancel at the end of the current period. + """ + subscription_cancel_now: NotRequired["bool"] + """ + This simulates the subscription being canceled or expired immediately. + """ + subscription_default_tax_rates: NotRequired["Literal['']|List[str]"] + """ + If provided, the invoice returned will preview updating or creating a subscription with these default tax rates. The default tax rates will apply to any line item that does not have `tax_rates` set. + """ + subscription_items: NotRequired[ + "List[InvoiceUpcomingLinesService.ListParamsSubscriptionItem]" + ] + """ + A list of up to 20 subscription items, each with an attached price. + """ + subscription_proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + """ + subscription_proration_date: NotRequired["int"] + """ + If previewing an update to a subscription, and doing proration, `subscription_proration_date` forces the proration to be calculated as though the update was done at the specified time. The time given must be within the current subscription period and within the current phase of the schedule backing this subscription, if the schedule exists. If set, `subscription`, and one of `subscription_items`, or `subscription_trial_end` are required. Also, `subscription_proration_behavior` cannot be set to 'none'. + """ + subscription_resume_at: NotRequired["Literal['now']"] + """ + For paused subscriptions, setting `subscription_resume_at` to `now` will preview the invoice that will be generated if the subscription is resumed. + """ + subscription_start_date: NotRequired["int"] + """ + Date a subscription is intended to start (can be future or past). + """ + subscription_trial_end: NotRequired["Literal['now']|int"] + """ + If provided, the invoice returned will preview updating or creating a subscription with that trial end. If set, one of `subscription_items` or `subscription` is required. + """ + subscription_trial_from_plan: NotRequired["bool"] + """ + Indicates if a plan's `trial_period_days` should be applied to the subscription. Setting `subscription_trial_end` per subscription is preferred, and this defaults to `false`. Setting this flag to `true` together with `subscription_trial_end` is not allowed. See [Using trial periods on subscriptions](https://stripe.com/docs/billing/subscriptions/trials) to learn more. + """ + + class ListParamsAutomaticTax(TypedDict): + enabled: bool + """ + Whether Stripe automatically computes tax on this invoice. Note that incompatible invoice items (invoice items with manually specified [tax rates](https://stripe.com/docs/api/tax_rates), negative amounts, or `tax_behavior=unspecified`) cannot be added to automatic tax invoices. + """ + liability: NotRequired[ + "InvoiceUpcomingLinesService.ListParamsAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class ListParamsAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class ListParamsCustomerDetails(TypedDict): + address: NotRequired[ + "Literal['']|InvoiceUpcomingLinesService.ListParamsCustomerDetailsAddress" + ] + """ + The customer's address. + """ + shipping: NotRequired[ + "Literal['']|InvoiceUpcomingLinesService.ListParamsCustomerDetailsShipping" + ] + """ + The customer's shipping information. Appears on invoices emailed to this customer. + """ + tax: NotRequired[ + "InvoiceUpcomingLinesService.ListParamsCustomerDetailsTax" + ] + """ + Tax details about the customer. + """ + tax_exempt: NotRequired[ + "Literal['']|Literal['exempt', 'none', 'reverse']" + ] + """ + The customer's tax exemption. One of `none`, `exempt`, or `reverse`. + """ + tax_ids: NotRequired[ + "List[InvoiceUpcomingLinesService.ListParamsCustomerDetailsTaxId]" + ] + """ + The customer's tax IDs. + """ + + class ListParamsCustomerDetailsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class ListParamsCustomerDetailsShipping(TypedDict): + address: "InvoiceUpcomingLinesService.ListParamsCustomerDetailsShippingAddress" + """ + Customer shipping address. + """ + name: str + """ + Customer name. + """ + phone: NotRequired["str"] + """ + Customer phone (including extension). + """ + + class ListParamsCustomerDetailsShippingAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class ListParamsCustomerDetailsTax(TypedDict): + ip_address: NotRequired["Literal['']|str"] + """ + A recent IP address of the customer used for tax reporting and tax location inference. Stripe recommends updating the IP address when a new PaymentMethod is attached or the address field on the customer is updated. We recommend against updating this field more frequently since it could result in unexpected tax location/reporting outcomes. + """ + + class ListParamsCustomerDetailsTaxId(TypedDict): + type: Literal[ + "ad_nrt", + "ae_trn", + "ar_cuit", + "au_abn", + "au_arn", + "bg_uic", + "bo_tin", + "br_cnpj", + "br_cpf", + "ca_bn", + "ca_gst_hst", + "ca_pst_bc", + "ca_pst_mb", + "ca_pst_sk", + "ca_qst", + "ch_vat", + "cl_tin", + "cn_tin", + "co_nit", + "cr_tin", + "do_rcn", + "ec_ruc", + "eg_tin", + "es_cif", + "eu_oss_vat", + "eu_vat", + "gb_vat", + "ge_vat", + "hk_br", + "hu_tin", + "id_npwp", + "il_vat", + "in_gst", + "is_vat", + "jp_cn", + "jp_rn", + "jp_trn", + "ke_pin", + "kr_brn", + "li_uid", + "mx_rfc", + "my_frp", + "my_itn", + "my_sst", + "no_vat", + "nz_gst", + "pe_ruc", + "ph_tin", + "ro_tin", + "rs_pib", + "ru_inn", + "ru_kpp", + "sa_vat", + "sg_gst", + "sg_uen", + "si_tin", + "sv_nit", + "th_vat", + "tr_tin", + "tw_vat", + "ua_vat", + "us_ein", + "uy_ruc", + "ve_rif", + "vn_tin", + "za_vat", + ] + """ + Type of the tax ID, one of `ad_nrt`, `ae_trn`, `ar_cuit`, `au_abn`, `au_arn`, `bg_uic`, `bo_tin`, `br_cnpj`, `br_cpf`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `ch_vat`, `cl_tin`, `cn_tin`, `co_nit`, `cr_tin`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `hk_br`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kr_brn`, `li_uid`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `no_vat`, `nz_gst`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sv_nit`, `th_vat`, `tr_tin`, `tw_vat`, `ua_vat`, `us_ein`, `uy_ruc`, `ve_rif`, `vn_tin`, or `za_vat` + """ + value: str + """ + Value of the tax ID. + """ + + class ListParamsDiscount(TypedDict): + coupon: NotRequired["str"] + """ + ID of the coupon to create a new discount for. + """ + discount: NotRequired["str"] + """ + ID of an existing discount on the object (or one of its ancestors) to reuse. + """ + promotion_code: NotRequired["str"] + """ + ID of the promotion code to create a new discount for. + """ + + class ListParamsInvoiceItem(TypedDict): + amount: NotRequired["int"] + """ + The integer amount in cents (or local equivalent) of previewed invoice item. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). Only applicable to new invoice items. + """ + description: NotRequired["str"] + """ + An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. + """ + discountable: NotRequired["bool"] + """ + Explicitly controls whether discounts apply to this invoice item. Defaults to true, except for negative invoice items. + """ + discounts: NotRequired[ + "Literal['']|List[InvoiceUpcomingLinesService.ListParamsInvoiceItemDiscount]" + ] + """ + The coupons to redeem into discounts for the invoice item in the preview. + """ + invoiceitem: NotRequired["str"] + """ + The ID of the invoice item to update in preview. If not specified, a new invoice item will be added to the preview of the upcoming invoice. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + period: NotRequired[ + "InvoiceUpcomingLinesService.ListParamsInvoiceItemPeriod" + ] + """ + The period associated with this invoice item. When set to different values, the period will be rendered on the invoice. If you have [Stripe Revenue Recognition](https://stripe.com/docs/revenue-recognition) enabled, the period will be used to recognize and defer revenue. See the [Revenue Recognition documentation](https://stripe.com/docs/revenue-recognition/methodology/subscriptions-and-invoicing) for details. + """ + price: NotRequired["str"] + """ + The ID of the price object. + """ + price_data: NotRequired[ + "InvoiceUpcomingLinesService.ListParamsInvoiceItemPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Non-negative integer. The quantity of units for the invoice item. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + tax_code: NotRequired["Literal['']|str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates that apply to the item. When set, any `default_tax_rates` do not apply to this item. + """ + unit_amount: NotRequired["int"] + """ + The integer unit amount in cents (or local equivalent) of the charge to be applied to the upcoming invoice. This unit_amount will be multiplied by the quantity to get the full amount. If you want to apply a credit to the customer's account, pass a negative unit_amount. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class ListParamsInvoiceItemDiscount(TypedDict): + coupon: NotRequired["str"] + """ + ID of the coupon to create a new discount for. + """ + discount: NotRequired["str"] + """ + ID of an existing discount on the object (or one of its ancestors) to reuse. + """ + promotion_code: NotRequired["str"] + """ + ID of the promotion code to create a new discount for. + """ + + class ListParamsInvoiceItemPeriod(TypedDict): + end: int + """ + The end of the period, which must be greater than or equal to the start. This value is inclusive. + """ + start: int + """ + The start of the period. This value is inclusive. + """ + + class ListParamsInvoiceItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class ListParamsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class ListParamsSubscriptionItem(TypedDict): + billing_thresholds: NotRequired[ + "Literal['']|InvoiceUpcomingLinesService.ListParamsSubscriptionItemBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. + """ + clear_usage: NotRequired["bool"] + """ + Delete all usage for a given subscription item. Allowed only when `deleted` is set to `true` and the current plan's `usage_type` is `metered`. + """ + deleted: NotRequired["bool"] + """ + A flag that, if set to `true`, will delete the specified item. + """ + id: NotRequired["str"] + """ + Subscription item to update. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + plan: NotRequired["str"] + """ + Plan ID for this item, as a string. + """ + price: NotRequired["str"] + """ + The ID of the price object. When changing a subscription item's price, `quantity` is set to 1 unless a `quantity` parameter is provided. + """ + price_data: NotRequired[ + "InvoiceUpcomingLinesService.ListParamsSubscriptionItemPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Quantity for this item. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + """ + + class ListParamsSubscriptionItemBillingThresholds(TypedDict): + usage_gte: int + """ + Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + """ + + class ListParamsSubscriptionItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + recurring: "InvoiceUpcomingLinesService.ListParamsSubscriptionItemPriceDataRecurring" + """ + The recurring components of a price such as `interval` and `interval_count`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class ListParamsSubscriptionItemPriceDataRecurring(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + + def list( + self, + params: "InvoiceUpcomingLinesService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[InvoiceLineItem]: + """ + When retrieving an upcoming invoice, you'll get a lines property containing the total count of line items and the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. + """ + return cast( + ListObject[InvoiceLineItem], + self._requestor.request( + "get", + "/v1/invoices/upcoming/lines", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_issuing_service.py b/stripe/_issuing_service.py new file mode 100644 index 000000000..62f65c00f --- /dev/null +++ b/stripe/_issuing_service.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.issuing._authorization_service import AuthorizationService +from stripe.issuing._card_service import CardService +from stripe.issuing._cardholder_service import CardholderService +from stripe.issuing._dispute_service import DisputeService +from stripe.issuing._token_service import TokenService +from stripe.issuing._transaction_service import TransactionService + + +class IssuingService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.authorizations = AuthorizationService(self._requestor) + self.cards = CardService(self._requestor) + self.cardholders = CardholderService(self._requestor) + self.disputes = DisputeService(self._requestor) + self.tokens = TokenService(self._requestor) + self.transactions = TransactionService(self._requestor) diff --git a/stripe/_list_object.py b/stripe/_list_object.py index 98bc5faf0..fddf71bbc 100644 --- a/stripe/_list_object.py +++ b/stripe/_list_object.py @@ -1,23 +1,24 @@ # pyright: strict, reportUnnecessaryTypeIgnoreComment=false # reportUnnecessaryTypeIgnoreComment is set to false because some type ignores are required in some # python versions but not the others -from typing_extensions import Self +from typing_extensions import Self, Unpack from typing import ( Any, Iterator, List, Generic, - Optional, TypeVar, cast, Mapping, ) -from stripe import _util +from stripe._api_requestor import ( + _APIRequestor, # pyright: ignore[reportPrivateUsage] +) from stripe._stripe_object import StripeObject +from stripe._request_options import RequestOptions, extract_options_from_dict from urllib.parse import quote_plus -import warnings T = TypeVar("T", bound=StripeObject) @@ -28,32 +29,7 @@ class ListObject(StripeObject, Generic[T]): has_more: bool url: str - def _list( - self, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Mapping[str, Any] - ) -> Self: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) - return self.list( # pyright: ignore[reportDeprecated] - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, - **params, - ) - - @_util.deprecated( - "This will be removed in a future version of stripe-python. Please call the `list` method on the corresponding resource directly, instead of using `list` from the list object." - ) - def list( - self, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Mapping[str, Any] - ) -> Self: + def list(self, **params: Mapping[str, Any]) -> Self: url = self.get("url") if not isinstance(url, str): raise ValueError( @@ -64,24 +40,13 @@ def list( self._request( "get", url, - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, + base_address="api", + api_mode="V1", ), ) - @_util.deprecated( - "This will be removed in a future version of stripe-python. Please call the `create` method on the corresponding resource directly, instead of using `create` from the list object." - ) - def create( - self, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Mapping[str, Any] - ) -> T: + def create(self, **params: Mapping[str, Any]) -> T: url = self.get("url") if not isinstance(url, str): raise ValueError( @@ -92,25 +57,13 @@ def create( self._request( "post", url, - api_key=api_key, - idempotency_key=idempotency_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, + base_address="api", + api_mode="V1", ), ) - @_util.deprecated( - "This will be removed in a future version of stripe-python. Please call the `retrieve` method on the corresponding resource directly, instead of using `retrieve` from the list object." - ) - def retrieve( - self, - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Mapping[str, Any] - ): + def retrieve(self, id: str, **params: Mapping[str, Any]): url = self.get("url") if not isinstance(url, str): raise ValueError( @@ -123,10 +76,9 @@ def retrieve( self._request( "get", url, - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, + base_address="api", + api_mode="V1", ), ) @@ -174,53 +126,29 @@ def auto_paging_iter(self) -> Iterator[T]: if page.is_empty: break - @classmethod - @_util.deprecated( - "This method is for internal stripe-python use only. The public interface will be removed in a future version." - ) - def empty_list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - ) -> Self: - return cls._empty_list( - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, - ) - @classmethod def _empty_list( cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, + **params: Unpack[RequestOptions], ) -> Self: - return cls.construct_from( - {"data": []}, - key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, + return cls._construct_from( + values={"data": []}, last_response=None, + requestor=_APIRequestor._global_with_options( # pyright: ignore[reportPrivateUsage] + **params, + ), + api_mode="V1", ) @property def is_empty(self) -> bool: return not self.data - def next_page( - self, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Mapping[str, Any] - ) -> Self: + def next_page(self, **params: Unpack[RequestOptions]) -> Self: if not self.has_more: + request_options, _ = extract_options_from_dict(params) return self._empty_list( - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, + **request_options, ) last_id = getattr(self.data[-1], "id") @@ -229,29 +157,19 @@ def next_page( "Unexpected: element in .data of list object had no id" ) - params_with_filters = self._retrieve_params.copy() + params_with_filters = dict(self._retrieve_params) params_with_filters.update({"starting_after": last_id}) params_with_filters.update(params) - return self._list( - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, + return self.list( **params_with_filters, ) - def previous_page( - self, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Mapping[str, Any] - ) -> Self: + def previous_page(self, **params: Unpack[RequestOptions]) -> Self: if not self.has_more: + request_options, _ = extract_options_from_dict(params) return self._empty_list( - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, + **request_options, ) first_id = getattr(self.data[0], "id") @@ -260,14 +178,11 @@ def previous_page( "Unexpected: element in .data of list object had no id" ) - params_with_filters = self._retrieve_params.copy() + params_with_filters = dict(self._retrieve_params) params_with_filters.update({"ending_before": first_id}) params_with_filters.update(params) - result = self._list( - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, + result = self.list( **params_with_filters, ) return result diff --git a/stripe/_listable_api_resource.py b/stripe/_listable_api_resource.py index 9f27facd7..ea2b4b8bb 100644 --- a/stripe/_listable_api_resource.py +++ b/stripe/_listable_api_resource.py @@ -11,19 +11,14 @@ class ListableAPIResource(APIResource[T]): @classmethod - def auto_paging_iter(cls, *args, **params): - return cls.list(*args, **params).auto_paging_iter() + def auto_paging_iter(cls, **params): + return cls.list(**params).auto_paging_iter() @classmethod - def list( - cls, api_key=None, stripe_version=None, stripe_account=None, **params - ) -> ListObject[T]: + def list(cls, **params) -> ListObject[T]: result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) diff --git a/stripe/_mandate_service.py b/stripe/_mandate_service.py new file mode 100644 index 000000000..d78cf5b88 --- /dev/null +++ b/stripe/_mandate_service.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._mandate import Mandate +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class MandateService(StripeService): + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def retrieve( + self, + mandate: str, + params: "MandateService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Mandate: + """ + Retrieves a Mandate object. + """ + return cast( + Mandate, + self._requestor.request( + "get", + "/v1/mandates/{mandate}".format( + mandate=_util.sanitize_id(mandate), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_nested_resource_class_methods.py b/stripe/_nested_resource_class_methods.py index 54f418a66..5eeea6c4d 100644 --- a/stripe/_nested_resource_class_methods.py +++ b/stripe/_nested_resource_class_methods.py @@ -31,23 +31,10 @@ def nested_resource_url(cls, id, nested_id=None): resource_url_method = "%ss_url" % resource setattr(cls, resource_url_method, classmethod(nested_resource_url)) - def nested_resource_request( - cls, - method, - url, - api_key=None, - idempotency_key=None, - stripe_version=None, - stripe_account=None, - **params - ): + def nested_resource_request(cls, method, url, **params): return APIResource._static_request( method, url, - api_key=api_key, - idempotency_key=idempotency_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) diff --git a/stripe/_oauth.py b/stripe/_oauth.py index 981409795..e0050c7e1 100644 --- a/stripe/_oauth.py +++ b/stripe/_oauth.py @@ -1,12 +1,287 @@ # Used for global variables -import stripe # noqa: IMP101 +from stripe import connect_api_base from stripe._error import AuthenticationError -from stripe._api_requestor import APIRequestor +from stripe._api_requestor import _APIRequestor from stripe._encode import _api_encode from urllib.parse import urlencode +from stripe._request_options import RequestOptions +from stripe._stripe_object import StripeObject + +from typing import List, cast, Optional +from typing_extensions import Literal, NotRequired, TypedDict, Unpack class OAuth(object): + class OAuthToken(StripeObject): + access_token: Optional[str] + """ + The access token you can use to make requests on behalf of this Stripe account. Use it as you would any Stripe secret API key. + This key does not expire, but may be revoked by the user at any time (you'll get a account.application.deauthorized webhook event when this happens). + """ + scope: Optional[str] + """ + The scope granted to the access token, depending on the scope of the authorization code and scope parameter. + """ + livemode: Optional[bool] + """ + The live mode indicator for the token. If true, the access_token can be used as a live secret key. If false, the access_token can be used as a test secret key. + Depends on the mode of the secret API key used to make the request. + """ + token_type: Optional[Literal["bearer"]] + """ + Will always have a value of bearer. + """ + refresh_token: Optional[str] + """ + Can be used to get a new access token of an equal or lesser scope, or of a different live mode (where applicable). + """ + stripe_user_id: Optional[str] + """ + The unique id of the account you have been granted access to, as a string. + """ + stripe_publishable_key: Optional[str] + """ + A publishable key that can be used with this account. Matches the mode—live or test—of the token. + """ + + class OAuthDeauthorization(StripeObject): + stripe_user_id: str + """ + The unique id of the account you have revoked access to, as a string. + This is the same as the stripe_user_id you passed in. + If this is returned, the revocation was successful. + """ + + class OAuthAuthorizeUrlParams(TypedDict): + client_id: NotRequired[str] + """ + The unique identifier provided to your application, found in your application settings. + """ + response_type: NotRequired[Literal["code"]] + """ + The only option at the moment is `'code'`. + """ + redirect_uri: NotRequired[str] + """ + The URL for the authorize response redirect. If provided, this must exactly match one of the comma-separated redirect_uri values in your application settings. + To protect yourself from certain forms of man-in-the-middle attacks, the live mode redirect_uri must use a secure HTTPS connection. + Defaults to the redirect_uri in your application settings if not provided. + """ + scope: NotRequired[str] + """ + read_write or read_only, depending on the level of access you need. + Defaults to read_only. + """ + state: NotRequired[str] + """ + An arbitrary string value we will pass back to you, useful for CSRF protection. + """ + stripe_landing: NotRequired[str] + """ + login or register, depending on what type of screen you want your users to see. Only override this to be login if you expect all your users to have Stripe accounts already (e.g., most read-only applications, like analytics dashboards or accounting software). + Defaults to login for scope read_only and register for scope read_write. + """ + always_prompt: NotRequired[bool] + """ + Boolean to indicate that the user should always be asked to connect, even if they're already connected. + Defaults to false. + """ + suggested_capabilities: NotRequired[List[str]] + """ + Express only + An array of capabilities to apply to the connected account. + """ + stripe_user: NotRequired["OAuth.OAuthAuthorizeUrlParamsStripeUser"] + """ + Stripe will use these to prefill details in the account form for new users. + Some prefilled fields (e.g., URL or product category) may be automatically hidden from the user's view. + Any parameters with invalid values will be silently ignored. + """ + + class OAuthAuthorizeUrlParamsStripeUser(TypedDict): + """ + A more detailed explanation of what it means for a field to be + required or optional can be found in our API documentation. + See `Account Creation (Overview)` and `Account Update` + """ + + email: NotRequired[str] + """ + Recommended + The user's email address. Must be a valid email format. + """ + url: NotRequired[str] + """ + Recommended + The URL for the user's business. This may be the user's website, a profile page within your application, or another publicly available profile for the business, such as a LinkedIn or Facebook profile. + Must be URL-encoded and include a scheme (http or https). + If you will be prefilling this field, we highly recommend that the linked page contain a description of the user's products or services and their contact information. If we don't have enough information, we'll have to reach out to the user directly before initiating payouts. + """ + country: NotRequired[str] + """ + Two-letter country code (e.g., US or CA). + Must be a country that Stripe currently supports. + """ + phone_number: NotRequired[str] + """ + The business phone number. Must be 10 digits only. + Must also prefill stripe_user[country] with the corresponding country. + """ + business_name: NotRequired[str] + """ + The legal name of the business, also used for the statement descriptor. + """ + business_type: NotRequired[str] + """ + The type of the business. + Must be one of sole_prop, corporation, non_profit, partnership, or llc. + """ + first_name: NotRequired[str] + """ + First name of the person who will be filling out a Stripe application. + """ + last_name: NotRequired[str] + """ + Last name of the person who will be filling out a Stripe application. + """ + dob_day: NotRequired[str] + """ + Day (0-31), month (1-12), and year (YYYY, greater than 1900) for the birth date of the person who will be filling out a Stripe application. + If you choose to pass these parameters, you must pass all three. + """ + dob_month: NotRequired[str] + """ + Day (0-31), month (1-12), and year (YYYY, greater than 1900) for the birth date of the person who will be filling out a Stripe application. + If you choose to pass these parameters, you must pass all three. + """ + dob_year: NotRequired[str] + """ + Day (0-31), month (1-12), and year (YYYY, greater than 1900) for the birth date of the person who will be filling out a Stripe application. + If you choose to pass these parameters, you must pass all three. + """ + street_address: NotRequired[str] + """ + Standard only + Street address of the business. + """ + city: NotRequired[str] + """ + Address city of the business. + We highly recommend that you also prefill stripe_user[country] with the corresponding country. + """ + state: NotRequired[str] + """ + Standard only + Address state of the business, must be the two-letter state or province code (e.g., NY for a U.S. business or AB for a Canadian one). + Must also prefill stripe_user[country] with the corresponding country. + """ + zip: NotRequired[str] + """ + Standard only + Address ZIP code of the business, must be a string. + We highly recommend that you also prefill stripe_user[country] with the corresponding country. + """ + physical_product: NotRequired[str] + """ + Standard only + A string: true if the user sells a physical product, false otherwise. + """ + product_description: NotRequired[str] + """ + A description of what the business is accepting payments for. + """ + currency: NotRequired[str] + """ + Standard only + Three-letter ISO code representing currency, in lowercase (e.g., usd or cad). + Must be a valid country and currency combination that Stripe supports. + Must prefill stripe_user[country] with the corresponding country. + """ + first_name_kana: NotRequired[str] + """ + The Kana variation of the first name of the person who will be filling out a Stripe application. + Must prefill stripe_user[country] with JP, as this parameter is only relevant for Japan. + """ + first_name_kanji: NotRequired[str] + """ + The Kanji variation of the first name of the person who will be filling out a Stripe application. + Must prefill stripe_user[country] with JP, as this parameter is only relevant for Japan. + """ + last_name_kana: NotRequired[str] + """ + The Kana variation of the last name of the person who will be filling out a Stripe application. + Must prefill stripe_user[country] with JP, as this parameter is only relevant for Japan. + """ + last_name_kanji: NotRequired[str] + """ + The Kanji variation of the last name of the person who will be filling out a Stripe application. + Must prefill stripe_user[country] with JP, as this parameter is only relevant for Japan. + """ + gender: NotRequired[str] + """ + The gender of the person who will be filling out a Stripe application. (International regulations require either male or female.) + Must prefill stripe_user[country] with JP, as this parameter is only relevant for Japan. + """ + block_kana: NotRequired[str] + """ + Standard only + The Kana variation of the address block. + This parameter is only relevant for Japan. You must prefill stripe_user[country] with JP and stripe_user[zip] with a valid Japanese postal code to use this parameter. + """ + block_kanji: NotRequired[str] + """ + Standard only + The Kanji variation of the address block. + This parameter is only relevant for Japan. You must prefill stripe_user[country] with JP and stripe_user[zip] with a valid Japanese postal code to use this parameter. + """ + building_kana: NotRequired[str] + """ + Standard only + The Kana variation of the address building. + This parameter is only relevant for Japan. You must prefill stripe_user[country] with JP and stripe_user[zip] with a valid Japanese postal code to use this parameter. + """ + building_kanji: NotRequired[str] + """ + Standard only + The Kanji variation of the address building. + This parameter is only relevant for Japan. You must prefill stripe_user[country] with JP and stripe_user[zip] with a valid Japanese postal code to use this parameter. + """ + + class OAuthTokenParams(TypedDict): + grant_type: Literal["authorization_code", "refresh_token"] + """ + `'authorization_code'` when turning an authorization code into an access token, or `'refresh_token'` when using a refresh token to get a new access token. + """ + code: NotRequired[str] + """ + The value of the code or refresh_token, depending on the grant_type. + """ + refresh_token: NotRequired[str] + """ + The value of the code or refresh_token, depending on the grant_type. + """ + scope: NotRequired[str] + """ + When requesting a new access token from a refresh token, any scope that has an equal or lesser scope as the refresh token. Has no effect when requesting an access token from an authorization code. + Defaults to the scope of the refresh token. + """ + assert_capabilities: NotRequired[List[str]] + """ + Express only + Check whether the suggested_capabilities were applied to the connected account. + """ + + class OAuthDeauthorizeParams(TypedDict): + client_id: NotRequired[str] + """ + The client_id of the application that you'd like to disconnect the account from. + The account must be connected to this application. + """ + stripe_user_id: str + """ + The account you'd like to disconnect from. + """ + @staticmethod def _set_client_id(params): if "client_id" in params: @@ -29,7 +304,9 @@ def _set_client_id(params): ) @staticmethod - def authorize_url(express=False, **params): + def authorize_url( + express: bool = False, **params: Unpack[OAuthAuthorizeUrlParams] + ) -> str: if express is False: path = "/oauth/authorize" else: @@ -39,20 +316,42 @@ def authorize_url(express=False, **params): if "response_type" not in params: params["response_type"] = "code" query = urlencode(list(_api_encode(params))) - url = stripe.connect_api_base + path + "?" + query + url = connect_api_base + path + "?" + query return url @staticmethod - def token(api_key=None, **params): - requestor = APIRequestor(api_key, api_base=stripe.connect_api_base) - response, _ = requestor.request("post", "/oauth/token", params, None) - return response.data + def token( + api_key: Optional[str] = None, **params: Unpack[OAuthTokenParams] + ) -> OAuthToken: + options: RequestOptions = {"api_key": api_key} + requestor = _APIRequestor._global_instance() + return cast( + "OAuth.OAuthToken", + requestor.request( + "post", + "/oauth/token", + params=params, + options=options, + base_address="connect", + api_mode="V1", + ), + ) @staticmethod - def deauthorize(api_key=None, **params): - requestor = APIRequestor(api_key, api_base=stripe.connect_api_base) + def deauthorize( + api_key: Optional[str] = None, **params: Unpack[OAuthDeauthorizeParams] + ) -> OAuthDeauthorization: + options: RequestOptions = {"api_key": api_key} + requestor = _APIRequestor._global_instance() OAuth._set_client_id(params) - response, _ = requestor.request( - "post", "/oauth/deauthorize", params, None + return cast( + "OAuth.OAuthDeauthorization", + requestor.request( + "post", + "/oauth/deauthorize", + params=params, + options=options, + base_address="connect", + api_mode="V1", + ), ) - return response.data diff --git a/stripe/_oauth_service.py b/stripe/_oauth_service.py new file mode 100644 index 000000000..480cd6f12 --- /dev/null +++ b/stripe/_oauth_service.py @@ -0,0 +1,101 @@ +from stripe._stripe_service import StripeService +from stripe._error import AuthenticationError +from stripe._encode import _api_encode +from stripe._oauth import OAuth +from urllib.parse import urlencode +from stripe._request_options import RequestOptions +from stripe._client_options import _ClientOptions + +from typing import cast, Optional +from typing_extensions import NotRequired, TypedDict + + +class OAuthService(StripeService): + _options: Optional[_ClientOptions] + + def __init__(self, client, options=None): + super(OAuthService, self).__init__(client) + self._options = options + + class OAuthAuthorizeUrlOptions(TypedDict): + express: NotRequired[bool] + """ + Express only + Boolean to indicate that the user should be sent to the express onboarding flow instead of the standard onboarding flow. + """ + + def _set_client_id(self, params): + if "client_id" in params: + return + + client_id = self._options and self._options.client_id + + if client_id: + params["client_id"] = client_id + return + + raise AuthenticationError( + "No client_id provided. (HINT: set your client_id when configuring " + 'your StripeClient: "stripe.StripeClient(..., client_id=)"). ' + "You can find your client_ids in your Stripe dashboard at " + "https://dashboard.stripe.com/account/applications/settings, " + "after registering your account as a platform. See " + "https://stripe.com/docs/connect/standalone-accounts for details, " + "or email support@stripe.com if you have any questions." + ) + + def authorize_url( + self, + params: OAuth.OAuthAuthorizeUrlParams = {}, + options: OAuthAuthorizeUrlOptions = {}, + ) -> str: + if options.get("express"): + path = "/express/oauth/authorize" + else: + path = "/oauth/authorize" + + self._set_client_id(params) + if "response_type" not in params: + params["response_type"] = "code" + query = urlencode(list(_api_encode(params))) + + # connect_api_base will be always set to stripe.DEFAULT_CONNECT_API_BASE + # if it is not overridden on the client explicitly. + connect_api_base = self._requestor.base_addresses.get("connect") + assert connect_api_base is not None + + url = connect_api_base + path + "?" + query + return url + + def token( + self, params: OAuth.OAuthTokenParams, options: RequestOptions = {} + ) -> OAuth.OAuthToken: + return cast( + OAuth.OAuthToken, + self._requestor.request( + "post", + "/oauth/token", + params=params, + options=options, + base_address="connect", + api_mode="V1", + ), + ) + + def deauthorize( + self, + params: OAuth.OAuthDeauthorizeParams, + options: RequestOptions = {}, + ) -> OAuth.OAuthDeauthorization: + self._set_client_id(params) + return cast( + OAuth.OAuthDeauthorization, + self._requestor.request( + "post", + "/oauth/deauthorize", + params=params, + options=options, + base_address="connect", + api_mode="V1", + ), + ) diff --git a/stripe/_payment_intent.py b/stripe/_payment_intent.py index 0e32560a6..e95d184eb 100644 --- a/stripe/_payment_intent.py +++ b/stripe/_payment_intent.py @@ -7675,12 +7675,7 @@ class VerifyMicrodepositsParams(RequestOptions): def _cls_apply_customer_balance( cls, intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.ApplyCustomerBalanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["PaymentIntent.ApplyCustomerBalanceParams"] ) -> "PaymentIntent": """ Manually reconcile the remaining amount for a customer_balance PaymentIntent. @@ -7692,9 +7687,6 @@ def _cls_apply_customer_balance( "/v1/payment_intents/{intent}/apply_customer_balance".format( intent=_util.sanitize_id(intent) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -7703,12 +7695,7 @@ def _cls_apply_customer_balance( @staticmethod def apply_customer_balance( intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.ApplyCustomerBalanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["PaymentIntent.ApplyCustomerBalanceParams"] ) -> "PaymentIntent": """ Manually reconcile the remaining amount for a customer_balance PaymentIntent. @@ -7717,11 +7704,7 @@ def apply_customer_balance( @overload def apply_customer_balance( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.ApplyCustomerBalanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentIntent.ApplyCustomerBalanceParams"] ) -> "PaymentIntent": """ Manually reconcile the remaining amount for a customer_balance PaymentIntent. @@ -7730,11 +7713,7 @@ def apply_customer_balance( @class_method_variant("_cls_apply_customer_balance") def apply_customer_balance( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.ApplyCustomerBalanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentIntent.ApplyCustomerBalanceParams"] ) -> "PaymentIntent": """ Manually reconcile the remaining amount for a customer_balance PaymentIntent. @@ -7746,21 +7725,13 @@ def apply_customer_balance( # pyright: ignore[reportGeneralTypeIssues] "/v1/payment_intents/{intent}/apply_customer_balance".format( intent=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_cancel( - cls, - intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, intent: str, **params: Unpack["PaymentIntent.CancelParams"] ) -> "PaymentIntent": """ You can cancel a PaymentIntent object when it's in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_action or, [in rare cases](https://stripe.com/docs/payments/intents), processing. @@ -7776,9 +7747,6 @@ def _cls_cancel( "/v1/payment_intents/{intent}/cancel".format( intent=_util.sanitize_id(intent) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -7786,13 +7754,7 @@ def _cls_cancel( @overload @staticmethod def cancel( - intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + intent: str, **params: Unpack["PaymentIntent.CancelParams"] ) -> "PaymentIntent": """ You can cancel a PaymentIntent object when it's in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_action or, [in rare cases](https://stripe.com/docs/payments/intents), processing. @@ -7805,11 +7767,7 @@ def cancel( @overload def cancel( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentIntent.CancelParams"] ) -> "PaymentIntent": """ You can cancel a PaymentIntent object when it's in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_action or, [in rare cases](https://stripe.com/docs/payments/intents), processing. @@ -7822,11 +7780,7 @@ def cancel( @class_method_variant("_cls_cancel") def cancel( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentIntent.CancelParams"] ) -> "PaymentIntent": """ You can cancel a PaymentIntent object when it's in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_action or, [in rare cases](https://stripe.com/docs/payments/intents), processing. @@ -7842,21 +7796,13 @@ def cancel( # pyright: ignore[reportGeneralTypeIssues] "/v1/payment_intents/{intent}/cancel".format( intent=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_capture( - cls, - intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.CaptureParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, intent: str, **params: Unpack["PaymentIntent.CaptureParams"] ) -> "PaymentIntent": """ Capture the funds of an existing uncaptured PaymentIntent when its status is requires_capture. @@ -7872,9 +7818,6 @@ def _cls_capture( "/v1/payment_intents/{intent}/capture".format( intent=_util.sanitize_id(intent) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -7882,13 +7825,7 @@ def _cls_capture( @overload @staticmethod def capture( - intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.CaptureParams" - ] # pyright: ignore[reportGeneralTypeIssues] + intent: str, **params: Unpack["PaymentIntent.CaptureParams"] ) -> "PaymentIntent": """ Capture the funds of an existing uncaptured PaymentIntent when its status is requires_capture. @@ -7901,11 +7838,7 @@ def capture( @overload def capture( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.CaptureParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentIntent.CaptureParams"] ) -> "PaymentIntent": """ Capture the funds of an existing uncaptured PaymentIntent when its status is requires_capture. @@ -7918,11 +7851,7 @@ def capture( @class_method_variant("_cls_capture") def capture( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.CaptureParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentIntent.CaptureParams"] ) -> "PaymentIntent": """ Capture the funds of an existing uncaptured PaymentIntent when its status is requires_capture. @@ -7938,21 +7867,13 @@ def capture( # pyright: ignore[reportGeneralTypeIssues] "/v1/payment_intents/{intent}/capture".format( intent=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_confirm( - cls, - intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.ConfirmParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, intent: str, **params: Unpack["PaymentIntent.ConfirmParams"] ) -> "PaymentIntent": """ Confirm that your customer intends to pay with current or provided @@ -7986,9 +7907,6 @@ def _cls_confirm( "/v1/payment_intents/{intent}/confirm".format( intent=_util.sanitize_id(intent) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -7996,13 +7914,7 @@ def _cls_confirm( @overload @staticmethod def confirm( - intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.ConfirmParams" - ] # pyright: ignore[reportGeneralTypeIssues] + intent: str, **params: Unpack["PaymentIntent.ConfirmParams"] ) -> "PaymentIntent": """ Confirm that your customer intends to pay with current or provided @@ -8033,11 +7945,7 @@ def confirm( @overload def confirm( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.ConfirmParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentIntent.ConfirmParams"] ) -> "PaymentIntent": """ Confirm that your customer intends to pay with current or provided @@ -8068,11 +7976,7 @@ def confirm( @class_method_variant("_cls_confirm") def confirm( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.ConfirmParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentIntent.ConfirmParams"] ) -> "PaymentIntent": """ Confirm that your customer intends to pay with current or provided @@ -8106,21 +8010,13 @@ def confirm( # pyright: ignore[reportGeneralTypeIssues] "/v1/payment_intents/{intent}/confirm".format( intent=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["PaymentIntent.CreateParams"] ) -> "PaymentIntent": """ Creates a PaymentIntent object. @@ -8139,10 +8035,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -8151,12 +8043,7 @@ def create( def _cls_increment_authorization( cls, intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.IncrementAuthorizationParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["PaymentIntent.IncrementAuthorizationParams"] ) -> "PaymentIntent": """ Perform an incremental authorization on an eligible @@ -8191,9 +8078,6 @@ def _cls_increment_authorization( "/v1/payment_intents/{intent}/increment_authorization".format( intent=_util.sanitize_id(intent) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -8202,12 +8086,7 @@ def _cls_increment_authorization( @staticmethod def increment_authorization( intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.IncrementAuthorizationParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["PaymentIntent.IncrementAuthorizationParams"] ) -> "PaymentIntent": """ Perform an incremental authorization on an eligible @@ -8239,11 +8118,7 @@ def increment_authorization( @overload def increment_authorization( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.IncrementAuthorizationParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentIntent.IncrementAuthorizationParams"] ) -> "PaymentIntent": """ Perform an incremental authorization on an eligible @@ -8275,11 +8150,7 @@ def increment_authorization( @class_method_variant("_cls_increment_authorization") def increment_authorization( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.IncrementAuthorizationParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentIntent.IncrementAuthorizationParams"] ) -> "PaymentIntent": """ Perform an incremental authorization on an eligible @@ -8314,20 +8185,13 @@ def increment_authorization( # pyright: ignore[reportGeneralTypeIssues] "/v1/payment_intents/{intent}/increment_authorization".format( intent=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["PaymentIntent.ListParams"] ) -> ListObject["PaymentIntent"]: """ Returns a list of PaymentIntents. @@ -8335,9 +8199,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -8387,12 +8248,7 @@ def retrieve( def _cls_verify_microdeposits( cls, intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.VerifyMicrodepositsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["PaymentIntent.VerifyMicrodepositsParams"] ) -> "PaymentIntent": """ Verifies microdeposits on a PaymentIntent object. @@ -8404,9 +8260,6 @@ def _cls_verify_microdeposits( "/v1/payment_intents/{intent}/verify_microdeposits".format( intent=_util.sanitize_id(intent) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -8415,12 +8268,7 @@ def _cls_verify_microdeposits( @staticmethod def verify_microdeposits( intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.VerifyMicrodepositsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["PaymentIntent.VerifyMicrodepositsParams"] ) -> "PaymentIntent": """ Verifies microdeposits on a PaymentIntent object. @@ -8429,11 +8277,7 @@ def verify_microdeposits( @overload def verify_microdeposits( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.VerifyMicrodepositsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentIntent.VerifyMicrodepositsParams"] ) -> "PaymentIntent": """ Verifies microdeposits on a PaymentIntent object. @@ -8442,11 +8286,7 @@ def verify_microdeposits( @class_method_variant("_cls_verify_microdeposits") def verify_microdeposits( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentIntent.VerifyMicrodepositsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentIntent.VerifyMicrodepositsParams"] ) -> "PaymentIntent": """ Verifies microdeposits on a PaymentIntent object. @@ -8458,7 +8298,6 @@ def verify_microdeposits( # pyright: ignore[reportGeneralTypeIssues] "/v1/payment_intents/{intent}/verify_microdeposits".format( intent=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/_payment_intent_service.py b/stripe/_payment_intent_service.py new file mode 100644 index 000000000..89b833cea --- /dev/null +++ b/stripe/_payment_intent_service.py @@ -0,0 +1,6103 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._payment_intent import PaymentIntent +from stripe._request_options import RequestOptions +from stripe._search_result_object import SearchResultObject +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class PaymentIntentService(StripeService): + class ApplyCustomerBalanceParams(TypedDict): + amount: NotRequired["int"] + """ + Amount that you intend to apply to this PaymentIntent from the customer's cash balance. + + A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (for example, 100 cents to charge 1 USD or 100 to charge 100 JPY, a zero-decimal currency). + + The maximum amount is the amount of the PaymentIntent. + + When you omit the amount, it defaults to the remaining amount requested on the PaymentIntent. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CancelParams(TypedDict): + cancellation_reason: NotRequired[ + "Literal['abandoned', 'duplicate', 'fraudulent', 'requested_by_customer']" + ] + """ + Reason for canceling this PaymentIntent. Possible values are: `duplicate`, `fraudulent`, `requested_by_customer`, or `abandoned` + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CaptureParams(TypedDict): + amount_to_capture: NotRequired["int"] + """ + The amount to capture from the PaymentIntent, which must be less than or equal to the original amount. Any additional amount is automatically refunded. Defaults to the full `amount_capturable` if it's not provided. + """ + application_fee_amount: NotRequired["int"] + """ + The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. The amount of the application fee collected will be capped at the total payment amount. For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + final_capture: NotRequired["bool"] + """ + Defaults to `true`. When capturing a PaymentIntent, setting `final_capture` to `false` notifies Stripe to not release the remaining uncaptured funds to make sure that they're captured in future requests. You can only use this setting when [multicapture](https://stripe.com/docs/payments/multicapture) is available for PaymentIntents. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + statement_descriptor: NotRequired["str"] + """ + For card charges, use [statement_descriptor_suffix](https://stripe.com/docs/payments/account/statement-descriptors#dynamic). Otherwise, you can use this value as the complete description of a charge on your customers' statements. It must contain at least one letter and be 1–22 characters long. + """ + statement_descriptor_suffix: NotRequired["str"] + """ + Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that's set on the account to form the complete statement descriptor. The concatenated descriptor must be 1-22 characters long. + """ + transfer_data: NotRequired[ + "PaymentIntentService.CaptureParamsTransferData" + ] + """ + The parameters that you can use to automatically create a transfer after the payment + is captured. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + """ + + class CaptureParamsTransferData(TypedDict): + amount: NotRequired["int"] + """ + The amount that will be transferred automatically when a charge succeeds. + """ + + class ConfirmParams(TypedDict): + capture_method: NotRequired[ + "Literal['automatic', 'automatic_async', 'manual']" + ] + """ + Controls when the funds will be captured from the customer's account. + """ + error_on_requires_action: NotRequired["bool"] + """ + Set to `true` to fail the payment attempt if the PaymentIntent transitions into `requires_action`. This parameter is intended for simpler integrations that do not handle customer actions, like [saving cards without authentication](https://stripe.com/docs/payments/save-card-without-authentication). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + mandate: NotRequired["str"] + """ + ID of the mandate that's used for this payment. + """ + mandate_data: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsMandateData" + ] + off_session: NotRequired["bool|Literal['one_off', 'recurring']"] + """ + Set to `true` to indicate that the customer isn't in your checkout flow during this payment attempt and can't authenticate. Use this parameter in scenarios where you collect card details and [charge them later](https://stripe.com/docs/payments/cards/charging-saved-cards). + """ + payment_method: NotRequired["str"] + """ + ID of the payment method (a PaymentMethod, Card, or [compatible Source](https://stripe.com/docs/payments/payment-methods/transitioning#compatibility) object) to attach to this PaymentIntent. + """ + payment_method_data: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodData" + ] + """ + If provided, this hash will be used to create a PaymentMethod. The new PaymentMethod will appear + in the [payment_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-payment_method) + property on the PaymentIntent. + """ + payment_method_options: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodOptions" + ] + """ + Payment method-specific configuration for this PaymentIntent. + """ + radar_options: NotRequired[ + "PaymentIntentService.ConfirmParamsRadarOptions" + ] + """ + Options to configure Radar. Learn more about [Radar Sessions](https://stripe.com/docs/radar/radar-session). + """ + receipt_email: NotRequired["Literal['']|str"] + """ + Email address that the receipt for the resulting payment will be sent to. If `receipt_email` is specified for a payment in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + """ + return_url: NotRequired["str"] + """ + The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method's app or site. + If you'd prefer to redirect to a mobile application, you can alternatively supply an application URI scheme. + This parameter is only used for cards and other redirect-based payment methods. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + shipping: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsShipping" + ] + """ + Shipping information for this PaymentIntent. + """ + use_stripe_sdk: NotRequired["bool"] + """ + Set to `true` when confirming server-side and using Stripe.js, iOS, or Android client-side SDKs to handle the next actions. + """ + + class ConfirmParamsMandateData(TypedDict): + customer_acceptance: NotRequired[ + "PaymentIntentService.ConfirmParamsMandateDataCustomerAcceptance" + ] + """ + This hash contains details about the customer acceptance of the Mandate. + """ + + class ConfirmParamsMandateDataCustomerAcceptance(TypedDict): + accepted_at: NotRequired["int"] + """ + The time at which the customer accepted the Mandate. + """ + offline: NotRequired[ + "PaymentIntentService.ConfirmParamsMandateDataCustomerAcceptanceOffline" + ] + """ + If this is a Mandate accepted offline, this hash contains details about the offline acceptance. + """ + online: NotRequired[ + "PaymentIntentService.ConfirmParamsMandateDataCustomerAcceptanceOnline" + ] + """ + If this is a Mandate accepted online, this hash contains details about the online acceptance. + """ + type: Literal["offline", "online"] + """ + The type of customer acceptance information included with the Mandate. One of `online` or `offline`. + """ + + class ConfirmParamsMandateDataCustomerAcceptanceOffline(TypedDict): + pass + + class ConfirmParamsMandateDataCustomerAcceptanceOnline(TypedDict): + ip_address: NotRequired["str"] + """ + The IP address from which the Mandate was accepted by the customer. + """ + user_agent: NotRequired["str"] + """ + The user agent of the browser from which the Mandate was accepted by the customer. + """ + + class ConfirmParamsPaymentMethodData(TypedDict): + acss_debit: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataAcssDebit" + ] + """ + If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + """ + affirm: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataAffirm" + ] + """ + If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + """ + afterpay_clearpay: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataAfterpayClearpay" + ] + """ + If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + """ + alipay: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataAlipay" + ] + """ + If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + """ + au_becs_debit: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataAuBecsDebit" + ] + """ + If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + """ + bacs_debit: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataBacsDebit" + ] + """ + If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + """ + bancontact: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataBancontact" + ] + """ + If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + """ + billing_details: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataBillingDetails" + ] + """ + Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + """ + blik: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataBlik" + ] + """ + If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + """ + boleto: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataBoleto" + ] + """ + If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + """ + cashapp: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataCashapp" + ] + """ + If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + """ + customer_balance: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataCustomerBalance" + ] + """ + If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + """ + eps: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataEps" + ] + """ + If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + """ + fpx: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataFpx" + ] + """ + If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + """ + giropay: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataGiropay" + ] + """ + If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + """ + grabpay: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataGrabpay" + ] + """ + If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + """ + ideal: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataIdeal" + ] + """ + If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + """ + interac_present: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataInteracPresent" + ] + """ + If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + """ + klarna: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataKlarna" + ] + """ + If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + """ + konbini: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataKonbini" + ] + """ + If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + """ + link: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataLink" + ] + """ + If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + oxxo: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataOxxo" + ] + """ + If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + """ + p24: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataP24" + ] + """ + If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + """ + paynow: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataPaynow" + ] + """ + If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + """ + paypal: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataPaypal" + ] + """ + If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + """ + pix: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataPix" + ] + """ + If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + """ + promptpay: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataPromptpay" + ] + """ + If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + """ + radar_options: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataRadarOptions" + ] + """ + Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + """ + revolut_pay: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataRevolutPay" + ] + """ + If this is a `Revolut Pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + """ + sepa_debit: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataSepaDebit" + ] + """ + If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + """ + sofort: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataSofort" + ] + """ + If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + """ + type: Literal[ + "acss_debit", + "affirm", + "afterpay_clearpay", + "alipay", + "au_becs_debit", + "bacs_debit", + "bancontact", + "blik", + "boleto", + "cashapp", + "customer_balance", + "eps", + "fpx", + "giropay", + "grabpay", + "ideal", + "klarna", + "konbini", + "link", + "oxxo", + "p24", + "paynow", + "paypal", + "pix", + "promptpay", + "revolut_pay", + "sepa_debit", + "sofort", + "us_bank_account", + "wechat_pay", + "zip", + ] + """ + The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + """ + us_bank_account: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataUsBankAccount" + ] + """ + If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + """ + wechat_pay: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataWechatPay" + ] + """ + If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + """ + zip: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataZip" + ] + """ + If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + """ + + class ConfirmParamsPaymentMethodDataAcssDebit(TypedDict): + account_number: str + """ + Customer's bank account number. + """ + institution_number: str + """ + Institution number of the customer's bank. + """ + transit_number: str + """ + Transit number of the customer's bank. + """ + + class ConfirmParamsPaymentMethodDataAffirm(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataAfterpayClearpay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataAlipay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataAuBecsDebit(TypedDict): + account_number: str + """ + The account number for the bank account. + """ + bsb_number: str + """ + Bank-State-Branch number of the bank account. + """ + + class ConfirmParamsPaymentMethodDataBacsDebit(TypedDict): + account_number: NotRequired["str"] + """ + Account number of the bank account that the funds will be debited from. + """ + sort_code: NotRequired["str"] + """ + Sort code of the bank account. (e.g., `10-20-30`) + """ + + class ConfirmParamsPaymentMethodDataBancontact(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataBillingDetails(TypedDict): + address: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodDataBillingDetailsAddress" + ] + """ + Billing address. + """ + email: NotRequired["Literal['']|str"] + """ + Email address. + """ + name: NotRequired["Literal['']|str"] + """ + Full name. + """ + phone: NotRequired["Literal['']|str"] + """ + Billing phone number (including extension). + """ + + class ConfirmParamsPaymentMethodDataBillingDetailsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class ConfirmParamsPaymentMethodDataBlik(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataBoleto(TypedDict): + tax_id: str + """ + The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + """ + + class ConfirmParamsPaymentMethodDataCashapp(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataCustomerBalance(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataEps(TypedDict): + bank: NotRequired[ + "Literal['arzte_und_apotheker_bank', 'austrian_anadi_bank_ag', 'bank_austria', 'bankhaus_carl_spangler', 'bankhaus_schelhammer_und_schattera_ag', 'bawag_psk_ag', 'bks_bank_ag', 'brull_kallmus_bank_ag', 'btv_vier_lander_bank', 'capital_bank_grawe_gruppe_ag', 'deutsche_bank_ag', 'dolomitenbank', 'easybank_ag', 'erste_bank_und_sparkassen', 'hypo_alpeadriabank_international_ag', 'hypo_bank_burgenland_aktiengesellschaft', 'hypo_noe_lb_fur_niederosterreich_u_wien', 'hypo_oberosterreich_salzburg_steiermark', 'hypo_tirol_bank_ag', 'hypo_vorarlberg_bank_ag', 'marchfelder_bank', 'oberbank_ag', 'raiffeisen_bankengruppe_osterreich', 'schoellerbank_ag', 'sparda_bank_wien', 'volksbank_gruppe', 'volkskreditbank_ag', 'vr_bank_braunau']" + ] + """ + The customer's bank. + """ + + class ConfirmParamsPaymentMethodDataFpx(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type for FPX transaction + """ + bank: Literal[ + "affin_bank", + "agrobank", + "alliance_bank", + "ambank", + "bank_islam", + "bank_muamalat", + "bank_of_china", + "bank_rakyat", + "bsn", + "cimb", + "deutsche_bank", + "hong_leong_bank", + "hsbc", + "kfh", + "maybank2e", + "maybank2u", + "ocbc", + "pb_enterprise", + "public_bank", + "rhb", + "standard_chartered", + "uob", + ] + """ + The customer's bank. + """ + + class ConfirmParamsPaymentMethodDataGiropay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataGrabpay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataIdeal(TypedDict): + bank: NotRequired[ + "Literal['abn_amro', 'asn_bank', 'bunq', 'handelsbanken', 'ing', 'knab', 'moneyou', 'n26', 'nn', 'rabobank', 'regiobank', 'revolut', 'sns_bank', 'triodos_bank', 'van_lanschot', 'yoursafe']" + ] + """ + The customer's bank. + """ + + class ConfirmParamsPaymentMethodDataInteracPresent(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataKlarna(TypedDict): + dob: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodDataKlarnaDob" + ] + """ + Customer's date of birth + """ + + class ConfirmParamsPaymentMethodDataKlarnaDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class ConfirmParamsPaymentMethodDataKonbini(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataLink(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataOxxo(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataP24(TypedDict): + bank: NotRequired[ + "Literal['alior_bank', 'bank_millennium', 'bank_nowy_bfg_sa', 'bank_pekao_sa', 'banki_spbdzielcze', 'blik', 'bnp_paribas', 'boz', 'citi_handlowy', 'credit_agricole', 'envelobank', 'etransfer_pocztowy24', 'getin_bank', 'ideabank', 'ing', 'inteligo', 'mbank_mtransfer', 'nest_przelew', 'noble_pay', 'pbac_z_ipko', 'plus_bank', 'santander_przelew24', 'tmobile_usbugi_bankowe', 'toyota_bank', 'volkswagen_bank']" + ] + """ + The customer's bank. + """ + + class ConfirmParamsPaymentMethodDataPaynow(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataPaypal(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataPix(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataPromptpay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataRadarOptions(TypedDict): + session: NotRequired["str"] + """ + A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + """ + + class ConfirmParamsPaymentMethodDataRevolutPay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataSepaDebit(TypedDict): + iban: str + """ + IBAN of the bank account. + """ + + class ConfirmParamsPaymentMethodDataSofort(TypedDict): + country: Literal["AT", "BE", "DE", "ES", "IT", "NL"] + """ + Two-letter ISO code representing the country the bank account is located in. + """ + + class ConfirmParamsPaymentMethodDataUsBankAccount(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type: individual or company. + """ + account_number: NotRequired["str"] + """ + Account number of the bank account. + """ + account_type: NotRequired["Literal['checking', 'savings']"] + """ + Account type: checkings or savings. Defaults to checking if omitted. + """ + financial_connections_account: NotRequired["str"] + """ + The ID of a Financial Connections Account to use as a payment method. + """ + routing_number: NotRequired["str"] + """ + Routing number of the bank account. + """ + + class ConfirmParamsPaymentMethodDataWechatPay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataZip(TypedDict): + pass + + class ConfirmParamsPaymentMethodOptions(TypedDict): + acss_debit: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsAcssDebit" + ] + """ + If this is a `acss_debit` PaymentMethod, this sub-hash contains details about the ACSS Debit payment method options. + """ + affirm: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsAffirm" + ] + """ + If this is an `affirm` PaymentMethod, this sub-hash contains details about the Affirm payment method options. + """ + afterpay_clearpay: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsAfterpayClearpay" + ] + """ + If this is a `afterpay_clearpay` PaymentMethod, this sub-hash contains details about the Afterpay Clearpay payment method options. + """ + alipay: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsAlipay" + ] + """ + If this is a `alipay` PaymentMethod, this sub-hash contains details about the Alipay payment method options. + """ + au_becs_debit: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsAuBecsDebit" + ] + """ + If this is a `au_becs_debit` PaymentMethod, this sub-hash contains details about the AU BECS Direct Debit payment method options. + """ + bacs_debit: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsBacsDebit" + ] + """ + If this is a `bacs_debit` PaymentMethod, this sub-hash contains details about the BACS Debit payment method options. + """ + bancontact: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsBancontact" + ] + """ + If this is a `bancontact` PaymentMethod, this sub-hash contains details about the Bancontact payment method options. + """ + blik: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsBlik" + ] + """ + If this is a `blik` PaymentMethod, this sub-hash contains details about the BLIK payment method options. + """ + boleto: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsBoleto" + ] + """ + If this is a `boleto` PaymentMethod, this sub-hash contains details about the Boleto payment method options. + """ + card: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsCard" + ] + """ + Configuration for any card payments attempted on this PaymentIntent. + """ + card_present: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsCardPresent" + ] + """ + If this is a `card_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. + """ + cashapp: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsCashapp" + ] + """ + If this is a `cashapp` PaymentMethod, this sub-hash contains details about the Cash App Pay payment method options. + """ + customer_balance: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsCustomerBalance" + ] + """ + If this is a `customer balance` PaymentMethod, this sub-hash contains details about the customer balance payment method options. + """ + eps: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsEps" + ] + """ + If this is a `eps` PaymentMethod, this sub-hash contains details about the EPS payment method options. + """ + fpx: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsFpx" + ] + """ + If this is a `fpx` PaymentMethod, this sub-hash contains details about the FPX payment method options. + """ + giropay: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsGiropay" + ] + """ + If this is a `giropay` PaymentMethod, this sub-hash contains details about the Giropay payment method options. + """ + grabpay: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsGrabpay" + ] + """ + If this is a `grabpay` PaymentMethod, this sub-hash contains details about the Grabpay payment method options. + """ + ideal: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsIdeal" + ] + """ + If this is a `ideal` PaymentMethod, this sub-hash contains details about the Ideal payment method options. + """ + interac_present: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsInteracPresent" + ] + """ + If this is a `interac_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. + """ + klarna: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsKlarna" + ] + """ + If this is a `klarna` PaymentMethod, this sub-hash contains details about the Klarna payment method options. + """ + konbini: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsKonbini" + ] + """ + If this is a `konbini` PaymentMethod, this sub-hash contains details about the Konbini payment method options. + """ + link: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsLink" + ] + """ + If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. + """ + oxxo: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsOxxo" + ] + """ + If this is a `oxxo` PaymentMethod, this sub-hash contains details about the OXXO payment method options. + """ + p24: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsP24" + ] + """ + If this is a `p24` PaymentMethod, this sub-hash contains details about the Przelewy24 payment method options. + """ + paynow: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsPaynow" + ] + """ + If this is a `paynow` PaymentMethod, this sub-hash contains details about the PayNow payment method options. + """ + paypal: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsPaypal" + ] + """ + If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. + """ + pix: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsPix" + ] + """ + If this is a `pix` PaymentMethod, this sub-hash contains details about the Pix payment method options. + """ + promptpay: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsPromptpay" + ] + """ + If this is a `promptpay` PaymentMethod, this sub-hash contains details about the PromptPay payment method options. + """ + revolut_pay: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsRevolutPay" + ] + """ + If this is a `revolut_pay` PaymentMethod, this sub-hash contains details about the Revolut Pay payment method options. + """ + sepa_debit: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsSepaDebit" + ] + """ + If this is a `sepa_debit` PaymentIntent, this sub-hash contains details about the SEPA Debit payment method options. + """ + sofort: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsSofort" + ] + """ + If this is a `sofort` PaymentMethod, this sub-hash contains details about the SOFORT payment method options. + """ + us_bank_account: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsUsBankAccount" + ] + """ + If this is a `us_bank_account` PaymentMethod, this sub-hash contains details about the US bank account payment method options. + """ + wechat_pay: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsWechatPay" + ] + """ + If this is a `wechat_pay` PaymentMethod, this sub-hash contains details about the WeChat Pay payment method options. + """ + zip: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsZip" + ] + """ + If this is a `zip` PaymentMethod, this sub-hash contains details about the Zip payment method options. + """ + + class ConfirmParamsPaymentMethodOptionsAcssDebit(TypedDict): + mandate_options: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodOptionsAcssDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Bank account verification method. + """ + + class ConfirmParamsPaymentMethodOptionsAcssDebitMandateOptions(TypedDict): + custom_mandate_url: NotRequired["Literal['']|str"] + """ + A URL for custom mandate text to render during confirmation step. + The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + """ + interval_description: NotRequired["str"] + """ + Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + """ + payment_schedule: NotRequired[ + "Literal['combined', 'interval', 'sporadic']" + ] + """ + Payment schedule for the mandate. + """ + transaction_type: NotRequired["Literal['business', 'personal']"] + """ + Transaction type of the mandate. + """ + + class ConfirmParamsPaymentMethodOptionsAffirm(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + preferred_locale: NotRequired["str"] + """ + Preferred language of the Affirm authorization page that the customer is redirected to. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsAfterpayClearpay(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + reference: NotRequired["str"] + """ + An internal identifier or reference that this payment corresponds to. You must limit the identifier to 128 characters, and it can only contain letters, numbers, underscores, backslashes, and dashes. + This field differs from the statement descriptor and item name. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsAlipay(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsAuBecsDebit(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsBacsDebit(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsBancontact(TypedDict): + preferred_language: NotRequired["Literal['de', 'en', 'fr', 'nl']"] + """ + Preferred language of the Bancontact authorization page that the customer is redirected to. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsBlik(TypedDict): + code: NotRequired["str"] + """ + The 6-digit BLIK code that a customer has generated using their banking application. Can only be set on confirmation. + """ + + class ConfirmParamsPaymentMethodOptionsBoleto(TypedDict): + expires_after_days: NotRequired["int"] + """ + The number of calendar days before a Boleto voucher expires. For example, if you create a Boleto voucher on Monday and you set expires_after_days to 2, the Boleto invoice will expire on Wednesday at 23:59 America/Sao_Paulo time. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsCard(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + cvc_token: NotRequired["str"] + """ + A single-use `cvc_update` Token that represents a card CVC value. When provided, the CVC value will be verified during the card payment attempt. This parameter can only be provided during confirmation. + """ + installments: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodOptionsCardInstallments" + ] + """ + Installment configuration for payments attempted on this PaymentIntent (Mexico Only). + + For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + """ + mandate_options: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodOptionsCardMandateOptions" + ] + """ + Configuration options for setting up an eMandate for cards issued in India. + """ + moto: NotRequired["bool"] + """ + When specified, this parameter indicates that a transaction will be marked + as MOTO (Mail Order Telephone Order) and thus out of scope for SCA. This + parameter can only be provided during confirmation. + """ + network: NotRequired[ + "Literal['amex', 'cartes_bancaires', 'diners', 'discover', 'eftpos_au', 'interac', 'jcb', 'mastercard', 'unionpay', 'unknown', 'visa']" + ] + """ + Selected network to process this PaymentIntent on. Depends on the available networks of the card attached to the PaymentIntent. Can be only set confirm-time. + """ + request_extended_authorization: NotRequired[ + "Literal['if_available', 'never']" + ] + """ + Request ability to [capture beyond the standard authorization validity window](https://stripe.com/docs/payments/extended-authorization) for this PaymentIntent. + """ + request_incremental_authorization: NotRequired[ + "Literal['if_available', 'never']" + ] + """ + Request ability to [increment the authorization](https://stripe.com/docs/payments/incremental-authorization) for this PaymentIntent. + """ + request_multicapture: NotRequired["Literal['if_available', 'never']"] + """ + Request ability to make [multiple captures](https://stripe.com/docs/payments/multicapture) for this PaymentIntent. + """ + request_overcapture: NotRequired["Literal['if_available', 'never']"] + """ + Request ability to [overcapture](https://stripe.com/docs/payments/overcapture) for this PaymentIntent. + """ + request_three_d_secure: NotRequired[ + "Literal['any', 'automatic', 'challenge']" + ] + """ + We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + statement_descriptor_suffix_kana: NotRequired["Literal['']|str"] + """ + Provides information about a card payment that customers see on their statements. Concatenated with the Kana prefix (shortened Kana descriptor) or Kana statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 22 characters. + """ + statement_descriptor_suffix_kanji: NotRequired["Literal['']|str"] + """ + Provides information about a card payment that customers see on their statements. Concatenated with the Kanji prefix (shortened Kanji descriptor) or Kanji statement descriptor that's set on the account to form the complete statement descriptor. Maximum 17 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 17 characters. + """ + three_d_secure: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodOptionsCardThreeDSecure" + ] + """ + If 3D Secure authentication was performed with a third-party provider, + the authentication details to use for this payment. + """ + + class ConfirmParamsPaymentMethodOptionsCardInstallments(TypedDict): + enabled: NotRequired["bool"] + """ + Setting to true enables installments for this PaymentIntent. + This will cause the response to contain a list of available installment plans. + Setting to false will prevent any selected plan from applying to a charge. + """ + plan: NotRequired[ + "Literal['']|PaymentIntentService.ConfirmParamsPaymentMethodOptionsCardInstallmentsPlan" + ] + """ + The selected installment plan to use for this payment attempt. + This parameter can only be provided during confirmation. + """ + + class ConfirmParamsPaymentMethodOptionsCardInstallmentsPlan(TypedDict): + count: int + """ + For `fixed_count` installment plans, this is the number of installment payments your customer will make to their credit card. + """ + interval: Literal["month"] + """ + For `fixed_count` installment plans, this is the interval between installment payments your customer will make to their credit card. + One of `month`. + """ + type: Literal["fixed_count"] + """ + Type of installment plan, one of `fixed_count`. + """ + + class ConfirmParamsPaymentMethodOptionsCardMandateOptions(TypedDict): + amount: int + """ + Amount to be charged for future payments. + """ + amount_type: Literal["fixed", "maximum"] + """ + One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + """ + description: NotRequired["str"] + """ + A description of the mandate or subscription that is meant to be displayed to the customer. + """ + end_date: NotRequired["int"] + """ + End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + """ + interval: Literal["day", "month", "sporadic", "week", "year"] + """ + Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + """ + reference: str + """ + Unique identifier for the mandate or subscription. + """ + start_date: int + """ + Start date of the mandate or subscription. Start date should not be lesser than yesterday. + """ + supported_types: NotRequired["List[Literal['india']]"] + """ + Specifies the type of mandates supported. Possible values are `india`. + """ + + class ConfirmParamsPaymentMethodOptionsCardPresent(TypedDict): + request_extended_authorization: NotRequired["bool"] + """ + Request ability to capture this payment beyond the standard [authorization validity window](https://stripe.com/docs/terminal/features/extended-authorizations#authorization-validity) + """ + request_incremental_authorization_support: NotRequired["bool"] + """ + Request ability to [increment](https://stripe.com/docs/terminal/features/incremental-authorizations) this PaymentIntent if the combination of MCC and card brand is eligible. Check [incremental_authorization_supported](https://stripe.com/docs/api/charges/object#charge_object-payment_method_details-card_present-incremental_authorization_supported) in the [Confirm](https://stripe.com/docs/api/payment_intents/confirm) response to verify support. + """ + request_incremental_authorization: NotRequired[ + "Literal['if_available', 'never']" + ] + """ + This field was released by mistake and will be removed in the next major version + """ + + class ConfirmParamsPaymentMethodOptionsCardThreeDSecure(TypedDict): + ares_trans_status: NotRequired[ + "Literal['A', 'C', 'I', 'N', 'R', 'U', 'Y']" + ] + """ + The `transStatus` returned from the card Issuer's ACS in the ARes. + """ + cryptogram: str + """ + The cryptogram, also known as the "authentication value" (AAV, CAVV or + AEVV). This value is 20 bytes, base64-encoded into a 28-character string. + (Most 3D Secure providers will return the base64-encoded version, which + is what you should specify here.) + """ + electronic_commerce_indicator: NotRequired[ + "Literal['01', '02', '05', '06', '07']" + ] + """ + The Electronic Commerce Indicator (ECI) is returned by your 3D Secure + provider and indicates what degree of authentication was performed. + """ + exemption_indicator: NotRequired["Literal['low_risk', 'none']"] + """ + The exemption requested via 3DS and accepted by the issuer at authentication time. + """ + network_options: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodOptionsCardThreeDSecureNetworkOptions" + ] + """ + Network specific 3DS fields. Network specific arguments require an + explicit card brand choice. The parameter `payment_method_options.card.network`` + must be populated accordingly + """ + requestor_challenge_indicator: NotRequired["str"] + """ + The challenge indicator (`threeDSRequestorChallengeInd`) which was requested in the + AReq sent to the card Issuer's ACS. A string containing 2 digits from 01-99. + """ + transaction_id: str + """ + For 3D Secure 1, the XID. For 3D Secure 2, the Directory Server + Transaction ID (dsTransID). + """ + version: Literal["1.0.2", "2.1.0", "2.2.0"] + """ + The version of 3D Secure that was performed. + """ + + class ConfirmParamsPaymentMethodOptionsCardThreeDSecureNetworkOptions( + TypedDict, + ): + cartes_bancaires: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancaires" + ] + """ + Cartes Bancaires-specific 3DS fields. + """ + + class ConfirmParamsPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancaires( + TypedDict, + ): + cb_avalgo: Literal["0", "1", "2", "3", "4", "A"] + """ + The cryptogram calculation algorithm used by the card Issuer's ACS + to calculate the Authentication cryptogram. Also known as `cavvAlgorithm`. + messageExtension: CB-AVALGO + """ + cb_exemption: NotRequired["str"] + """ + The exemption indicator returned from Cartes Bancaires in the ARes. + message extension: CB-EXEMPTION; string (4 characters) + This is a 3 byte bitmap (low significant byte first and most significant + bit first) that has been Base64 encoded + """ + cb_score: NotRequired["int"] + """ + The risk score returned from Cartes Bancaires in the ARes. + message extension: CB-SCORE; numeric value 0-99 + """ + + class ConfirmParamsPaymentMethodOptionsCashapp(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsCustomerBalance(TypedDict): + bank_transfer: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodOptionsCustomerBalanceBankTransfer" + ] + """ + Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + """ + funding_type: NotRequired["Literal['bank_transfer']"] + """ + The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsCustomerBalanceBankTransfer( + TypedDict, + ): + eu_bank_transfer: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer" + ] + """ + Configuration for the eu_bank_transfer funding type. + """ + requested_address_types: NotRequired[ + "List[Literal['aba', 'iban', 'sepa', 'sort_code', 'spei', 'swift', 'zengin']]" + ] + """ + List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. + + Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. + """ + type: Literal[ + "eu_bank_transfer", + "gb_bank_transfer", + "jp_bank_transfer", + "mx_bank_transfer", + "us_bank_transfer", + ] + """ + The list of bank transfer types that this PaymentIntent is allowed to use for funding Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + """ + + class ConfirmParamsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer( + TypedDict, + ): + country: str + """ + The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + """ + + class ConfirmParamsPaymentMethodOptionsEps(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsFpx(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsGiropay(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsGrabpay(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsIdeal(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsInteracPresent(TypedDict): + pass + + class ConfirmParamsPaymentMethodOptionsKlarna(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + preferred_locale: NotRequired[ + "Literal['cs-CZ', 'da-DK', 'de-AT', 'de-CH', 'de-DE', 'el-GR', 'en-AT', 'en-AU', 'en-BE', 'en-CA', 'en-CH', 'en-CZ', 'en-DE', 'en-DK', 'en-ES', 'en-FI', 'en-FR', 'en-GB', 'en-GR', 'en-IE', 'en-IT', 'en-NL', 'en-NO', 'en-NZ', 'en-PL', 'en-PT', 'en-SE', 'en-US', 'es-ES', 'es-US', 'fi-FI', 'fr-BE', 'fr-CA', 'fr-CH', 'fr-FR', 'it-CH', 'it-IT', 'nb-NO', 'nl-BE', 'nl-NL', 'pl-PL', 'pt-PT', 'sv-FI', 'sv-SE']" + ] + """ + Preferred language of the Klarna authorization page that the customer is redirected to + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsKonbini(TypedDict): + confirmation_number: NotRequired["Literal['']|str"] + """ + An optional 10 to 11 digit numeric-only string determining the confirmation code at applicable convenience stores. Must not consist of only zeroes and could be rejected in case of insufficient uniqueness. We recommend to use the customer's phone number. + """ + expires_after_days: NotRequired["Literal['']|int"] + """ + The number of calendar days (between 1 and 60) after which Konbini payment instructions will expire. For example, if a PaymentIntent is confirmed with Konbini and `expires_after_days` set to 2 on Monday JST, the instructions will expire on Wednesday 23:59:59 JST. Defaults to 3 days. + """ + expires_at: NotRequired["Literal['']|int"] + """ + The timestamp at which the Konbini payment instructions will expire. Only one of `expires_after_days` or `expires_at` may be set. + """ + product_description: NotRequired["Literal['']|str"] + """ + A product descriptor of up to 22 characters, which will appear to customers at the convenience store. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsLink(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + persistent_token: NotRequired["str"] + """ + [Deprecated] This is a legacy parameter that no longer has any function. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsOxxo(TypedDict): + expires_after_days: NotRequired["int"] + """ + The number of calendar days before an OXXO voucher expires. For example, if you create an OXXO voucher on Monday and you set expires_after_days to 2, the OXXO invoice will expire on Wednesday at 23:59 America/Mexico_City time. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsP24(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + tos_shown_and_accepted: NotRequired["bool"] + """ + Confirm that the payer has accepted the P24 terms and conditions. + """ + + class ConfirmParamsPaymentMethodOptionsPaynow(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsPaypal(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + """ + preferred_locale: NotRequired[ + "Literal['cs-CZ', 'da-DK', 'de-AT', 'de-DE', 'de-LU', 'el-GR', 'en-GB', 'en-US', 'es-ES', 'fi-FI', 'fr-BE', 'fr-FR', 'fr-LU', 'hu-HU', 'it-IT', 'nl-BE', 'nl-NL', 'pl-PL', 'pt-PT', 'sk-SK', 'sv-SE']" + ] + """ + [Preferred locale](https://stripe.com/docs/payments/paypal/supported-locales) of the PayPal checkout page that the customer is redirected to. + """ + reference: NotRequired["str"] + """ + A reference of the PayPal transaction visible to customer which is mapped to PayPal's invoice ID. This must be a globally unique ID if you have configured in your PayPal settings to block multiple payments per invoice ID. + """ + risk_correlation_id: NotRequired["str"] + """ + The risk correlation ID for an on-session payment using a saved PayPal payment method. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsPix(TypedDict): + expires_after_seconds: NotRequired["int"] + """ + The number of seconds (between 10 and 1209600) after which Pix payment will expire. Defaults to 86400 seconds. + """ + expires_at: NotRequired["int"] + """ + The timestamp at which the Pix expires (between 10 and 1209600 seconds in the future). Defaults to 1 day in the future. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsPromptpay(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsRevolutPay(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class ConfirmParamsPaymentMethodOptionsSepaDebit(TypedDict): + mandate_options: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodOptionsSepaDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsSepaDebitMandateOptions(TypedDict): + pass + + class ConfirmParamsPaymentMethodOptionsSofort(TypedDict): + preferred_language: NotRequired[ + "Literal['']|Literal['de', 'en', 'es', 'fr', 'it', 'nl', 'pl']" + ] + """ + Language shown to the payer on redirect. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsUsBankAccount(TypedDict): + financial_connections: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodOptionsUsBankAccountFinancialConnections" + ] + """ + Additional fields for Financial Connections Session creation + """ + mandate_options: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodOptionsUsBankAccountMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + networks: NotRequired[ + "PaymentIntentService.ConfirmParamsPaymentMethodOptionsUsBankAccountNetworks" + ] + """ + Additional fields for network related functions + """ + preferred_settlement_speed: NotRequired[ + "Literal['']|Literal['fastest', 'standard']" + ] + """ + Preferred transaction settlement speed + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Bank account verification method. + """ + + class ConfirmParamsPaymentMethodOptionsUsBankAccountFinancialConnections( + TypedDict, + ): + permissions: NotRequired[ + "List[Literal['balances', 'ownership', 'payment_method', 'transactions']]" + ] + """ + The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + """ + prefetch: NotRequired["List[Literal['balances', 'transactions']]"] + """ + List of data features that you would like to retrieve upon account creation. + """ + return_url: NotRequired["str"] + """ + For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + """ + + class ConfirmParamsPaymentMethodOptionsUsBankAccountMandateOptions( + TypedDict, + ): + collection_method: NotRequired["Literal['']|Literal['paper']"] + """ + The method used to collect offline mandate customer acceptance. + """ + + class ConfirmParamsPaymentMethodOptionsUsBankAccountNetworks(TypedDict): + requested: NotRequired["List[Literal['ach', 'us_domestic_wire']]"] + """ + Triggers validations to run across the selected networks + """ + + class ConfirmParamsPaymentMethodOptionsWechatPay(TypedDict): + app_id: NotRequired["str"] + """ + The app ID registered with WeChat Pay. Only required when client is ios or android. + """ + client: Literal["android", "ios", "web"] + """ + The client type that the end customer will pay from + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsPaymentMethodOptionsZip(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class ConfirmParamsRadarOptions(TypedDict): + session: NotRequired["str"] + """ + A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + """ + + class ConfirmParamsShipping(TypedDict): + address: "PaymentIntentService.ConfirmParamsShippingAddress" + """ + Shipping address. + """ + carrier: NotRequired["str"] + """ + The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. + """ + name: str + """ + Recipient name. + """ + phone: NotRequired["str"] + """ + Recipient phone (including extension). + """ + tracking_number: NotRequired["str"] + """ + The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. + """ + + class ConfirmParamsShippingAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParams(TypedDict): + amount: int + """ + Amount intended to be collected by this PaymentIntent. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + """ + application_fee_amount: NotRequired["int"] + """ + The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. The amount of the application fee collected will be capped at the total payment amount. For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + """ + automatic_payment_methods: NotRequired[ + "PaymentIntentService.CreateParamsAutomaticPaymentMethods" + ] + """ + When you enable this parameter, this PaymentIntent accepts payment methods that you enable in the Dashboard and that are compatible with this PaymentIntent's other parameters. + """ + capture_method: NotRequired[ + "Literal['automatic', 'automatic_async', 'manual']" + ] + """ + Controls when the funds will be captured from the customer's account. + """ + confirm: NotRequired["bool"] + """ + Set to `true` to attempt to [confirm this PaymentIntent](https://stripe.com/docs/api/payment_intents/confirm) this PaymentIntent immediately. This parameter defaults to `false`. When creating and confirming a PaymentIntent at the same time, you can also provide the parameters available in the [Confirm API](https://stripe.com/docs/api/payment_intents/confirm). + """ + confirmation_method: NotRequired["Literal['automatic', 'manual']"] + """ + Describes whether we can confirm this PaymentIntent automatically, or if it requires customer action to confirm the payment. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + customer: NotRequired["str"] + """ + ID of the Customer this PaymentIntent belongs to, if one exists. + + Payment methods attached to other Customers cannot be used with this PaymentIntent. + + If present in combination with [setup_future_usage](https://stripe.com/docs/api#payment_intent_object-setup_future_usage), this PaymentIntent's payment method will be attached to the Customer after the PaymentIntent has been confirmed and any required actions from the user are complete. + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + error_on_requires_action: NotRequired["bool"] + """ + Set to `true` to fail the payment attempt if the PaymentIntent transitions into `requires_action`. Use this parameter for simpler integrations that don't handle customer actions, such as [saving cards without authentication](https://stripe.com/docs/payments/save-card-without-authentication). This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + mandate: NotRequired["str"] + """ + ID of the mandate that's used for this payment. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + """ + mandate_data: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsMandateData" + ] + """ + This hash contains details about the Mandate to create. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + off_session: NotRequired["bool|Literal['one_off', 'recurring']"] + """ + Set to `true` to indicate that the customer isn't in your checkout flow during this payment attempt and can't authenticate. Use this parameter in scenarios where you collect card details and [charge them later](https://stripe.com/docs/payments/cards/charging-saved-cards). This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + """ + on_behalf_of: NotRequired["str"] + """ + The Stripe account ID that these funds are intended for. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + """ + payment_method: NotRequired["str"] + """ + ID of the payment method (a PaymentMethod, Card, or [compatible Source](https://stripe.com/docs/payments/payment-methods#compatibility) object) to attach to this PaymentIntent. + + If you don't provide the `payment_method` parameter or the `source` parameter with `confirm=true`, `source` automatically populates with `customer.default_source` to improve migration for users of the Charges API. We recommend that you explicitly provide the `payment_method` moving forward. + """ + payment_method_configuration: NotRequired["str"] + """ + The ID of the payment method configuration to use with this PaymentIntent. + """ + payment_method_data: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodData" + ] + """ + If provided, this hash will be used to create a PaymentMethod. The new PaymentMethod will appear + in the [payment_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-payment_method) + property on the PaymentIntent. + """ + payment_method_options: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodOptions" + ] + """ + Payment method-specific configuration for this PaymentIntent. + """ + payment_method_types: NotRequired["List[str]"] + """ + The list of payment method types (for example, a card) that this PaymentIntent can use. If you don't provide this, it defaults to ["card"]. Use `automatic_payment_methods` to manage payment methods from the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). + """ + radar_options: NotRequired[ + "PaymentIntentService.CreateParamsRadarOptions" + ] + """ + Options to configure Radar. Learn more about [Radar Sessions](https://stripe.com/docs/radar/radar-session). + """ + receipt_email: NotRequired["str"] + """ + Email address to send the receipt to. If you specify `receipt_email` for a payment in live mode, you send a receipt regardless of your [email settings](https://dashboard.stripe.com/account/emails). + """ + return_url: NotRequired["str"] + """ + The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method's app or site. If you'd prefer to redirect to a mobile application, you can alternatively supply an application URI scheme. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-confirm). + """ + setup_future_usage: NotRequired["Literal['off_session', 'on_session']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + shipping: NotRequired["PaymentIntentService.CreateParamsShipping"] + """ + Shipping information for this PaymentIntent. + """ + statement_descriptor: NotRequired["str"] + """ + For card charges, use [statement_descriptor_suffix](https://stripe.com/docs/payments/account/statement-descriptors#dynamic). Otherwise, you can use this value as the complete description of a charge on your customers' statements. It must contain at least one letter and be 1–22 characters long. + """ + statement_descriptor_suffix: NotRequired["str"] + """ + Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that's set on the account to form the complete statement descriptor. The concatenated descriptor must contain 1-22 characters. + """ + transfer_data: NotRequired[ + "PaymentIntentService.CreateParamsTransferData" + ] + """ + The parameters that you can use to automatically create a Transfer. + Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + """ + transfer_group: NotRequired["str"] + """ + A string that identifies the resulting payment as part of a group. Learn more about the [use case for connected accounts](https://stripe.com/docs/connect/separate-charges-and-transfers). + """ + use_stripe_sdk: NotRequired["bool"] + """ + Set to `true` when confirming server-side and using Stripe.js, iOS, or Android client-side SDKs to handle the next actions. + """ + + class CreateParamsAutomaticPaymentMethods(TypedDict): + allow_redirects: NotRequired["Literal['always', 'never']"] + """ + Controls whether this PaymentIntent will accept redirect-based payment methods. + + Redirect-based payment methods may require your customer to be redirected to a payment method's app or site for authentication or additional steps. To [confirm](https://stripe.com/docs/api/payment_intents/confirm) this PaymentIntent, you may be required to provide a `return_url` to redirect customers back to your site after they authenticate or complete the payment. + """ + enabled: bool + """ + Whether this feature is enabled. + """ + + class CreateParamsMandateData(TypedDict): + customer_acceptance: "PaymentIntentService.CreateParamsMandateDataCustomerAcceptance" + """ + This hash contains details about the customer acceptance of the Mandate. + """ + + class CreateParamsMandateDataCustomerAcceptance(TypedDict): + accepted_at: NotRequired["int"] + """ + The time at which the customer accepted the Mandate. + """ + offline: NotRequired[ + "PaymentIntentService.CreateParamsMandateDataCustomerAcceptanceOffline" + ] + """ + If this is a Mandate accepted offline, this hash contains details about the offline acceptance. + """ + online: NotRequired[ + "PaymentIntentService.CreateParamsMandateDataCustomerAcceptanceOnline" + ] + """ + If this is a Mandate accepted online, this hash contains details about the online acceptance. + """ + type: Literal["offline", "online"] + """ + The type of customer acceptance information included with the Mandate. One of `online` or `offline`. + """ + + class CreateParamsMandateDataCustomerAcceptanceOffline(TypedDict): + pass + + class CreateParamsMandateDataCustomerAcceptanceOnline(TypedDict): + ip_address: str + """ + The IP address from which the Mandate was accepted by the customer. + """ + user_agent: str + """ + The user agent of the browser from which the Mandate was accepted by the customer. + """ + + class CreateParamsPaymentMethodData(TypedDict): + acss_debit: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataAcssDebit" + ] + """ + If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + """ + affirm: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataAffirm" + ] + """ + If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + """ + afterpay_clearpay: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataAfterpayClearpay" + ] + """ + If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + """ + alipay: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataAlipay" + ] + """ + If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + """ + au_becs_debit: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataAuBecsDebit" + ] + """ + If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + """ + bacs_debit: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataBacsDebit" + ] + """ + If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + """ + bancontact: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataBancontact" + ] + """ + If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + """ + billing_details: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataBillingDetails" + ] + """ + Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + """ + blik: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataBlik" + ] + """ + If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + """ + boleto: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataBoleto" + ] + """ + If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + """ + cashapp: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataCashapp" + ] + """ + If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + """ + customer_balance: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataCustomerBalance" + ] + """ + If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + """ + eps: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataEps" + ] + """ + If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + """ + fpx: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataFpx" + ] + """ + If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + """ + giropay: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataGiropay" + ] + """ + If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + """ + grabpay: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataGrabpay" + ] + """ + If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + """ + ideal: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataIdeal" + ] + """ + If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + """ + interac_present: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataInteracPresent" + ] + """ + If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + """ + klarna: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataKlarna" + ] + """ + If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + """ + konbini: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataKonbini" + ] + """ + If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + """ + link: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataLink" + ] + """ + If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + oxxo: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataOxxo" + ] + """ + If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + """ + p24: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataP24" + ] + """ + If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + """ + paynow: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataPaynow" + ] + """ + If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + """ + paypal: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataPaypal" + ] + """ + If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + """ + pix: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataPix" + ] + """ + If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + """ + promptpay: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataPromptpay" + ] + """ + If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + """ + radar_options: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataRadarOptions" + ] + """ + Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + """ + revolut_pay: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataRevolutPay" + ] + """ + If this is a `Revolut Pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + """ + sepa_debit: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataSepaDebit" + ] + """ + If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + """ + sofort: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataSofort" + ] + """ + If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + """ + type: Literal[ + "acss_debit", + "affirm", + "afterpay_clearpay", + "alipay", + "au_becs_debit", + "bacs_debit", + "bancontact", + "blik", + "boleto", + "cashapp", + "customer_balance", + "eps", + "fpx", + "giropay", + "grabpay", + "ideal", + "klarna", + "konbini", + "link", + "oxxo", + "p24", + "paynow", + "paypal", + "pix", + "promptpay", + "revolut_pay", + "sepa_debit", + "sofort", + "us_bank_account", + "wechat_pay", + "zip", + ] + """ + The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + """ + us_bank_account: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataUsBankAccount" + ] + """ + If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + """ + wechat_pay: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataWechatPay" + ] + """ + If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + """ + zip: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataZip" + ] + """ + If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + """ + + class CreateParamsPaymentMethodDataAcssDebit(TypedDict): + account_number: str + """ + Customer's bank account number. + """ + institution_number: str + """ + Institution number of the customer's bank. + """ + transit_number: str + """ + Transit number of the customer's bank. + """ + + class CreateParamsPaymentMethodDataAffirm(TypedDict): + pass + + class CreateParamsPaymentMethodDataAfterpayClearpay(TypedDict): + pass + + class CreateParamsPaymentMethodDataAlipay(TypedDict): + pass + + class CreateParamsPaymentMethodDataAuBecsDebit(TypedDict): + account_number: str + """ + The account number for the bank account. + """ + bsb_number: str + """ + Bank-State-Branch number of the bank account. + """ + + class CreateParamsPaymentMethodDataBacsDebit(TypedDict): + account_number: NotRequired["str"] + """ + Account number of the bank account that the funds will be debited from. + """ + sort_code: NotRequired["str"] + """ + Sort code of the bank account. (e.g., `10-20-30`) + """ + + class CreateParamsPaymentMethodDataBancontact(TypedDict): + pass + + class CreateParamsPaymentMethodDataBillingDetails(TypedDict): + address: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodDataBillingDetailsAddress" + ] + """ + Billing address. + """ + email: NotRequired["Literal['']|str"] + """ + Email address. + """ + name: NotRequired["Literal['']|str"] + """ + Full name. + """ + phone: NotRequired["Literal['']|str"] + """ + Billing phone number (including extension). + """ + + class CreateParamsPaymentMethodDataBillingDetailsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsPaymentMethodDataBlik(TypedDict): + pass + + class CreateParamsPaymentMethodDataBoleto(TypedDict): + tax_id: str + """ + The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + """ + + class CreateParamsPaymentMethodDataCashapp(TypedDict): + pass + + class CreateParamsPaymentMethodDataCustomerBalance(TypedDict): + pass + + class CreateParamsPaymentMethodDataEps(TypedDict): + bank: NotRequired[ + "Literal['arzte_und_apotheker_bank', 'austrian_anadi_bank_ag', 'bank_austria', 'bankhaus_carl_spangler', 'bankhaus_schelhammer_und_schattera_ag', 'bawag_psk_ag', 'bks_bank_ag', 'brull_kallmus_bank_ag', 'btv_vier_lander_bank', 'capital_bank_grawe_gruppe_ag', 'deutsche_bank_ag', 'dolomitenbank', 'easybank_ag', 'erste_bank_und_sparkassen', 'hypo_alpeadriabank_international_ag', 'hypo_bank_burgenland_aktiengesellschaft', 'hypo_noe_lb_fur_niederosterreich_u_wien', 'hypo_oberosterreich_salzburg_steiermark', 'hypo_tirol_bank_ag', 'hypo_vorarlberg_bank_ag', 'marchfelder_bank', 'oberbank_ag', 'raiffeisen_bankengruppe_osterreich', 'schoellerbank_ag', 'sparda_bank_wien', 'volksbank_gruppe', 'volkskreditbank_ag', 'vr_bank_braunau']" + ] + """ + The customer's bank. + """ + + class CreateParamsPaymentMethodDataFpx(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type for FPX transaction + """ + bank: Literal[ + "affin_bank", + "agrobank", + "alliance_bank", + "ambank", + "bank_islam", + "bank_muamalat", + "bank_of_china", + "bank_rakyat", + "bsn", + "cimb", + "deutsche_bank", + "hong_leong_bank", + "hsbc", + "kfh", + "maybank2e", + "maybank2u", + "ocbc", + "pb_enterprise", + "public_bank", + "rhb", + "standard_chartered", + "uob", + ] + """ + The customer's bank. + """ + + class CreateParamsPaymentMethodDataGiropay(TypedDict): + pass + + class CreateParamsPaymentMethodDataGrabpay(TypedDict): + pass + + class CreateParamsPaymentMethodDataIdeal(TypedDict): + bank: NotRequired[ + "Literal['abn_amro', 'asn_bank', 'bunq', 'handelsbanken', 'ing', 'knab', 'moneyou', 'n26', 'nn', 'rabobank', 'regiobank', 'revolut', 'sns_bank', 'triodos_bank', 'van_lanschot', 'yoursafe']" + ] + """ + The customer's bank. + """ + + class CreateParamsPaymentMethodDataInteracPresent(TypedDict): + pass + + class CreateParamsPaymentMethodDataKlarna(TypedDict): + dob: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodDataKlarnaDob" + ] + """ + Customer's date of birth + """ + + class CreateParamsPaymentMethodDataKlarnaDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class CreateParamsPaymentMethodDataKonbini(TypedDict): + pass + + class CreateParamsPaymentMethodDataLink(TypedDict): + pass + + class CreateParamsPaymentMethodDataOxxo(TypedDict): + pass + + class CreateParamsPaymentMethodDataP24(TypedDict): + bank: NotRequired[ + "Literal['alior_bank', 'bank_millennium', 'bank_nowy_bfg_sa', 'bank_pekao_sa', 'banki_spbdzielcze', 'blik', 'bnp_paribas', 'boz', 'citi_handlowy', 'credit_agricole', 'envelobank', 'etransfer_pocztowy24', 'getin_bank', 'ideabank', 'ing', 'inteligo', 'mbank_mtransfer', 'nest_przelew', 'noble_pay', 'pbac_z_ipko', 'plus_bank', 'santander_przelew24', 'tmobile_usbugi_bankowe', 'toyota_bank', 'volkswagen_bank']" + ] + """ + The customer's bank. + """ + + class CreateParamsPaymentMethodDataPaynow(TypedDict): + pass + + class CreateParamsPaymentMethodDataPaypal(TypedDict): + pass + + class CreateParamsPaymentMethodDataPix(TypedDict): + pass + + class CreateParamsPaymentMethodDataPromptpay(TypedDict): + pass + + class CreateParamsPaymentMethodDataRadarOptions(TypedDict): + session: NotRequired["str"] + """ + A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + """ + + class CreateParamsPaymentMethodDataRevolutPay(TypedDict): + pass + + class CreateParamsPaymentMethodDataSepaDebit(TypedDict): + iban: str + """ + IBAN of the bank account. + """ + + class CreateParamsPaymentMethodDataSofort(TypedDict): + country: Literal["AT", "BE", "DE", "ES", "IT", "NL"] + """ + Two-letter ISO code representing the country the bank account is located in. + """ + + class CreateParamsPaymentMethodDataUsBankAccount(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type: individual or company. + """ + account_number: NotRequired["str"] + """ + Account number of the bank account. + """ + account_type: NotRequired["Literal['checking', 'savings']"] + """ + Account type: checkings or savings. Defaults to checking if omitted. + """ + financial_connections_account: NotRequired["str"] + """ + The ID of a Financial Connections Account to use as a payment method. + """ + routing_number: NotRequired["str"] + """ + Routing number of the bank account. + """ + + class CreateParamsPaymentMethodDataWechatPay(TypedDict): + pass + + class CreateParamsPaymentMethodDataZip(TypedDict): + pass + + class CreateParamsPaymentMethodOptions(TypedDict): + acss_debit: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsAcssDebit" + ] + """ + If this is a `acss_debit` PaymentMethod, this sub-hash contains details about the ACSS Debit payment method options. + """ + affirm: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsAffirm" + ] + """ + If this is an `affirm` PaymentMethod, this sub-hash contains details about the Affirm payment method options. + """ + afterpay_clearpay: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsAfterpayClearpay" + ] + """ + If this is a `afterpay_clearpay` PaymentMethod, this sub-hash contains details about the Afterpay Clearpay payment method options. + """ + alipay: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsAlipay" + ] + """ + If this is a `alipay` PaymentMethod, this sub-hash contains details about the Alipay payment method options. + """ + au_becs_debit: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsAuBecsDebit" + ] + """ + If this is a `au_becs_debit` PaymentMethod, this sub-hash contains details about the AU BECS Direct Debit payment method options. + """ + bacs_debit: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsBacsDebit" + ] + """ + If this is a `bacs_debit` PaymentMethod, this sub-hash contains details about the BACS Debit payment method options. + """ + bancontact: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsBancontact" + ] + """ + If this is a `bancontact` PaymentMethod, this sub-hash contains details about the Bancontact payment method options. + """ + blik: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsBlik" + ] + """ + If this is a `blik` PaymentMethod, this sub-hash contains details about the BLIK payment method options. + """ + boleto: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsBoleto" + ] + """ + If this is a `boleto` PaymentMethod, this sub-hash contains details about the Boleto payment method options. + """ + card: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsCard" + ] + """ + Configuration for any card payments attempted on this PaymentIntent. + """ + card_present: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsCardPresent" + ] + """ + If this is a `card_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. + """ + cashapp: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsCashapp" + ] + """ + If this is a `cashapp` PaymentMethod, this sub-hash contains details about the Cash App Pay payment method options. + """ + customer_balance: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsCustomerBalance" + ] + """ + If this is a `customer balance` PaymentMethod, this sub-hash contains details about the customer balance payment method options. + """ + eps: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsEps" + ] + """ + If this is a `eps` PaymentMethod, this sub-hash contains details about the EPS payment method options. + """ + fpx: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsFpx" + ] + """ + If this is a `fpx` PaymentMethod, this sub-hash contains details about the FPX payment method options. + """ + giropay: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsGiropay" + ] + """ + If this is a `giropay` PaymentMethod, this sub-hash contains details about the Giropay payment method options. + """ + grabpay: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsGrabpay" + ] + """ + If this is a `grabpay` PaymentMethod, this sub-hash contains details about the Grabpay payment method options. + """ + ideal: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsIdeal" + ] + """ + If this is a `ideal` PaymentMethod, this sub-hash contains details about the Ideal payment method options. + """ + interac_present: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsInteracPresent" + ] + """ + If this is a `interac_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. + """ + klarna: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsKlarna" + ] + """ + If this is a `klarna` PaymentMethod, this sub-hash contains details about the Klarna payment method options. + """ + konbini: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsKonbini" + ] + """ + If this is a `konbini` PaymentMethod, this sub-hash contains details about the Konbini payment method options. + """ + link: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsLink" + ] + """ + If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. + """ + oxxo: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsOxxo" + ] + """ + If this is a `oxxo` PaymentMethod, this sub-hash contains details about the OXXO payment method options. + """ + p24: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsP24" + ] + """ + If this is a `p24` PaymentMethod, this sub-hash contains details about the Przelewy24 payment method options. + """ + paynow: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsPaynow" + ] + """ + If this is a `paynow` PaymentMethod, this sub-hash contains details about the PayNow payment method options. + """ + paypal: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsPaypal" + ] + """ + If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. + """ + pix: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsPix" + ] + """ + If this is a `pix` PaymentMethod, this sub-hash contains details about the Pix payment method options. + """ + promptpay: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsPromptpay" + ] + """ + If this is a `promptpay` PaymentMethod, this sub-hash contains details about the PromptPay payment method options. + """ + revolut_pay: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsRevolutPay" + ] + """ + If this is a `revolut_pay` PaymentMethod, this sub-hash contains details about the Revolut Pay payment method options. + """ + sepa_debit: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsSepaDebit" + ] + """ + If this is a `sepa_debit` PaymentIntent, this sub-hash contains details about the SEPA Debit payment method options. + """ + sofort: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsSofort" + ] + """ + If this is a `sofort` PaymentMethod, this sub-hash contains details about the SOFORT payment method options. + """ + us_bank_account: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsUsBankAccount" + ] + """ + If this is a `us_bank_account` PaymentMethod, this sub-hash contains details about the US bank account payment method options. + """ + wechat_pay: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsWechatPay" + ] + """ + If this is a `wechat_pay` PaymentMethod, this sub-hash contains details about the WeChat Pay payment method options. + """ + zip: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsZip" + ] + """ + If this is a `zip` PaymentMethod, this sub-hash contains details about the Zip payment method options. + """ + + class CreateParamsPaymentMethodOptionsAcssDebit(TypedDict): + mandate_options: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodOptionsAcssDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Bank account verification method. + """ + + class CreateParamsPaymentMethodOptionsAcssDebitMandateOptions(TypedDict): + custom_mandate_url: NotRequired["Literal['']|str"] + """ + A URL for custom mandate text to render during confirmation step. + The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + """ + interval_description: NotRequired["str"] + """ + Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + """ + payment_schedule: NotRequired[ + "Literal['combined', 'interval', 'sporadic']" + ] + """ + Payment schedule for the mandate. + """ + transaction_type: NotRequired["Literal['business', 'personal']"] + """ + Transaction type of the mandate. + """ + + class CreateParamsPaymentMethodOptionsAffirm(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + preferred_locale: NotRequired["str"] + """ + Preferred language of the Affirm authorization page that the customer is redirected to. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsAfterpayClearpay(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + reference: NotRequired["str"] + """ + An internal identifier or reference that this payment corresponds to. You must limit the identifier to 128 characters, and it can only contain letters, numbers, underscores, backslashes, and dashes. + This field differs from the statement descriptor and item name. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsAlipay(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsAuBecsDebit(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsBacsDebit(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsBancontact(TypedDict): + preferred_language: NotRequired["Literal['de', 'en', 'fr', 'nl']"] + """ + Preferred language of the Bancontact authorization page that the customer is redirected to. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsBlik(TypedDict): + code: NotRequired["str"] + """ + The 6-digit BLIK code that a customer has generated using their banking application. Can only be set on confirmation. + """ + + class CreateParamsPaymentMethodOptionsBoleto(TypedDict): + expires_after_days: NotRequired["int"] + """ + The number of calendar days before a Boleto voucher expires. For example, if you create a Boleto voucher on Monday and you set expires_after_days to 2, the Boleto invoice will expire on Wednesday at 23:59 America/Sao_Paulo time. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsCard(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + cvc_token: NotRequired["str"] + """ + A single-use `cvc_update` Token that represents a card CVC value. When provided, the CVC value will be verified during the card payment attempt. This parameter can only be provided during confirmation. + """ + installments: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodOptionsCardInstallments" + ] + """ + Installment configuration for payments attempted on this PaymentIntent (Mexico Only). + + For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + """ + mandate_options: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodOptionsCardMandateOptions" + ] + """ + Configuration options for setting up an eMandate for cards issued in India. + """ + moto: NotRequired["bool"] + """ + When specified, this parameter indicates that a transaction will be marked + as MOTO (Mail Order Telephone Order) and thus out of scope for SCA. This + parameter can only be provided during confirmation. + """ + network: NotRequired[ + "Literal['amex', 'cartes_bancaires', 'diners', 'discover', 'eftpos_au', 'interac', 'jcb', 'mastercard', 'unionpay', 'unknown', 'visa']" + ] + """ + Selected network to process this PaymentIntent on. Depends on the available networks of the card attached to the PaymentIntent. Can be only set confirm-time. + """ + request_extended_authorization: NotRequired[ + "Literal['if_available', 'never']" + ] + """ + Request ability to [capture beyond the standard authorization validity window](https://stripe.com/docs/payments/extended-authorization) for this PaymentIntent. + """ + request_incremental_authorization: NotRequired[ + "Literal['if_available', 'never']" + ] + """ + Request ability to [increment the authorization](https://stripe.com/docs/payments/incremental-authorization) for this PaymentIntent. + """ + request_multicapture: NotRequired["Literal['if_available', 'never']"] + """ + Request ability to make [multiple captures](https://stripe.com/docs/payments/multicapture) for this PaymentIntent. + """ + request_overcapture: NotRequired["Literal['if_available', 'never']"] + """ + Request ability to [overcapture](https://stripe.com/docs/payments/overcapture) for this PaymentIntent. + """ + request_three_d_secure: NotRequired[ + "Literal['any', 'automatic', 'challenge']" + ] + """ + We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + statement_descriptor_suffix_kana: NotRequired["Literal['']|str"] + """ + Provides information about a card payment that customers see on their statements. Concatenated with the Kana prefix (shortened Kana descriptor) or Kana statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 22 characters. + """ + statement_descriptor_suffix_kanji: NotRequired["Literal['']|str"] + """ + Provides information about a card payment that customers see on their statements. Concatenated with the Kanji prefix (shortened Kanji descriptor) or Kanji statement descriptor that's set on the account to form the complete statement descriptor. Maximum 17 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 17 characters. + """ + three_d_secure: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodOptionsCardThreeDSecure" + ] + """ + If 3D Secure authentication was performed with a third-party provider, + the authentication details to use for this payment. + """ + + class CreateParamsPaymentMethodOptionsCardInstallments(TypedDict): + enabled: NotRequired["bool"] + """ + Setting to true enables installments for this PaymentIntent. + This will cause the response to contain a list of available installment plans. + Setting to false will prevent any selected plan from applying to a charge. + """ + plan: NotRequired[ + "Literal['']|PaymentIntentService.CreateParamsPaymentMethodOptionsCardInstallmentsPlan" + ] + """ + The selected installment plan to use for this payment attempt. + This parameter can only be provided during confirmation. + """ + + class CreateParamsPaymentMethodOptionsCardInstallmentsPlan(TypedDict): + count: int + """ + For `fixed_count` installment plans, this is the number of installment payments your customer will make to their credit card. + """ + interval: Literal["month"] + """ + For `fixed_count` installment plans, this is the interval between installment payments your customer will make to their credit card. + One of `month`. + """ + type: Literal["fixed_count"] + """ + Type of installment plan, one of `fixed_count`. + """ + + class CreateParamsPaymentMethodOptionsCardMandateOptions(TypedDict): + amount: int + """ + Amount to be charged for future payments. + """ + amount_type: Literal["fixed", "maximum"] + """ + One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + """ + description: NotRequired["str"] + """ + A description of the mandate or subscription that is meant to be displayed to the customer. + """ + end_date: NotRequired["int"] + """ + End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + """ + interval: Literal["day", "month", "sporadic", "week", "year"] + """ + Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + """ + reference: str + """ + Unique identifier for the mandate or subscription. + """ + start_date: int + """ + Start date of the mandate or subscription. Start date should not be lesser than yesterday. + """ + supported_types: NotRequired["List[Literal['india']]"] + """ + Specifies the type of mandates supported. Possible values are `india`. + """ + + class CreateParamsPaymentMethodOptionsCardPresent(TypedDict): + request_extended_authorization: NotRequired["bool"] + """ + Request ability to capture this payment beyond the standard [authorization validity window](https://stripe.com/docs/terminal/features/extended-authorizations#authorization-validity) + """ + request_incremental_authorization_support: NotRequired["bool"] + """ + Request ability to [increment](https://stripe.com/docs/terminal/features/incremental-authorizations) this PaymentIntent if the combination of MCC and card brand is eligible. Check [incremental_authorization_supported](https://stripe.com/docs/api/charges/object#charge_object-payment_method_details-card_present-incremental_authorization_supported) in the [Confirm](https://stripe.com/docs/api/payment_intents/confirm) response to verify support. + """ + request_incremental_authorization: NotRequired[ + "Literal['if_available', 'never']" + ] + """ + This field was released by mistake and will be removed in the next major version + """ + + class CreateParamsPaymentMethodOptionsCardThreeDSecure(TypedDict): + ares_trans_status: NotRequired[ + "Literal['A', 'C', 'I', 'N', 'R', 'U', 'Y']" + ] + """ + The `transStatus` returned from the card Issuer's ACS in the ARes. + """ + cryptogram: str + """ + The cryptogram, also known as the "authentication value" (AAV, CAVV or + AEVV). This value is 20 bytes, base64-encoded into a 28-character string. + (Most 3D Secure providers will return the base64-encoded version, which + is what you should specify here.) + """ + electronic_commerce_indicator: NotRequired[ + "Literal['01', '02', '05', '06', '07']" + ] + """ + The Electronic Commerce Indicator (ECI) is returned by your 3D Secure + provider and indicates what degree of authentication was performed. + """ + exemption_indicator: NotRequired["Literal['low_risk', 'none']"] + """ + The exemption requested via 3DS and accepted by the issuer at authentication time. + """ + network_options: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptions" + ] + """ + Network specific 3DS fields. Network specific arguments require an + explicit card brand choice. The parameter `payment_method_options.card.network`` + must be populated accordingly + """ + requestor_challenge_indicator: NotRequired["str"] + """ + The challenge indicator (`threeDSRequestorChallengeInd`) which was requested in the + AReq sent to the card Issuer's ACS. A string containing 2 digits from 01-99. + """ + transaction_id: str + """ + For 3D Secure 1, the XID. For 3D Secure 2, the Directory Server + Transaction ID (dsTransID). + """ + version: Literal["1.0.2", "2.1.0", "2.2.0"] + """ + The version of 3D Secure that was performed. + """ + + class CreateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptions( + TypedDict, + ): + cartes_bancaires: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancaires" + ] + """ + Cartes Bancaires-specific 3DS fields. + """ + + class CreateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancaires( + TypedDict, + ): + cb_avalgo: Literal["0", "1", "2", "3", "4", "A"] + """ + The cryptogram calculation algorithm used by the card Issuer's ACS + to calculate the Authentication cryptogram. Also known as `cavvAlgorithm`. + messageExtension: CB-AVALGO + """ + cb_exemption: NotRequired["str"] + """ + The exemption indicator returned from Cartes Bancaires in the ARes. + message extension: CB-EXEMPTION; string (4 characters) + This is a 3 byte bitmap (low significant byte first and most significant + bit first) that has been Base64 encoded + """ + cb_score: NotRequired["int"] + """ + The risk score returned from Cartes Bancaires in the ARes. + message extension: CB-SCORE; numeric value 0-99 + """ + + class CreateParamsPaymentMethodOptionsCashapp(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsCustomerBalance(TypedDict): + bank_transfer: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodOptionsCustomerBalanceBankTransfer" + ] + """ + Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + """ + funding_type: NotRequired["Literal['bank_transfer']"] + """ + The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsCustomerBalanceBankTransfer( + TypedDict, + ): + eu_bank_transfer: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer" + ] + """ + Configuration for the eu_bank_transfer funding type. + """ + requested_address_types: NotRequired[ + "List[Literal['aba', 'iban', 'sepa', 'sort_code', 'spei', 'swift', 'zengin']]" + ] + """ + List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. + + Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. + """ + type: Literal[ + "eu_bank_transfer", + "gb_bank_transfer", + "jp_bank_transfer", + "mx_bank_transfer", + "us_bank_transfer", + ] + """ + The list of bank transfer types that this PaymentIntent is allowed to use for funding Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + """ + + class CreateParamsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer( + TypedDict, + ): + country: str + """ + The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + """ + + class CreateParamsPaymentMethodOptionsEps(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsFpx(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsGiropay(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsGrabpay(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsIdeal(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsInteracPresent(TypedDict): + pass + + class CreateParamsPaymentMethodOptionsKlarna(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + preferred_locale: NotRequired[ + "Literal['cs-CZ', 'da-DK', 'de-AT', 'de-CH', 'de-DE', 'el-GR', 'en-AT', 'en-AU', 'en-BE', 'en-CA', 'en-CH', 'en-CZ', 'en-DE', 'en-DK', 'en-ES', 'en-FI', 'en-FR', 'en-GB', 'en-GR', 'en-IE', 'en-IT', 'en-NL', 'en-NO', 'en-NZ', 'en-PL', 'en-PT', 'en-SE', 'en-US', 'es-ES', 'es-US', 'fi-FI', 'fr-BE', 'fr-CA', 'fr-CH', 'fr-FR', 'it-CH', 'it-IT', 'nb-NO', 'nl-BE', 'nl-NL', 'pl-PL', 'pt-PT', 'sv-FI', 'sv-SE']" + ] + """ + Preferred language of the Klarna authorization page that the customer is redirected to + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsKonbini(TypedDict): + confirmation_number: NotRequired["Literal['']|str"] + """ + An optional 10 to 11 digit numeric-only string determining the confirmation code at applicable convenience stores. Must not consist of only zeroes and could be rejected in case of insufficient uniqueness. We recommend to use the customer's phone number. + """ + expires_after_days: NotRequired["Literal['']|int"] + """ + The number of calendar days (between 1 and 60) after which Konbini payment instructions will expire. For example, if a PaymentIntent is confirmed with Konbini and `expires_after_days` set to 2 on Monday JST, the instructions will expire on Wednesday 23:59:59 JST. Defaults to 3 days. + """ + expires_at: NotRequired["Literal['']|int"] + """ + The timestamp at which the Konbini payment instructions will expire. Only one of `expires_after_days` or `expires_at` may be set. + """ + product_description: NotRequired["Literal['']|str"] + """ + A product descriptor of up to 22 characters, which will appear to customers at the convenience store. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsLink(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + persistent_token: NotRequired["str"] + """ + [Deprecated] This is a legacy parameter that no longer has any function. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsOxxo(TypedDict): + expires_after_days: NotRequired["int"] + """ + The number of calendar days before an OXXO voucher expires. For example, if you create an OXXO voucher on Monday and you set expires_after_days to 2, the OXXO invoice will expire on Wednesday at 23:59 America/Mexico_City time. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsP24(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + tos_shown_and_accepted: NotRequired["bool"] + """ + Confirm that the payer has accepted the P24 terms and conditions. + """ + + class CreateParamsPaymentMethodOptionsPaynow(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsPaypal(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + """ + preferred_locale: NotRequired[ + "Literal['cs-CZ', 'da-DK', 'de-AT', 'de-DE', 'de-LU', 'el-GR', 'en-GB', 'en-US', 'es-ES', 'fi-FI', 'fr-BE', 'fr-FR', 'fr-LU', 'hu-HU', 'it-IT', 'nl-BE', 'nl-NL', 'pl-PL', 'pt-PT', 'sk-SK', 'sv-SE']" + ] + """ + [Preferred locale](https://stripe.com/docs/payments/paypal/supported-locales) of the PayPal checkout page that the customer is redirected to. + """ + reference: NotRequired["str"] + """ + A reference of the PayPal transaction visible to customer which is mapped to PayPal's invoice ID. This must be a globally unique ID if you have configured in your PayPal settings to block multiple payments per invoice ID. + """ + risk_correlation_id: NotRequired["str"] + """ + The risk correlation ID for an on-session payment using a saved PayPal payment method. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsPix(TypedDict): + expires_after_seconds: NotRequired["int"] + """ + The number of seconds (between 10 and 1209600) after which Pix payment will expire. Defaults to 86400 seconds. + """ + expires_at: NotRequired["int"] + """ + The timestamp at which the Pix expires (between 10 and 1209600 seconds in the future). Defaults to 1 day in the future. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsPromptpay(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsRevolutPay(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsSepaDebit(TypedDict): + mandate_options: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodOptionsSepaDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsSepaDebitMandateOptions(TypedDict): + pass + + class CreateParamsPaymentMethodOptionsSofort(TypedDict): + preferred_language: NotRequired[ + "Literal['']|Literal['de', 'en', 'es', 'fr', 'it', 'nl', 'pl']" + ] + """ + Language shown to the payer on redirect. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsUsBankAccount(TypedDict): + financial_connections: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodOptionsUsBankAccountFinancialConnections" + ] + """ + Additional fields for Financial Connections Session creation + """ + mandate_options: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodOptionsUsBankAccountMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + networks: NotRequired[ + "PaymentIntentService.CreateParamsPaymentMethodOptionsUsBankAccountNetworks" + ] + """ + Additional fields for network related functions + """ + preferred_settlement_speed: NotRequired[ + "Literal['']|Literal['fastest', 'standard']" + ] + """ + Preferred transaction settlement speed + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Bank account verification method. + """ + + class CreateParamsPaymentMethodOptionsUsBankAccountFinancialConnections( + TypedDict, + ): + permissions: NotRequired[ + "List[Literal['balances', 'ownership', 'payment_method', 'transactions']]" + ] + """ + The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + """ + prefetch: NotRequired["List[Literal['balances', 'transactions']]"] + """ + List of data features that you would like to retrieve upon account creation. + """ + return_url: NotRequired["str"] + """ + For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + """ + + class CreateParamsPaymentMethodOptionsUsBankAccountMandateOptions( + TypedDict, + ): + collection_method: NotRequired["Literal['']|Literal['paper']"] + """ + The method used to collect offline mandate customer acceptance. + """ + + class CreateParamsPaymentMethodOptionsUsBankAccountNetworks(TypedDict): + requested: NotRequired["List[Literal['ach', 'us_domestic_wire']]"] + """ + Triggers validations to run across the selected networks + """ + + class CreateParamsPaymentMethodOptionsWechatPay(TypedDict): + app_id: NotRequired["str"] + """ + The app ID registered with WeChat Pay. Only required when client is ios or android. + """ + client: Literal["android", "ios", "web"] + """ + The client type that the end customer will pay from + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsZip(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsRadarOptions(TypedDict): + session: NotRequired["str"] + """ + A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + """ + + class CreateParamsShipping(TypedDict): + address: "PaymentIntentService.CreateParamsShippingAddress" + """ + Shipping address. + """ + carrier: NotRequired["str"] + """ + The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. + """ + name: str + """ + Recipient name. + """ + phone: NotRequired["str"] + """ + Recipient phone (including extension). + """ + tracking_number: NotRequired["str"] + """ + The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. + """ + + class CreateParamsShippingAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsTransferData(TypedDict): + amount: NotRequired["int"] + """ + The amount that will be transferred automatically when a charge succeeds. + The amount is capped at the total transaction amount and if no amount is set, + the full amount is transferred. + + If you intend to collect a fee and you need a more robust reporting experience, using + [application_fee_amount](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-application_fee_amount) + might be a better fit for your integration. + """ + destination: str + """ + If specified, successful charges will be attributed to the destination + account for tax reporting, and the funds from charges will be transferred + to the destination account. The ID of the resulting transfer will be + returned on the successful charge's `transfer` field. + """ + + class IncrementAuthorizationParams(TypedDict): + amount: int + """ + The updated total amount that you intend to collect from the cardholder. This amount must be greater than the currently authorized amount. + """ + application_fee_amount: NotRequired["int"] + """ + The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. The amount of the application fee collected will be capped at the total payment amount. For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + statement_descriptor: NotRequired["str"] + """ + For card charges, use [statement_descriptor_suffix](https://stripe.com/docs/payments/account/statement-descriptors#dynamic). Otherwise, you can use this value as the complete description of a charge on your customers' statements. It must contain at least one letter and be 1–22 characters long. + """ + transfer_data: NotRequired[ + "PaymentIntentService.IncrementAuthorizationParamsTransferData" + ] + """ + The parameters used to automatically create a transfer after the payment is captured. + Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + """ + + class IncrementAuthorizationParamsTransferData(TypedDict): + amount: NotRequired["int"] + """ + The amount that will be transferred automatically when a charge succeeds. + """ + + class ListParams(TypedDict): + created: NotRequired["PaymentIntentService.ListParamsCreated|int"] + """ + A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp or a dictionary with a number of different query options. + """ + customer: NotRequired["str"] + """ + Only return PaymentIntents for the customer that this customer ID specifies. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + client_secret: NotRequired["str"] + """ + The client secret of the PaymentIntent. We require it if you use a publishable key to retrieve the source. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class SearchParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + page: NotRequired["str"] + """ + A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + """ + query: str + """ + The search query string. See [search query language](https://stripe.com/docs/search#search-query-language) and the list of supported [query fields for payment intents](https://stripe.com/docs/search#query-fields-for-payment-intents). + """ + + class UpdateParams(TypedDict): + amount: NotRequired["int"] + """ + Amount intended to be collected by this PaymentIntent. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + """ + application_fee_amount: NotRequired["Literal['']|int"] + """ + The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. The amount of the application fee collected will be capped at the total payment amount. For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + """ + capture_method: NotRequired[ + "Literal['automatic', 'automatic_async', 'manual']" + ] + """ + Controls when the funds will be captured from the customer's account. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + customer: NotRequired["str"] + """ + ID of the Customer this PaymentIntent belongs to, if one exists. + + Payment methods attached to other Customers cannot be used with this PaymentIntent. + + If present in combination with [setup_future_usage](https://stripe.com/docs/api#payment_intent_object-setup_future_usage), this PaymentIntent's payment method will be attached to the Customer after the PaymentIntent has been confirmed and any required actions from the user are complete. + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + payment_method: NotRequired["str"] + """ + ID of the payment method (a PaymentMethod, Card, or [compatible Source](https://stripe.com/docs/payments/payment-methods/transitioning#compatibility) object) to attach to this PaymentIntent. + """ + payment_method_configuration: NotRequired["str"] + """ + The ID of the payment method configuration to use with this PaymentIntent. + """ + payment_method_data: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodData" + ] + """ + If provided, this hash will be used to create a PaymentMethod. The new PaymentMethod will appear + in the [payment_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-payment_method) + property on the PaymentIntent. + """ + payment_method_options: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodOptions" + ] + """ + Payment-method-specific configuration for this PaymentIntent. + """ + payment_method_types: NotRequired["List[str]"] + """ + The list of payment method types (for example, card) that this PaymentIntent can use. Use `automatic_payment_methods` to manage payment methods from the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). + """ + receipt_email: NotRequired["Literal['']|str"] + """ + Email address that the receipt for the resulting payment will be sent to. If `receipt_email` is specified for a payment in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + shipping: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsShipping" + ] + """ + Shipping information for this PaymentIntent. + """ + statement_descriptor: NotRequired["str"] + """ + For card charges, use [statement_descriptor_suffix](https://stripe.com/docs/payments/account/statement-descriptors#dynamic). Otherwise, you can use this value as the complete description of a charge on your customers' statements. It must contain at least one letter and be 1–22 characters long. + """ + statement_descriptor_suffix: NotRequired["str"] + """ + Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. + """ + transfer_data: NotRequired[ + "PaymentIntentService.UpdateParamsTransferData" + ] + """ + Use this parameter to automatically create a Transfer when the payment succeeds. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + """ + transfer_group: NotRequired["str"] + """ + A string that identifies the resulting payment as part of a group. You can only provide `transfer_group` if it hasn't been set. Learn more about the [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + """ + + class UpdateParamsPaymentMethodData(TypedDict): + acss_debit: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataAcssDebit" + ] + """ + If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + """ + affirm: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataAffirm" + ] + """ + If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + """ + afterpay_clearpay: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataAfterpayClearpay" + ] + """ + If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + """ + alipay: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataAlipay" + ] + """ + If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + """ + au_becs_debit: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataAuBecsDebit" + ] + """ + If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + """ + bacs_debit: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataBacsDebit" + ] + """ + If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + """ + bancontact: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataBancontact" + ] + """ + If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + """ + billing_details: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataBillingDetails" + ] + """ + Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + """ + blik: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataBlik" + ] + """ + If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + """ + boleto: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataBoleto" + ] + """ + If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + """ + cashapp: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataCashapp" + ] + """ + If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + """ + customer_balance: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataCustomerBalance" + ] + """ + If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + """ + eps: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataEps" + ] + """ + If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + """ + fpx: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataFpx" + ] + """ + If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + """ + giropay: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataGiropay" + ] + """ + If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + """ + grabpay: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataGrabpay" + ] + """ + If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + """ + ideal: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataIdeal" + ] + """ + If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + """ + interac_present: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataInteracPresent" + ] + """ + If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + """ + klarna: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataKlarna" + ] + """ + If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + """ + konbini: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataKonbini" + ] + """ + If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + """ + link: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataLink" + ] + """ + If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + oxxo: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataOxxo" + ] + """ + If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + """ + p24: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataP24" + ] + """ + If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + """ + paynow: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataPaynow" + ] + """ + If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + """ + paypal: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataPaypal" + ] + """ + If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + """ + pix: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataPix" + ] + """ + If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + """ + promptpay: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataPromptpay" + ] + """ + If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + """ + radar_options: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataRadarOptions" + ] + """ + Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + """ + revolut_pay: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataRevolutPay" + ] + """ + If this is a `Revolut Pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + """ + sepa_debit: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataSepaDebit" + ] + """ + If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + """ + sofort: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataSofort" + ] + """ + If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + """ + type: Literal[ + "acss_debit", + "affirm", + "afterpay_clearpay", + "alipay", + "au_becs_debit", + "bacs_debit", + "bancontact", + "blik", + "boleto", + "cashapp", + "customer_balance", + "eps", + "fpx", + "giropay", + "grabpay", + "ideal", + "klarna", + "konbini", + "link", + "oxxo", + "p24", + "paynow", + "paypal", + "pix", + "promptpay", + "revolut_pay", + "sepa_debit", + "sofort", + "us_bank_account", + "wechat_pay", + "zip", + ] + """ + The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + """ + us_bank_account: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataUsBankAccount" + ] + """ + If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + """ + wechat_pay: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataWechatPay" + ] + """ + If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + """ + zip: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataZip" + ] + """ + If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + """ + + class UpdateParamsPaymentMethodDataAcssDebit(TypedDict): + account_number: str + """ + Customer's bank account number. + """ + institution_number: str + """ + Institution number of the customer's bank. + """ + transit_number: str + """ + Transit number of the customer's bank. + """ + + class UpdateParamsPaymentMethodDataAffirm(TypedDict): + pass + + class UpdateParamsPaymentMethodDataAfterpayClearpay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataAlipay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataAuBecsDebit(TypedDict): + account_number: str + """ + The account number for the bank account. + """ + bsb_number: str + """ + Bank-State-Branch number of the bank account. + """ + + class UpdateParamsPaymentMethodDataBacsDebit(TypedDict): + account_number: NotRequired["str"] + """ + Account number of the bank account that the funds will be debited from. + """ + sort_code: NotRequired["str"] + """ + Sort code of the bank account. (e.g., `10-20-30`) + """ + + class UpdateParamsPaymentMethodDataBancontact(TypedDict): + pass + + class UpdateParamsPaymentMethodDataBillingDetails(TypedDict): + address: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodDataBillingDetailsAddress" + ] + """ + Billing address. + """ + email: NotRequired["Literal['']|str"] + """ + Email address. + """ + name: NotRequired["Literal['']|str"] + """ + Full name. + """ + phone: NotRequired["Literal['']|str"] + """ + Billing phone number (including extension). + """ + + class UpdateParamsPaymentMethodDataBillingDetailsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsPaymentMethodDataBlik(TypedDict): + pass + + class UpdateParamsPaymentMethodDataBoleto(TypedDict): + tax_id: str + """ + The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + """ + + class UpdateParamsPaymentMethodDataCashapp(TypedDict): + pass + + class UpdateParamsPaymentMethodDataCustomerBalance(TypedDict): + pass + + class UpdateParamsPaymentMethodDataEps(TypedDict): + bank: NotRequired[ + "Literal['arzte_und_apotheker_bank', 'austrian_anadi_bank_ag', 'bank_austria', 'bankhaus_carl_spangler', 'bankhaus_schelhammer_und_schattera_ag', 'bawag_psk_ag', 'bks_bank_ag', 'brull_kallmus_bank_ag', 'btv_vier_lander_bank', 'capital_bank_grawe_gruppe_ag', 'deutsche_bank_ag', 'dolomitenbank', 'easybank_ag', 'erste_bank_und_sparkassen', 'hypo_alpeadriabank_international_ag', 'hypo_bank_burgenland_aktiengesellschaft', 'hypo_noe_lb_fur_niederosterreich_u_wien', 'hypo_oberosterreich_salzburg_steiermark', 'hypo_tirol_bank_ag', 'hypo_vorarlberg_bank_ag', 'marchfelder_bank', 'oberbank_ag', 'raiffeisen_bankengruppe_osterreich', 'schoellerbank_ag', 'sparda_bank_wien', 'volksbank_gruppe', 'volkskreditbank_ag', 'vr_bank_braunau']" + ] + """ + The customer's bank. + """ + + class UpdateParamsPaymentMethodDataFpx(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type for FPX transaction + """ + bank: Literal[ + "affin_bank", + "agrobank", + "alliance_bank", + "ambank", + "bank_islam", + "bank_muamalat", + "bank_of_china", + "bank_rakyat", + "bsn", + "cimb", + "deutsche_bank", + "hong_leong_bank", + "hsbc", + "kfh", + "maybank2e", + "maybank2u", + "ocbc", + "pb_enterprise", + "public_bank", + "rhb", + "standard_chartered", + "uob", + ] + """ + The customer's bank. + """ + + class UpdateParamsPaymentMethodDataGiropay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataGrabpay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataIdeal(TypedDict): + bank: NotRequired[ + "Literal['abn_amro', 'asn_bank', 'bunq', 'handelsbanken', 'ing', 'knab', 'moneyou', 'n26', 'nn', 'rabobank', 'regiobank', 'revolut', 'sns_bank', 'triodos_bank', 'van_lanschot', 'yoursafe']" + ] + """ + The customer's bank. + """ + + class UpdateParamsPaymentMethodDataInteracPresent(TypedDict): + pass + + class UpdateParamsPaymentMethodDataKlarna(TypedDict): + dob: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodDataKlarnaDob" + ] + """ + Customer's date of birth + """ + + class UpdateParamsPaymentMethodDataKlarnaDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class UpdateParamsPaymentMethodDataKonbini(TypedDict): + pass + + class UpdateParamsPaymentMethodDataLink(TypedDict): + pass + + class UpdateParamsPaymentMethodDataOxxo(TypedDict): + pass + + class UpdateParamsPaymentMethodDataP24(TypedDict): + bank: NotRequired[ + "Literal['alior_bank', 'bank_millennium', 'bank_nowy_bfg_sa', 'bank_pekao_sa', 'banki_spbdzielcze', 'blik', 'bnp_paribas', 'boz', 'citi_handlowy', 'credit_agricole', 'envelobank', 'etransfer_pocztowy24', 'getin_bank', 'ideabank', 'ing', 'inteligo', 'mbank_mtransfer', 'nest_przelew', 'noble_pay', 'pbac_z_ipko', 'plus_bank', 'santander_przelew24', 'tmobile_usbugi_bankowe', 'toyota_bank', 'volkswagen_bank']" + ] + """ + The customer's bank. + """ + + class UpdateParamsPaymentMethodDataPaynow(TypedDict): + pass + + class UpdateParamsPaymentMethodDataPaypal(TypedDict): + pass + + class UpdateParamsPaymentMethodDataPix(TypedDict): + pass + + class UpdateParamsPaymentMethodDataPromptpay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataRadarOptions(TypedDict): + session: NotRequired["str"] + """ + A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + """ + + class UpdateParamsPaymentMethodDataRevolutPay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataSepaDebit(TypedDict): + iban: str + """ + IBAN of the bank account. + """ + + class UpdateParamsPaymentMethodDataSofort(TypedDict): + country: Literal["AT", "BE", "DE", "ES", "IT", "NL"] + """ + Two-letter ISO code representing the country the bank account is located in. + """ + + class UpdateParamsPaymentMethodDataUsBankAccount(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type: individual or company. + """ + account_number: NotRequired["str"] + """ + Account number of the bank account. + """ + account_type: NotRequired["Literal['checking', 'savings']"] + """ + Account type: checkings or savings. Defaults to checking if omitted. + """ + financial_connections_account: NotRequired["str"] + """ + The ID of a Financial Connections Account to use as a payment method. + """ + routing_number: NotRequired["str"] + """ + Routing number of the bank account. + """ + + class UpdateParamsPaymentMethodDataWechatPay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataZip(TypedDict): + pass + + class UpdateParamsPaymentMethodOptions(TypedDict): + acss_debit: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsAcssDebit" + ] + """ + If this is a `acss_debit` PaymentMethod, this sub-hash contains details about the ACSS Debit payment method options. + """ + affirm: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsAffirm" + ] + """ + If this is an `affirm` PaymentMethod, this sub-hash contains details about the Affirm payment method options. + """ + afterpay_clearpay: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsAfterpayClearpay" + ] + """ + If this is a `afterpay_clearpay` PaymentMethod, this sub-hash contains details about the Afterpay Clearpay payment method options. + """ + alipay: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsAlipay" + ] + """ + If this is a `alipay` PaymentMethod, this sub-hash contains details about the Alipay payment method options. + """ + au_becs_debit: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsAuBecsDebit" + ] + """ + If this is a `au_becs_debit` PaymentMethod, this sub-hash contains details about the AU BECS Direct Debit payment method options. + """ + bacs_debit: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsBacsDebit" + ] + """ + If this is a `bacs_debit` PaymentMethod, this sub-hash contains details about the BACS Debit payment method options. + """ + bancontact: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsBancontact" + ] + """ + If this is a `bancontact` PaymentMethod, this sub-hash contains details about the Bancontact payment method options. + """ + blik: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsBlik" + ] + """ + If this is a `blik` PaymentMethod, this sub-hash contains details about the BLIK payment method options. + """ + boleto: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsBoleto" + ] + """ + If this is a `boleto` PaymentMethod, this sub-hash contains details about the Boleto payment method options. + """ + card: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsCard" + ] + """ + Configuration for any card payments attempted on this PaymentIntent. + """ + card_present: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsCardPresent" + ] + """ + If this is a `card_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. + """ + cashapp: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsCashapp" + ] + """ + If this is a `cashapp` PaymentMethod, this sub-hash contains details about the Cash App Pay payment method options. + """ + customer_balance: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsCustomerBalance" + ] + """ + If this is a `customer balance` PaymentMethod, this sub-hash contains details about the customer balance payment method options. + """ + eps: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsEps" + ] + """ + If this is a `eps` PaymentMethod, this sub-hash contains details about the EPS payment method options. + """ + fpx: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsFpx" + ] + """ + If this is a `fpx` PaymentMethod, this sub-hash contains details about the FPX payment method options. + """ + giropay: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsGiropay" + ] + """ + If this is a `giropay` PaymentMethod, this sub-hash contains details about the Giropay payment method options. + """ + grabpay: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsGrabpay" + ] + """ + If this is a `grabpay` PaymentMethod, this sub-hash contains details about the Grabpay payment method options. + """ + ideal: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsIdeal" + ] + """ + If this is a `ideal` PaymentMethod, this sub-hash contains details about the Ideal payment method options. + """ + interac_present: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsInteracPresent" + ] + """ + If this is a `interac_present` PaymentMethod, this sub-hash contains details about the Card Present payment method options. + """ + klarna: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsKlarna" + ] + """ + If this is a `klarna` PaymentMethod, this sub-hash contains details about the Klarna payment method options. + """ + konbini: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsKonbini" + ] + """ + If this is a `konbini` PaymentMethod, this sub-hash contains details about the Konbini payment method options. + """ + link: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsLink" + ] + """ + If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. + """ + oxxo: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsOxxo" + ] + """ + If this is a `oxxo` PaymentMethod, this sub-hash contains details about the OXXO payment method options. + """ + p24: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsP24" + ] + """ + If this is a `p24` PaymentMethod, this sub-hash contains details about the Przelewy24 payment method options. + """ + paynow: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsPaynow" + ] + """ + If this is a `paynow` PaymentMethod, this sub-hash contains details about the PayNow payment method options. + """ + paypal: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsPaypal" + ] + """ + If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. + """ + pix: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsPix" + ] + """ + If this is a `pix` PaymentMethod, this sub-hash contains details about the Pix payment method options. + """ + promptpay: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsPromptpay" + ] + """ + If this is a `promptpay` PaymentMethod, this sub-hash contains details about the PromptPay payment method options. + """ + revolut_pay: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsRevolutPay" + ] + """ + If this is a `revolut_pay` PaymentMethod, this sub-hash contains details about the Revolut Pay payment method options. + """ + sepa_debit: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsSepaDebit" + ] + """ + If this is a `sepa_debit` PaymentIntent, this sub-hash contains details about the SEPA Debit payment method options. + """ + sofort: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsSofort" + ] + """ + If this is a `sofort` PaymentMethod, this sub-hash contains details about the SOFORT payment method options. + """ + us_bank_account: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsUsBankAccount" + ] + """ + If this is a `us_bank_account` PaymentMethod, this sub-hash contains details about the US bank account payment method options. + """ + wechat_pay: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsWechatPay" + ] + """ + If this is a `wechat_pay` PaymentMethod, this sub-hash contains details about the WeChat Pay payment method options. + """ + zip: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsZip" + ] + """ + If this is a `zip` PaymentMethod, this sub-hash contains details about the Zip payment method options. + """ + + class UpdateParamsPaymentMethodOptionsAcssDebit(TypedDict): + mandate_options: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodOptionsAcssDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Bank account verification method. + """ + + class UpdateParamsPaymentMethodOptionsAcssDebitMandateOptions(TypedDict): + custom_mandate_url: NotRequired["Literal['']|str"] + """ + A URL for custom mandate text to render during confirmation step. + The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + """ + interval_description: NotRequired["str"] + """ + Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + """ + payment_schedule: NotRequired[ + "Literal['combined', 'interval', 'sporadic']" + ] + """ + Payment schedule for the mandate. + """ + transaction_type: NotRequired["Literal['business', 'personal']"] + """ + Transaction type of the mandate. + """ + + class UpdateParamsPaymentMethodOptionsAffirm(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + preferred_locale: NotRequired["str"] + """ + Preferred language of the Affirm authorization page that the customer is redirected to. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsAfterpayClearpay(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + reference: NotRequired["str"] + """ + An internal identifier or reference that this payment corresponds to. You must limit the identifier to 128 characters, and it can only contain letters, numbers, underscores, backslashes, and dashes. + This field differs from the statement descriptor and item name. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsAlipay(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsAuBecsDebit(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsBacsDebit(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsBancontact(TypedDict): + preferred_language: NotRequired["Literal['de', 'en', 'fr', 'nl']"] + """ + Preferred language of the Bancontact authorization page that the customer is redirected to. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsBlik(TypedDict): + code: NotRequired["str"] + """ + The 6-digit BLIK code that a customer has generated using their banking application. Can only be set on confirmation. + """ + + class UpdateParamsPaymentMethodOptionsBoleto(TypedDict): + expires_after_days: NotRequired["int"] + """ + The number of calendar days before a Boleto voucher expires. For example, if you create a Boleto voucher on Monday and you set expires_after_days to 2, the Boleto invoice will expire on Wednesday at 23:59 America/Sao_Paulo time. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsCard(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + cvc_token: NotRequired["str"] + """ + A single-use `cvc_update` Token that represents a card CVC value. When provided, the CVC value will be verified during the card payment attempt. This parameter can only be provided during confirmation. + """ + installments: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodOptionsCardInstallments" + ] + """ + Installment configuration for payments attempted on this PaymentIntent (Mexico Only). + + For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + """ + mandate_options: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodOptionsCardMandateOptions" + ] + """ + Configuration options for setting up an eMandate for cards issued in India. + """ + moto: NotRequired["bool"] + """ + When specified, this parameter indicates that a transaction will be marked + as MOTO (Mail Order Telephone Order) and thus out of scope for SCA. This + parameter can only be provided during confirmation. + """ + network: NotRequired[ + "Literal['amex', 'cartes_bancaires', 'diners', 'discover', 'eftpos_au', 'interac', 'jcb', 'mastercard', 'unionpay', 'unknown', 'visa']" + ] + """ + Selected network to process this PaymentIntent on. Depends on the available networks of the card attached to the PaymentIntent. Can be only set confirm-time. + """ + request_extended_authorization: NotRequired[ + "Literal['if_available', 'never']" + ] + """ + Request ability to [capture beyond the standard authorization validity window](https://stripe.com/docs/payments/extended-authorization) for this PaymentIntent. + """ + request_incremental_authorization: NotRequired[ + "Literal['if_available', 'never']" + ] + """ + Request ability to [increment the authorization](https://stripe.com/docs/payments/incremental-authorization) for this PaymentIntent. + """ + request_multicapture: NotRequired["Literal['if_available', 'never']"] + """ + Request ability to make [multiple captures](https://stripe.com/docs/payments/multicapture) for this PaymentIntent. + """ + request_overcapture: NotRequired["Literal['if_available', 'never']"] + """ + Request ability to [overcapture](https://stripe.com/docs/payments/overcapture) for this PaymentIntent. + """ + request_three_d_secure: NotRequired[ + "Literal['any', 'automatic', 'challenge']" + ] + """ + We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + statement_descriptor_suffix_kana: NotRequired["Literal['']|str"] + """ + Provides information about a card payment that customers see on their statements. Concatenated with the Kana prefix (shortened Kana descriptor) or Kana statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 22 characters. + """ + statement_descriptor_suffix_kanji: NotRequired["Literal['']|str"] + """ + Provides information about a card payment that customers see on their statements. Concatenated with the Kanji prefix (shortened Kanji descriptor) or Kanji statement descriptor that's set on the account to form the complete statement descriptor. Maximum 17 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 17 characters. + """ + three_d_secure: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodOptionsCardThreeDSecure" + ] + """ + If 3D Secure authentication was performed with a third-party provider, + the authentication details to use for this payment. + """ + + class UpdateParamsPaymentMethodOptionsCardInstallments(TypedDict): + enabled: NotRequired["bool"] + """ + Setting to true enables installments for this PaymentIntent. + This will cause the response to contain a list of available installment plans. + Setting to false will prevent any selected plan from applying to a charge. + """ + plan: NotRequired[ + "Literal['']|PaymentIntentService.UpdateParamsPaymentMethodOptionsCardInstallmentsPlan" + ] + """ + The selected installment plan to use for this payment attempt. + This parameter can only be provided during confirmation. + """ + + class UpdateParamsPaymentMethodOptionsCardInstallmentsPlan(TypedDict): + count: int + """ + For `fixed_count` installment plans, this is the number of installment payments your customer will make to their credit card. + """ + interval: Literal["month"] + """ + For `fixed_count` installment plans, this is the interval between installment payments your customer will make to their credit card. + One of `month`. + """ + type: Literal["fixed_count"] + """ + Type of installment plan, one of `fixed_count`. + """ + + class UpdateParamsPaymentMethodOptionsCardMandateOptions(TypedDict): + amount: int + """ + Amount to be charged for future payments. + """ + amount_type: Literal["fixed", "maximum"] + """ + One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + """ + description: NotRequired["str"] + """ + A description of the mandate or subscription that is meant to be displayed to the customer. + """ + end_date: NotRequired["int"] + """ + End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + """ + interval: Literal["day", "month", "sporadic", "week", "year"] + """ + Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + """ + reference: str + """ + Unique identifier for the mandate or subscription. + """ + start_date: int + """ + Start date of the mandate or subscription. Start date should not be lesser than yesterday. + """ + supported_types: NotRequired["List[Literal['india']]"] + """ + Specifies the type of mandates supported. Possible values are `india`. + """ + + class UpdateParamsPaymentMethodOptionsCardPresent(TypedDict): + request_extended_authorization: NotRequired["bool"] + """ + Request ability to capture this payment beyond the standard [authorization validity window](https://stripe.com/docs/terminal/features/extended-authorizations#authorization-validity) + """ + request_incremental_authorization_support: NotRequired["bool"] + """ + Request ability to [increment](https://stripe.com/docs/terminal/features/incremental-authorizations) this PaymentIntent if the combination of MCC and card brand is eligible. Check [incremental_authorization_supported](https://stripe.com/docs/api/charges/object#charge_object-payment_method_details-card_present-incremental_authorization_supported) in the [Confirm](https://stripe.com/docs/api/payment_intents/confirm) response to verify support. + """ + request_incremental_authorization: NotRequired[ + "Literal['if_available', 'never']" + ] + """ + This field was released by mistake and will be removed in the next major version + """ + + class UpdateParamsPaymentMethodOptionsCardThreeDSecure(TypedDict): + ares_trans_status: NotRequired[ + "Literal['A', 'C', 'I', 'N', 'R', 'U', 'Y']" + ] + """ + The `transStatus` returned from the card Issuer's ACS in the ARes. + """ + cryptogram: str + """ + The cryptogram, also known as the "authentication value" (AAV, CAVV or + AEVV). This value is 20 bytes, base64-encoded into a 28-character string. + (Most 3D Secure providers will return the base64-encoded version, which + is what you should specify here.) + """ + electronic_commerce_indicator: NotRequired[ + "Literal['01', '02', '05', '06', '07']" + ] + """ + The Electronic Commerce Indicator (ECI) is returned by your 3D Secure + provider and indicates what degree of authentication was performed. + """ + exemption_indicator: NotRequired["Literal['low_risk', 'none']"] + """ + The exemption requested via 3DS and accepted by the issuer at authentication time. + """ + network_options: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptions" + ] + """ + Network specific 3DS fields. Network specific arguments require an + explicit card brand choice. The parameter `payment_method_options.card.network`` + must be populated accordingly + """ + requestor_challenge_indicator: NotRequired["str"] + """ + The challenge indicator (`threeDSRequestorChallengeInd`) which was requested in the + AReq sent to the card Issuer's ACS. A string containing 2 digits from 01-99. + """ + transaction_id: str + """ + For 3D Secure 1, the XID. For 3D Secure 2, the Directory Server + Transaction ID (dsTransID). + """ + version: Literal["1.0.2", "2.1.0", "2.2.0"] + """ + The version of 3D Secure that was performed. + """ + + class UpdateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptions( + TypedDict, + ): + cartes_bancaires: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancaires" + ] + """ + Cartes Bancaires-specific 3DS fields. + """ + + class UpdateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancaires( + TypedDict, + ): + cb_avalgo: Literal["0", "1", "2", "3", "4", "A"] + """ + The cryptogram calculation algorithm used by the card Issuer's ACS + to calculate the Authentication cryptogram. Also known as `cavvAlgorithm`. + messageExtension: CB-AVALGO + """ + cb_exemption: NotRequired["str"] + """ + The exemption indicator returned from Cartes Bancaires in the ARes. + message extension: CB-EXEMPTION; string (4 characters) + This is a 3 byte bitmap (low significant byte first and most significant + bit first) that has been Base64 encoded + """ + cb_score: NotRequired["int"] + """ + The risk score returned from Cartes Bancaires in the ARes. + message extension: CB-SCORE; numeric value 0-99 + """ + + class UpdateParamsPaymentMethodOptionsCashapp(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsCustomerBalance(TypedDict): + bank_transfer: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodOptionsCustomerBalanceBankTransfer" + ] + """ + Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + """ + funding_type: NotRequired["Literal['bank_transfer']"] + """ + The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsCustomerBalanceBankTransfer( + TypedDict, + ): + eu_bank_transfer: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer" + ] + """ + Configuration for the eu_bank_transfer funding type. + """ + requested_address_types: NotRequired[ + "List[Literal['aba', 'iban', 'sepa', 'sort_code', 'spei', 'swift', 'zengin']]" + ] + """ + List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. + + Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. + """ + type: Literal[ + "eu_bank_transfer", + "gb_bank_transfer", + "jp_bank_transfer", + "mx_bank_transfer", + "us_bank_transfer", + ] + """ + The list of bank transfer types that this PaymentIntent is allowed to use for funding Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + """ + + class UpdateParamsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer( + TypedDict, + ): + country: str + """ + The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + """ + + class UpdateParamsPaymentMethodOptionsEps(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsFpx(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsGiropay(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsGrabpay(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsIdeal(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsInteracPresent(TypedDict): + pass + + class UpdateParamsPaymentMethodOptionsKlarna(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + preferred_locale: NotRequired[ + "Literal['cs-CZ', 'da-DK', 'de-AT', 'de-CH', 'de-DE', 'el-GR', 'en-AT', 'en-AU', 'en-BE', 'en-CA', 'en-CH', 'en-CZ', 'en-DE', 'en-DK', 'en-ES', 'en-FI', 'en-FR', 'en-GB', 'en-GR', 'en-IE', 'en-IT', 'en-NL', 'en-NO', 'en-NZ', 'en-PL', 'en-PT', 'en-SE', 'en-US', 'es-ES', 'es-US', 'fi-FI', 'fr-BE', 'fr-CA', 'fr-CH', 'fr-FR', 'it-CH', 'it-IT', 'nb-NO', 'nl-BE', 'nl-NL', 'pl-PL', 'pt-PT', 'sv-FI', 'sv-SE']" + ] + """ + Preferred language of the Klarna authorization page that the customer is redirected to + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsKonbini(TypedDict): + confirmation_number: NotRequired["Literal['']|str"] + """ + An optional 10 to 11 digit numeric-only string determining the confirmation code at applicable convenience stores. Must not consist of only zeroes and could be rejected in case of insufficient uniqueness. We recommend to use the customer's phone number. + """ + expires_after_days: NotRequired["Literal['']|int"] + """ + The number of calendar days (between 1 and 60) after which Konbini payment instructions will expire. For example, if a PaymentIntent is confirmed with Konbini and `expires_after_days` set to 2 on Monday JST, the instructions will expire on Wednesday 23:59:59 JST. Defaults to 3 days. + """ + expires_at: NotRequired["Literal['']|int"] + """ + The timestamp at which the Konbini payment instructions will expire. Only one of `expires_after_days` or `expires_at` may be set. + """ + product_description: NotRequired["Literal['']|str"] + """ + A product descriptor of up to 22 characters, which will appear to customers at the convenience store. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsLink(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + + If provided, this parameter will override the top-level `capture_method` when finalizing the payment with this payment method type. + + If `capture_method` is already set on the PaymentIntent, providing an empty value for this parameter will unset the stored value for this payment method type. + """ + persistent_token: NotRequired["str"] + """ + [Deprecated] This is a legacy parameter that no longer has any function. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsOxxo(TypedDict): + expires_after_days: NotRequired["int"] + """ + The number of calendar days before an OXXO voucher expires. For example, if you create an OXXO voucher on Monday and you set expires_after_days to 2, the OXXO invoice will expire on Wednesday at 23:59 America/Mexico_City time. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsP24(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + tos_shown_and_accepted: NotRequired["bool"] + """ + Confirm that the payer has accepted the P24 terms and conditions. + """ + + class UpdateParamsPaymentMethodOptionsPaynow(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsPaypal(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + """ + preferred_locale: NotRequired[ + "Literal['cs-CZ', 'da-DK', 'de-AT', 'de-DE', 'de-LU', 'el-GR', 'en-GB', 'en-US', 'es-ES', 'fi-FI', 'fr-BE', 'fr-FR', 'fr-LU', 'hu-HU', 'it-IT', 'nl-BE', 'nl-NL', 'pl-PL', 'pt-PT', 'sk-SK', 'sv-SE']" + ] + """ + [Preferred locale](https://stripe.com/docs/payments/paypal/supported-locales) of the PayPal checkout page that the customer is redirected to. + """ + reference: NotRequired["str"] + """ + A reference of the PayPal transaction visible to customer which is mapped to PayPal's invoice ID. This must be a globally unique ID if you have configured in your PayPal settings to block multiple payments per invoice ID. + """ + risk_correlation_id: NotRequired["str"] + """ + The risk correlation ID for an on-session payment using a saved PayPal payment method. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsPix(TypedDict): + expires_after_seconds: NotRequired["int"] + """ + The number of seconds (between 10 and 1209600) after which Pix payment will expire. Defaults to 86400 seconds. + """ + expires_at: NotRequired["int"] + """ + The timestamp at which the Pix expires (between 10 and 1209600 seconds in the future). Defaults to 1 day in the future. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsPromptpay(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsRevolutPay(TypedDict): + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class UpdateParamsPaymentMethodOptionsSepaDebit(TypedDict): + mandate_options: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodOptionsSepaDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsSepaDebitMandateOptions(TypedDict): + pass + + class UpdateParamsPaymentMethodOptionsSofort(TypedDict): + preferred_language: NotRequired[ + "Literal['']|Literal['de', 'en', 'es', 'fr', 'it', 'nl', 'pl']" + ] + """ + Language shown to the payer on redirect. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsUsBankAccount(TypedDict): + financial_connections: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodOptionsUsBankAccountFinancialConnections" + ] + """ + Additional fields for Financial Connections Session creation + """ + mandate_options: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodOptionsUsBankAccountMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + networks: NotRequired[ + "PaymentIntentService.UpdateParamsPaymentMethodOptionsUsBankAccountNetworks" + ] + """ + Additional fields for network related functions + """ + preferred_settlement_speed: NotRequired[ + "Literal['']|Literal['fastest', 'standard']" + ] + """ + Preferred transaction settlement speed + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Bank account verification method. + """ + + class UpdateParamsPaymentMethodOptionsUsBankAccountFinancialConnections( + TypedDict, + ): + permissions: NotRequired[ + "List[Literal['balances', 'ownership', 'payment_method', 'transactions']]" + ] + """ + The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + """ + prefetch: NotRequired["List[Literal['balances', 'transactions']]"] + """ + List of data features that you would like to retrieve upon account creation. + """ + return_url: NotRequired["str"] + """ + For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + """ + + class UpdateParamsPaymentMethodOptionsUsBankAccountMandateOptions( + TypedDict, + ): + collection_method: NotRequired["Literal['']|Literal['paper']"] + """ + The method used to collect offline mandate customer acceptance. + """ + + class UpdateParamsPaymentMethodOptionsUsBankAccountNetworks(TypedDict): + requested: NotRequired["List[Literal['ach', 'us_domestic_wire']]"] + """ + Triggers validations to run across the selected networks + """ + + class UpdateParamsPaymentMethodOptionsWechatPay(TypedDict): + app_id: NotRequired["str"] + """ + The app ID registered with WeChat Pay. Only required when client is ios or android. + """ + client: Literal["android", "ios", "web"] + """ + The client type that the end customer will pay from + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsPaymentMethodOptionsZip(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class UpdateParamsShipping(TypedDict): + address: "PaymentIntentService.UpdateParamsShippingAddress" + """ + Shipping address. + """ + carrier: NotRequired["str"] + """ + The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. + """ + name: str + """ + Recipient name. + """ + phone: NotRequired["str"] + """ + Recipient phone (including extension). + """ + tracking_number: NotRequired["str"] + """ + The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. + """ + + class UpdateParamsShippingAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsTransferData(TypedDict): + amount: NotRequired["int"] + """ + The amount that will be transferred automatically when a charge succeeds. + """ + + class VerifyMicrodepositsParams(TypedDict): + amounts: NotRequired["List[int]"] + """ + Two positive integers, in *cents*, equal to the values of the microdeposits sent to the bank account. + """ + descriptor_code: NotRequired["str"] + """ + A six-character code starting with SM present in the microdeposit sent to the bank account. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "PaymentIntentService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[PaymentIntent]: + """ + Returns a list of PaymentIntents. + """ + return cast( + ListObject[PaymentIntent], + self._requestor.request( + "get", + "/v1/payment_intents", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "PaymentIntentService.CreateParams", + options: RequestOptions = {}, + ) -> PaymentIntent: + """ + Creates a PaymentIntent object. + + After the PaymentIntent is created, attach a payment method and [confirm](https://stripe.com/docs/api/payment_intents/confirm) + to continue the payment. Learn more about the available payment flows + with the Payment Intents API. + + When you use confirm=true during creation, it's equivalent to creating + and confirming the PaymentIntent in the same call. You can use any parameters + available in the [confirm API](https://stripe.com/docs/api/payment_intents/confirm) when you supply + confirm=true. + """ + return cast( + PaymentIntent, + self._requestor.request( + "post", + "/v1/payment_intents", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + intent: str, + params: "PaymentIntentService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> PaymentIntent: + """ + Retrieves the details of a PaymentIntent that has previously been created. + + You can retrieve a PaymentIntent client-side using a publishable key when the client_secret is in the query string. + + If you retrieve a PaymentIntent with a publishable key, it only returns a subset of properties. Refer to the [payment intent](https://stripe.com/docs/api#payment_intent_object) object reference for more details. + """ + return cast( + PaymentIntent, + self._requestor.request( + "get", + "/v1/payment_intents/{intent}".format( + intent=_util.sanitize_id(intent), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + intent: str, + params: "PaymentIntentService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> PaymentIntent: + """ + Updates properties on a PaymentIntent object without confirming. + + Depending on which properties you update, you might need to confirm the + PaymentIntent again. For example, updating the payment_method + always requires you to confirm the PaymentIntent again. If you prefer to + update and confirm at the same time, we recommend updating properties through + the [confirm API](https://stripe.com/docs/api/payment_intents/confirm) instead. + """ + return cast( + PaymentIntent, + self._requestor.request( + "post", + "/v1/payment_intents/{intent}".format( + intent=_util.sanitize_id(intent), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def search( + self, + params: "PaymentIntentService.SearchParams", + options: RequestOptions = {}, + ) -> SearchResultObject[PaymentIntent]: + """ + Search for PaymentIntents you've previously created using Stripe's [Search Query Language](https://stripe.com/docs/search#search-query-language). + Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating + conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up + to an hour behind during outages. Search functionality is not available to merchants in India. + """ + return cast( + SearchResultObject[PaymentIntent], + self._requestor.request( + "get", + "/v1/payment_intents/search", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def apply_customer_balance( + self, + intent: str, + params: "PaymentIntentService.ApplyCustomerBalanceParams" = {}, + options: RequestOptions = {}, + ) -> PaymentIntent: + """ + Manually reconcile the remaining amount for a customer_balance PaymentIntent. + """ + return cast( + PaymentIntent, + self._requestor.request( + "post", + "/v1/payment_intents/{intent}/apply_customer_balance".format( + intent=_util.sanitize_id(intent), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def cancel( + self, + intent: str, + params: "PaymentIntentService.CancelParams" = {}, + options: RequestOptions = {}, + ) -> PaymentIntent: + """ + You can cancel a PaymentIntent object when it's in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_action or, [in rare cases](https://stripe.com/docs/payments/intents), processing. + + After it's canceled, no additional charges are made by the PaymentIntent and any operations on the PaymentIntent fail with an error. For PaymentIntents with a status of requires_capture, the remaining amount_capturable is automatically refunded. + + You can't cancel the PaymentIntent for a Checkout Session. [Expire the Checkout Session](https://stripe.com/docs/api/checkout/sessions/expire) instead. + """ + return cast( + PaymentIntent, + self._requestor.request( + "post", + "/v1/payment_intents/{intent}/cancel".format( + intent=_util.sanitize_id(intent), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def capture( + self, + intent: str, + params: "PaymentIntentService.CaptureParams" = {}, + options: RequestOptions = {}, + ) -> PaymentIntent: + """ + Capture the funds of an existing uncaptured PaymentIntent when its status is requires_capture. + + Uncaptured PaymentIntents are cancelled a set number of days (7 by default) after their creation. + + Learn more about [separate authorization and capture](https://stripe.com/docs/payments/capture-later). + """ + return cast( + PaymentIntent, + self._requestor.request( + "post", + "/v1/payment_intents/{intent}/capture".format( + intent=_util.sanitize_id(intent), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def confirm( + self, + intent: str, + params: "PaymentIntentService.ConfirmParams" = {}, + options: RequestOptions = {}, + ) -> PaymentIntent: + """ + Confirm that your customer intends to pay with current or provided + payment method. Upon confirmation, the PaymentIntent will attempt to initiate + a payment. + If the selected payment method requires additional authentication steps, the + PaymentIntent will transition to the requires_action status and + suggest additional actions via next_action. If payment fails, + the PaymentIntent transitions to the requires_payment_method status or the + canceled status if the confirmation limit is reached. If + payment succeeds, the PaymentIntent will transition to the succeeded + status (or requires_capture, if capture_method is set to manual). + If the confirmation_method is automatic, payment may be attempted + using our [client SDKs](https://stripe.com/docs/stripe-js/reference#stripe-handle-card-payment) + and the PaymentIntent's [client_secret](https://stripe.com/docs/api#payment_intent_object-client_secret). + After next_actions are handled by the client, no additional + confirmation is required to complete the payment. + If the confirmation_method is manual, all payment attempts must be + initiated using a secret key. + If any actions are required for the payment, the PaymentIntent will + return to the requires_confirmation state + after those actions are completed. Your server needs to then + explicitly re-confirm the PaymentIntent to initiate the next payment + attempt. Read the [expanded documentation](https://stripe.com/docs/payments/payment-intents/web-manual) + to learn more about manual confirmation. + """ + return cast( + PaymentIntent, + self._requestor.request( + "post", + "/v1/payment_intents/{intent}/confirm".format( + intent=_util.sanitize_id(intent), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def increment_authorization( + self, + intent: str, + params: "PaymentIntentService.IncrementAuthorizationParams", + options: RequestOptions = {}, + ) -> PaymentIntent: + """ + Perform an incremental authorization on an eligible + [PaymentIntent](https://stripe.com/docs/api/payment_intents/object). To be eligible, the + PaymentIntent's status must be requires_capture and + [incremental_authorization_supported](https://stripe.com/docs/api/charges/object#charge_object-payment_method_details-card_present-incremental_authorization_supported) + must be true. + + Incremental authorizations attempt to increase the authorized amount on + your customer's card to the new, higher amount provided. Similar to the + initial authorization, incremental authorizations can be declined. A + single PaymentIntent can call this endpoint multiple times to further + increase the authorized amount. + + If the incremental authorization succeeds, the PaymentIntent object + returns with the updated + [amount](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-amount). + If the incremental authorization fails, a + [card_declined](https://stripe.com/docs/error-codes#card-declined) error returns, and no other + fields on the PaymentIntent or Charge update. The PaymentIntent + object remains capturable for the previously authorized amount. + + Each PaymentIntent can have a maximum of 10 incremental authorization attempts, including declines. + After it's captured, a PaymentIntent can no longer be incremented. + + Learn more about [incremental authorizations](https://stripe.com/docs/terminal/features/incremental-authorizations). + """ + return cast( + PaymentIntent, + self._requestor.request( + "post", + "/v1/payment_intents/{intent}/increment_authorization".format( + intent=_util.sanitize_id(intent), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def verify_microdeposits( + self, + intent: str, + params: "PaymentIntentService.VerifyMicrodepositsParams" = {}, + options: RequestOptions = {}, + ) -> PaymentIntent: + """ + Verifies microdeposits on a PaymentIntent object. + """ + return cast( + PaymentIntent, + self._requestor.request( + "post", + "/v1/payment_intents/{intent}/verify_microdeposits".format( + intent=_util.sanitize_id(intent), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_payment_link.py b/stripe/_payment_link.py index 2a703e367..35c77b8dd 100644 --- a/stripe/_payment_link.py +++ b/stripe/_payment_link.py @@ -2427,14 +2427,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentLink.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["PaymentLink.CreateParams"] ) -> "PaymentLink": """ Creates a payment link. @@ -2444,23 +2437,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentLink.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["PaymentLink.ListParams"] ) -> ListObject["PaymentLink"]: """ Returns a list of your payment links. @@ -2468,9 +2451,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -2486,12 +2466,7 @@ def list( def _cls_list_line_items( cls, payment_link: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentLink.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["PaymentLink.ListLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a payment link, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -2503,9 +2478,6 @@ def _cls_list_line_items( "/v1/payment_links/{payment_link}/line_items".format( payment_link=_util.sanitize_id(payment_link) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2513,13 +2485,7 @@ def _cls_list_line_items( @overload @staticmethod def list_line_items( - payment_link: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentLink.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + payment_link: str, **params: Unpack["PaymentLink.ListLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a payment link, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -2528,11 +2494,7 @@ def list_line_items( @overload def list_line_items( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentLink.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentLink.ListLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a payment link, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -2541,11 +2503,7 @@ def list_line_items( @class_method_variant("_cls_list_line_items") def list_line_items( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentLink.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentLink.ListLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a payment link, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -2557,7 +2515,6 @@ def list_line_items( # pyright: ignore[reportGeneralTypeIssues] "/v1/payment_links/{payment_link}/line_items".format( payment_link=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/_payment_link_line_item_service.py b/stripe/_payment_link_line_item_service.py new file mode 100644 index 000000000..2173dbe23 --- /dev/null +++ b/stripe/_payment_link_line_item_service.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._line_item import LineItem +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class PaymentLinkLineItemService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + def list( + self, + payment_link: str, + params: "PaymentLinkLineItemService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[LineItem]: + """ + When retrieving a payment link, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. + """ + return cast( + ListObject[LineItem], + self._requestor.request( + "get", + "/v1/payment_links/{payment_link}/line_items".format( + payment_link=_util.sanitize_id(payment_link), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_payment_link_service.py b/stripe/_payment_link_service.py new file mode 100644 index 000000000..c176cbe38 --- /dev/null +++ b/stripe/_payment_link_service.py @@ -0,0 +1,1707 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._payment_link import PaymentLink +from stripe._payment_link_line_item_service import PaymentLinkLineItemService +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class PaymentLinkService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.line_items = PaymentLinkLineItemService(self._requestor) + + class CreateParams(TypedDict): + after_completion: NotRequired[ + "PaymentLinkService.CreateParamsAfterCompletion" + ] + """ + Behavior after the purchase is complete. + """ + allow_promotion_codes: NotRequired["bool"] + """ + Enables user redeemable promotion codes. + """ + application_fee_amount: NotRequired["int"] + """ + The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. Can only be applied when there are no line items with recurring prices. + """ + application_fee_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. There must be at least 1 line item with a recurring price to use this field. + """ + automatic_tax: NotRequired[ + "PaymentLinkService.CreateParamsAutomaticTax" + ] + """ + Configuration for automatic tax collection. + """ + billing_address_collection: NotRequired["Literal['auto', 'required']"] + """ + Configuration for collecting the customer's billing address. + """ + consent_collection: NotRequired[ + "PaymentLinkService.CreateParamsConsentCollection" + ] + """ + Configure fields to gather active consent from customers. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies) and supported by each line item's price. + """ + custom_fields: NotRequired[ + "List[PaymentLinkService.CreateParamsCustomField]" + ] + """ + Collect additional information from your customer using custom fields. Up to 3 fields are supported. + """ + custom_text: NotRequired["PaymentLinkService.CreateParamsCustomText"] + """ + Display additional text for your customers using custom text. + """ + customer_creation: NotRequired["Literal['always', 'if_required']"] + """ + Configures whether [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link create a [Customer](https://stripe.com/docs/api/customers). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + inactive_message: NotRequired["str"] + """ + The custom message to be displayed to a customer when a payment link is no longer active. + """ + invoice_creation: NotRequired[ + "PaymentLinkService.CreateParamsInvoiceCreation" + ] + """ + Generate a post-purchase Invoice for one-time payments. + """ + line_items: List["PaymentLinkService.CreateParamsLineItem"] + """ + The line items representing what is being sold. Each line item represents an item being sold. Up to 20 line items are supported. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. Metadata associated with this Payment Link will automatically be copied to [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link. + """ + on_behalf_of: NotRequired["str"] + """ + The account on behalf of which to charge. + """ + payment_intent_data: NotRequired[ + "PaymentLinkService.CreateParamsPaymentIntentData" + ] + """ + A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in `payment` mode. + """ + payment_method_collection: NotRequired[ + "Literal['always', 'if_required']" + ] + """ + Specify whether Checkout should collect a payment method. When set to `if_required`, Checkout will not collect a payment method when the total due for the session is 0.This may occur if the Checkout Session includes a free trial or a discount. + + Can only be set in `subscription` mode. + + If you'd like information on how to collect a payment method outside of Checkout, read the guide on [configuring subscriptions with a free trial](https://stripe.com/docs/payments/checkout/free-trials). + """ + payment_method_types: NotRequired[ + "List[Literal['affirm', 'afterpay_clearpay', 'alipay', 'au_becs_debit', 'bacs_debit', 'bancontact', 'blik', 'boleto', 'card', 'cashapp', 'eps', 'fpx', 'giropay', 'grabpay', 'ideal', 'klarna', 'konbini', 'link', 'oxxo', 'p24', 'paynow', 'paypal', 'pix', 'promptpay', 'sepa_debit', 'sofort', 'us_bank_account', 'wechat_pay']]" + ] + """ + The list of payment method types that customers can use. If no value is passed, Stripe will dynamically show relevant payment methods from your [payment method settings](https://dashboard.stripe.com/settings/payment_methods) (20+ payment methods [supported](https://stripe.com/docs/payments/payment-methods/integration-options#payment-method-product-support)). + """ + phone_number_collection: NotRequired[ + "PaymentLinkService.CreateParamsPhoneNumberCollection" + ] + """ + Controls phone number collection settings during checkout. + + We recommend that you review your privacy policy and check with your legal contacts. + """ + restrictions: NotRequired[ + "PaymentLinkService.CreateParamsRestrictions" + ] + """ + Settings that restrict the usage of a payment link. + """ + shipping_address_collection: NotRequired[ + "PaymentLinkService.CreateParamsShippingAddressCollection" + ] + """ + Configuration for collecting the customer's shipping address. + """ + shipping_options: NotRequired[ + "List[PaymentLinkService.CreateParamsShippingOption]" + ] + """ + The shipping rate options to apply to [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link. + """ + submit_type: NotRequired["Literal['auto', 'book', 'donate', 'pay']"] + """ + Describes the type of transaction being performed in order to customize relevant text on the page, such as the submit button. Changing this value will also affect the hostname in the [url](https://stripe.com/docs/api/payment_links/payment_links/object#url) property (example: `donate.stripe.com`). + """ + subscription_data: NotRequired[ + "PaymentLinkService.CreateParamsSubscriptionData" + ] + """ + When creating a subscription, the specified configuration data will be used. There must be at least one line item with a recurring price to use `subscription_data`. + """ + tax_id_collection: NotRequired[ + "PaymentLinkService.CreateParamsTaxIdCollection" + ] + """ + Controls tax ID collection during checkout. + """ + transfer_data: NotRequired[ + "PaymentLinkService.CreateParamsTransferData" + ] + """ + The account (if any) the payments will be attributed to for tax reporting, and where funds from each payment will be transferred to. + """ + + class CreateParamsAfterCompletion(TypedDict): + hosted_confirmation: NotRequired[ + "PaymentLinkService.CreateParamsAfterCompletionHostedConfirmation" + ] + """ + Configuration when `type=hosted_confirmation`. + """ + redirect: NotRequired[ + "PaymentLinkService.CreateParamsAfterCompletionRedirect" + ] + """ + Configuration when `type=redirect`. + """ + type: Literal["hosted_confirmation", "redirect"] + """ + The specified behavior after the purchase is complete. Either `redirect` or `hosted_confirmation`. + """ + + class CreateParamsAfterCompletionHostedConfirmation(TypedDict): + custom_message: NotRequired["str"] + """ + A custom message to display to the customer after the purchase is complete. + """ + + class CreateParamsAfterCompletionRedirect(TypedDict): + url: str + """ + The URL the customer will be redirected to after the purchase is complete. You can embed `{CHECKOUT_SESSION_ID}` into the URL to have the `id` of the completed [checkout session](https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-id) included. + """ + + class CreateParamsAutomaticTax(TypedDict): + enabled: bool + """ + If `true`, tax will be calculated automatically using the customer's location. + """ + liability: NotRequired[ + "PaymentLinkService.CreateParamsAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class CreateParamsAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsConsentCollection(TypedDict): + payment_method_reuse_agreement: NotRequired[ + "PaymentLinkService.CreateParamsConsentCollectionPaymentMethodReuseAgreement" + ] + """ + Determines the display of payment method reuse agreement text in the UI. If set to `hidden`, it will hide legal text related to the reuse of a payment method. + """ + promotions: NotRequired["Literal['auto', 'none']"] + """ + If set to `auto`, enables the collection of customer consent for promotional communications. The Checkout + Session will determine whether to display an option to opt into promotional communication + from the merchant depending on the customer's locale. Only available to US merchants. + """ + terms_of_service: NotRequired["Literal['none', 'required']"] + """ + If set to `required`, it requires customers to check a terms of service checkbox before being able to pay. + There must be a valid terms of service URL set in your [Dashboard settings](https://dashboard.stripe.com/settings/public). + """ + + class CreateParamsConsentCollectionPaymentMethodReuseAgreement(TypedDict): + position: Literal["auto", "hidden"] + """ + Determines the position and visibility of the payment method reuse agreement in the UI. When set to `auto`, Stripe's + defaults will be used. When set to `hidden`, the payment method reuse agreement text will always be hidden in the UI. + """ + + class CreateParamsCustomField(TypedDict): + dropdown: NotRequired[ + "PaymentLinkService.CreateParamsCustomFieldDropdown" + ] + """ + Configuration for `type=dropdown` fields. + """ + key: str + """ + String of your choice that your integration can use to reconcile this field. Must be unique to this field, alphanumeric, and up to 200 characters. + """ + label: "PaymentLinkService.CreateParamsCustomFieldLabel" + """ + The label for the field, displayed to the customer. + """ + numeric: NotRequired[ + "PaymentLinkService.CreateParamsCustomFieldNumeric" + ] + """ + Configuration for `type=numeric` fields. + """ + optional: NotRequired["bool"] + """ + Whether the customer is required to complete the field before completing the Checkout Session. Defaults to `false`. + """ + text: NotRequired["PaymentLinkService.CreateParamsCustomFieldText"] + """ + Configuration for `type=text` fields. + """ + type: Literal["dropdown", "numeric", "text"] + """ + The type of the field. + """ + + class CreateParamsCustomFieldDropdown(TypedDict): + options: List[ + "PaymentLinkService.CreateParamsCustomFieldDropdownOption" + ] + """ + The options available for the customer to select. Up to 200 options allowed. + """ + + class CreateParamsCustomFieldDropdownOption(TypedDict): + label: str + """ + The label for the option, displayed to the customer. Up to 100 characters. + """ + value: str + """ + The value for this option, not displayed to the customer, used by your integration to reconcile the option selected by the customer. Must be unique to this option, alphanumeric, and up to 100 characters. + """ + + class CreateParamsCustomFieldLabel(TypedDict): + custom: str + """ + Custom text for the label, displayed to the customer. Up to 50 characters. + """ + type: Literal["custom"] + """ + The type of the label. + """ + + class CreateParamsCustomFieldNumeric(TypedDict): + maximum_length: NotRequired["int"] + """ + The maximum character length constraint for the customer's input. + """ + minimum_length: NotRequired["int"] + """ + The minimum character length requirement for the customer's input. + """ + + class CreateParamsCustomFieldText(TypedDict): + maximum_length: NotRequired["int"] + """ + The maximum character length constraint for the customer's input. + """ + minimum_length: NotRequired["int"] + """ + The minimum character length requirement for the customer's input. + """ + + class CreateParamsCustomText(TypedDict): + after_submit: NotRequired[ + "Literal['']|PaymentLinkService.CreateParamsCustomTextAfterSubmit" + ] + """ + Custom text that should be displayed after the payment confirmation button. + """ + shipping_address: NotRequired[ + "Literal['']|PaymentLinkService.CreateParamsCustomTextShippingAddress" + ] + """ + Custom text that should be displayed alongside shipping address collection. + """ + submit: NotRequired[ + "Literal['']|PaymentLinkService.CreateParamsCustomTextSubmit" + ] + """ + Custom text that should be displayed alongside the payment confirmation button. + """ + terms_of_service_acceptance: NotRequired[ + "Literal['']|PaymentLinkService.CreateParamsCustomTextTermsOfServiceAcceptance" + ] + """ + Custom text that should be displayed in place of the default terms of service agreement text. + """ + + class CreateParamsCustomTextAfterSubmit(TypedDict): + message: str + """ + Text may be up to 1200 characters in length. + """ + + class CreateParamsCustomTextShippingAddress(TypedDict): + message: str + """ + Text may be up to 1200 characters in length. + """ + + class CreateParamsCustomTextSubmit(TypedDict): + message: str + """ + Text may be up to 1200 characters in length. + """ + + class CreateParamsCustomTextTermsOfServiceAcceptance(TypedDict): + message: str + """ + Text may be up to 1200 characters in length. + """ + + class CreateParamsInvoiceCreation(TypedDict): + enabled: bool + """ + Whether the feature is enabled + """ + invoice_data: NotRequired[ + "PaymentLinkService.CreateParamsInvoiceCreationInvoiceData" + ] + """ + Invoice PDF configuration. + """ + + class CreateParamsInvoiceCreationInvoiceData(TypedDict): + account_tax_ids: NotRequired["Literal['']|List[str]"] + """ + The account tax IDs associated with the invoice. + """ + custom_fields: NotRequired[ + "Literal['']|List[PaymentLinkService.CreateParamsInvoiceCreationInvoiceDataCustomField]" + ] + """ + Default custom fields to be displayed on invoices for this customer. + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + footer: NotRequired["str"] + """ + Default footer to be displayed on invoices for this customer. + """ + issuer: NotRequired[ + "PaymentLinkService.CreateParamsInvoiceCreationInvoiceDataIssuer" + ] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + rendering_options: NotRequired[ + "Literal['']|PaymentLinkService.CreateParamsInvoiceCreationInvoiceDataRenderingOptions" + ] + """ + Default options for invoice PDF rendering for this customer. + """ + + class CreateParamsInvoiceCreationInvoiceDataCustomField(TypedDict): + name: str + """ + The name of the custom field. This may be up to 30 characters. + """ + value: str + """ + The value of the custom field. This may be up to 30 characters. + """ + + class CreateParamsInvoiceCreationInvoiceDataIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsInvoiceCreationInvoiceDataRenderingOptions(TypedDict): + amount_tax_display: NotRequired[ + "Literal['']|Literal['exclude_tax', 'include_inclusive_tax']" + ] + """ + How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + """ + + class CreateParamsLineItem(TypedDict): + adjustable_quantity: NotRequired[ + "PaymentLinkService.CreateParamsLineItemAdjustableQuantity" + ] + """ + When set, provides configuration for this item's quantity to be adjusted by the customer during checkout. + """ + price: str + """ + The ID of the [Price](https://stripe.com/docs/api/prices) or [Plan](https://stripe.com/docs/api/plans) object. + """ + quantity: int + """ + The quantity of the line item being purchased. + """ + + class CreateParamsLineItemAdjustableQuantity(TypedDict): + enabled: bool + """ + Set to true if the quantity can be adjusted to any non-negative Integer. + """ + maximum: NotRequired["int"] + """ + The maximum quantity the customer can purchase. By default this value is 99. You can specify a value up to 999. + """ + minimum: NotRequired["int"] + """ + The minimum quantity the customer can purchase. By default this value is 0. If there is only one item in the cart then that item's quantity cannot go down to 0. + """ + + class CreateParamsPaymentIntentData(TypedDict): + capture_method: NotRequired[ + "Literal['automatic', 'automatic_async', 'manual']" + ] + """ + Controls when the funds will be captured from the customer's account. + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will declaratively set metadata on [Payment Intents](https://stripe.com/docs/api/payment_intents) generated from this payment link. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + """ + setup_future_usage: NotRequired["Literal['off_session', 'on_session']"] + """ + Indicates that you intend to [make future payments](https://stripe.com/docs/payments/payment-intents#future-usage) with the payment method collected by this Checkout Session. + + When setting this to `on_session`, Checkout will show a notice to the customer that their payment details will be saved. + + When setting this to `off_session`, Checkout will show a notice to the customer that their payment details will be saved and used for future payments. + + If a Customer has been provided or Checkout creates a new Customer,Checkout will attach the payment method to the Customer. + + If Checkout does not create a Customer, the payment method is not attached to a Customer. To reuse the payment method, you can retrieve it from the Checkout Session's PaymentIntent. + + When processing card payments, Checkout also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as SCA. + """ + statement_descriptor: NotRequired["str"] + """ + Extra information about the payment. This will appear on your customer's statement when this payment succeeds in creating a charge. + """ + statement_descriptor_suffix: NotRequired["str"] + """ + Provides information about the charge that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. + """ + transfer_group: NotRequired["str"] + """ + A string that identifies the resulting payment as part of a group. See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/connect/separate-charges-and-transfers) for details. + """ + + class CreateParamsPhoneNumberCollection(TypedDict): + enabled: bool + """ + Set to `true` to enable phone number collection. + """ + + class CreateParamsRestrictions(TypedDict): + completed_sessions: "PaymentLinkService.CreateParamsRestrictionsCompletedSessions" + """ + Configuration for the `completed_sessions` restriction type. + """ + + class CreateParamsRestrictionsCompletedSessions(TypedDict): + limit: int + """ + The maximum number of checkout sessions that can be completed for the `completed_sessions` restriction to be met. + """ + + class CreateParamsShippingAddressCollection(TypedDict): + allowed_countries: List[ + Literal[ + "AC", + "AD", + "AE", + "AF", + "AG", + "AI", + "AL", + "AM", + "AO", + "AQ", + "AR", + "AT", + "AU", + "AW", + "AX", + "AZ", + "BA", + "BB", + "BD", + "BE", + "BF", + "BG", + "BH", + "BI", + "BJ", + "BL", + "BM", + "BN", + "BO", + "BQ", + "BR", + "BS", + "BT", + "BV", + "BW", + "BY", + "BZ", + "CA", + "CD", + "CF", + "CG", + "CH", + "CI", + "CK", + "CL", + "CM", + "CN", + "CO", + "CR", + "CV", + "CW", + "CY", + "CZ", + "DE", + "DJ", + "DK", + "DM", + "DO", + "DZ", + "EC", + "EE", + "EG", + "EH", + "ER", + "ES", + "ET", + "FI", + "FJ", + "FK", + "FO", + "FR", + "GA", + "GB", + "GD", + "GE", + "GF", + "GG", + "GH", + "GI", + "GL", + "GM", + "GN", + "GP", + "GQ", + "GR", + "GS", + "GT", + "GU", + "GW", + "GY", + "HK", + "HN", + "HR", + "HT", + "HU", + "ID", + "IE", + "IL", + "IM", + "IN", + "IO", + "IQ", + "IS", + "IT", + "JE", + "JM", + "JO", + "JP", + "KE", + "KG", + "KH", + "KI", + "KM", + "KN", + "KR", + "KW", + "KY", + "KZ", + "LA", + "LB", + "LC", + "LI", + "LK", + "LR", + "LS", + "LT", + "LU", + "LV", + "LY", + "MA", + "MC", + "MD", + "ME", + "MF", + "MG", + "MK", + "ML", + "MM", + "MN", + "MO", + "MQ", + "MR", + "MS", + "MT", + "MU", + "MV", + "MW", + "MX", + "MY", + "MZ", + "NA", + "NC", + "NE", + "NG", + "NI", + "NL", + "NO", + "NP", + "NR", + "NU", + "NZ", + "OM", + "PA", + "PE", + "PF", + "PG", + "PH", + "PK", + "PL", + "PM", + "PN", + "PR", + "PS", + "PT", + "PY", + "QA", + "RE", + "RO", + "RS", + "RU", + "RW", + "SA", + "SB", + "SC", + "SE", + "SG", + "SH", + "SI", + "SJ", + "SK", + "SL", + "SM", + "SN", + "SO", + "SR", + "SS", + "ST", + "SV", + "SX", + "SZ", + "TA", + "TC", + "TD", + "TF", + "TG", + "TH", + "TJ", + "TK", + "TL", + "TM", + "TN", + "TO", + "TR", + "TT", + "TV", + "TW", + "TZ", + "UA", + "UG", + "US", + "UY", + "UZ", + "VA", + "VC", + "VE", + "VG", + "VN", + "VU", + "WF", + "WS", + "XK", + "YE", + "YT", + "ZA", + "ZM", + "ZW", + "ZZ", + ] + ] + """ + An array of two-letter ISO country codes representing which countries Checkout should provide as options for + shipping locations. Unsupported country codes: `AS, CX, CC, CU, HM, IR, KP, MH, FM, NF, MP, PW, SD, SY, UM, VI`. + """ + + class CreateParamsShippingOption(TypedDict): + shipping_rate: NotRequired["str"] + """ + The ID of the Shipping Rate to use for this shipping option. + """ + + class CreateParamsSubscriptionData(TypedDict): + description: NotRequired["str"] + """ + The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + """ + invoice_settings: NotRequired[ + "PaymentLinkService.CreateParamsSubscriptionDataInvoiceSettings" + ] + """ + All invoices will be billed using the specified settings. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will declaratively set metadata on [Subscriptions](https://stripe.com/docs/api/subscriptions) generated from this payment link. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + """ + trial_period_days: NotRequired["int"] + """ + Integer representing the number of trial period days before the customer is charged for the first time. Has to be at least 1. + """ + trial_settings: NotRequired[ + "PaymentLinkService.CreateParamsSubscriptionDataTrialSettings" + ] + """ + Settings related to subscription trials. + """ + + class CreateParamsSubscriptionDataInvoiceSettings(TypedDict): + issuer: NotRequired[ + "PaymentLinkService.CreateParamsSubscriptionDataInvoiceSettingsIssuer" + ] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + + class CreateParamsSubscriptionDataInvoiceSettingsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsSubscriptionDataTrialSettings(TypedDict): + end_behavior: "PaymentLinkService.CreateParamsSubscriptionDataTrialSettingsEndBehavior" + """ + Defines how the subscription should behave when the user's free trial ends. + """ + + class CreateParamsSubscriptionDataTrialSettingsEndBehavior(TypedDict): + missing_payment_method: Literal["cancel", "create_invoice", "pause"] + """ + Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + """ + + class CreateParamsTaxIdCollection(TypedDict): + enabled: bool + """ + Set to `true` to enable tax ID collection. + """ + + class CreateParamsTransferData(TypedDict): + amount: NotRequired["int"] + """ + The amount that will be transferred automatically when a charge succeeds. + """ + destination: str + """ + If specified, successful charges will be attributed to the destination + account for tax reporting, and the funds from charges will be transferred + to the destination account. The ID of the resulting transfer will be + returned on the successful charge's `transfer` field. + """ + + class ListParams(TypedDict): + active: NotRequired["bool"] + """ + Only return payment links that are active or inactive (e.g., pass `false` to list all inactive payment links). + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + active: NotRequired["bool"] + """ + Whether the payment link's `url` is active. If `false`, customers visiting the URL will be shown a page saying that the link has been deactivated. + """ + after_completion: NotRequired[ + "PaymentLinkService.UpdateParamsAfterCompletion" + ] + """ + Behavior after the purchase is complete. + """ + allow_promotion_codes: NotRequired["bool"] + """ + Enables user redeemable promotion codes. + """ + automatic_tax: NotRequired[ + "PaymentLinkService.UpdateParamsAutomaticTax" + ] + """ + Configuration for automatic tax collection. + """ + billing_address_collection: NotRequired["Literal['auto', 'required']"] + """ + Configuration for collecting the customer's billing address. + """ + custom_fields: NotRequired[ + "Literal['']|List[PaymentLinkService.UpdateParamsCustomField]" + ] + """ + Collect additional information from your customer using custom fields. Up to 3 fields are supported. + """ + custom_text: NotRequired["PaymentLinkService.UpdateParamsCustomText"] + """ + Display additional text for your customers using custom text. + """ + customer_creation: NotRequired["Literal['always', 'if_required']"] + """ + Configures whether [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link create a [Customer](https://stripe.com/docs/api/customers). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + inactive_message: NotRequired["Literal['']|str"] + """ + The custom message to be displayed to a customer when a payment link is no longer active. + """ + invoice_creation: NotRequired[ + "PaymentLinkService.UpdateParamsInvoiceCreation" + ] + """ + Generate a post-purchase Invoice for one-time payments. + """ + line_items: NotRequired[ + "List[PaymentLinkService.UpdateParamsLineItem]" + ] + """ + The line items representing what is being sold. Each line item represents an item being sold. Up to 20 line items are supported. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. Metadata associated with this Payment Link will automatically be copied to [checkout sessions](https://stripe.com/docs/api/checkout/sessions) created by this payment link. + """ + payment_intent_data: NotRequired[ + "PaymentLinkService.UpdateParamsPaymentIntentData" + ] + """ + A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in `payment` mode. + """ + payment_method_collection: NotRequired[ + "Literal['always', 'if_required']" + ] + """ + Specify whether Checkout should collect a payment method. When set to `if_required`, Checkout will not collect a payment method when the total due for the session is 0.This may occur if the Checkout Session includes a free trial or a discount. + + Can only be set in `subscription` mode. + + If you'd like information on how to collect a payment method outside of Checkout, read the guide on [configuring subscriptions with a free trial](https://stripe.com/docs/payments/checkout/free-trials). + """ + payment_method_types: NotRequired[ + "Literal['']|List[Literal['affirm', 'afterpay_clearpay', 'alipay', 'au_becs_debit', 'bacs_debit', 'bancontact', 'blik', 'boleto', 'card', 'cashapp', 'eps', 'fpx', 'giropay', 'grabpay', 'ideal', 'klarna', 'konbini', 'link', 'oxxo', 'p24', 'paynow', 'paypal', 'pix', 'promptpay', 'sepa_debit', 'sofort', 'us_bank_account', 'wechat_pay']]" + ] + """ + The list of payment method types that customers can use. Pass an empty string to enable dynamic payment methods that use your [payment method settings](https://dashboard.stripe.com/settings/payment_methods). + """ + restrictions: NotRequired[ + "Literal['']|PaymentLinkService.UpdateParamsRestrictions" + ] + """ + Settings that restrict the usage of a payment link. + """ + shipping_address_collection: NotRequired[ + "Literal['']|PaymentLinkService.UpdateParamsShippingAddressCollection" + ] + """ + Configuration for collecting the customer's shipping address. + """ + subscription_data: NotRequired[ + "PaymentLinkService.UpdateParamsSubscriptionData" + ] + """ + When creating a subscription, the specified configuration data will be used. There must be at least one line item with a recurring price to use `subscription_data`. + """ + + class UpdateParamsAfterCompletion(TypedDict): + hosted_confirmation: NotRequired[ + "PaymentLinkService.UpdateParamsAfterCompletionHostedConfirmation" + ] + """ + Configuration when `type=hosted_confirmation`. + """ + redirect: NotRequired[ + "PaymentLinkService.UpdateParamsAfterCompletionRedirect" + ] + """ + Configuration when `type=redirect`. + """ + type: Literal["hosted_confirmation", "redirect"] + """ + The specified behavior after the purchase is complete. Either `redirect` or `hosted_confirmation`. + """ + + class UpdateParamsAfterCompletionHostedConfirmation(TypedDict): + custom_message: NotRequired["str"] + """ + A custom message to display to the customer after the purchase is complete. + """ + + class UpdateParamsAfterCompletionRedirect(TypedDict): + url: str + """ + The URL the customer will be redirected to after the purchase is complete. You can embed `{CHECKOUT_SESSION_ID}` into the URL to have the `id` of the completed [checkout session](https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-id) included. + """ + + class UpdateParamsAutomaticTax(TypedDict): + enabled: bool + """ + If `true`, tax will be calculated automatically using the customer's location. + """ + liability: NotRequired[ + "PaymentLinkService.UpdateParamsAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class UpdateParamsAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpdateParamsCustomField(TypedDict): + dropdown: NotRequired[ + "PaymentLinkService.UpdateParamsCustomFieldDropdown" + ] + """ + Configuration for `type=dropdown` fields. + """ + key: str + """ + String of your choice that your integration can use to reconcile this field. Must be unique to this field, alphanumeric, and up to 200 characters. + """ + label: "PaymentLinkService.UpdateParamsCustomFieldLabel" + """ + The label for the field, displayed to the customer. + """ + numeric: NotRequired[ + "PaymentLinkService.UpdateParamsCustomFieldNumeric" + ] + """ + Configuration for `type=numeric` fields. + """ + optional: NotRequired["bool"] + """ + Whether the customer is required to complete the field before completing the Checkout Session. Defaults to `false`. + """ + text: NotRequired["PaymentLinkService.UpdateParamsCustomFieldText"] + """ + Configuration for `type=text` fields. + """ + type: Literal["dropdown", "numeric", "text"] + """ + The type of the field. + """ + + class UpdateParamsCustomFieldDropdown(TypedDict): + options: List[ + "PaymentLinkService.UpdateParamsCustomFieldDropdownOption" + ] + """ + The options available for the customer to select. Up to 200 options allowed. + """ + + class UpdateParamsCustomFieldDropdownOption(TypedDict): + label: str + """ + The label for the option, displayed to the customer. Up to 100 characters. + """ + value: str + """ + The value for this option, not displayed to the customer, used by your integration to reconcile the option selected by the customer. Must be unique to this option, alphanumeric, and up to 100 characters. + """ + + class UpdateParamsCustomFieldLabel(TypedDict): + custom: str + """ + Custom text for the label, displayed to the customer. Up to 50 characters. + """ + type: Literal["custom"] + """ + The type of the label. + """ + + class UpdateParamsCustomFieldNumeric(TypedDict): + maximum_length: NotRequired["int"] + """ + The maximum character length constraint for the customer's input. + """ + minimum_length: NotRequired["int"] + """ + The minimum character length requirement for the customer's input. + """ + + class UpdateParamsCustomFieldText(TypedDict): + maximum_length: NotRequired["int"] + """ + The maximum character length constraint for the customer's input. + """ + minimum_length: NotRequired["int"] + """ + The minimum character length requirement for the customer's input. + """ + + class UpdateParamsCustomText(TypedDict): + after_submit: NotRequired[ + "Literal['']|PaymentLinkService.UpdateParamsCustomTextAfterSubmit" + ] + """ + Custom text that should be displayed after the payment confirmation button. + """ + shipping_address: NotRequired[ + "Literal['']|PaymentLinkService.UpdateParamsCustomTextShippingAddress" + ] + """ + Custom text that should be displayed alongside shipping address collection. + """ + submit: NotRequired[ + "Literal['']|PaymentLinkService.UpdateParamsCustomTextSubmit" + ] + """ + Custom text that should be displayed alongside the payment confirmation button. + """ + terms_of_service_acceptance: NotRequired[ + "Literal['']|PaymentLinkService.UpdateParamsCustomTextTermsOfServiceAcceptance" + ] + """ + Custom text that should be displayed in place of the default terms of service agreement text. + """ + + class UpdateParamsCustomTextAfterSubmit(TypedDict): + message: str + """ + Text may be up to 1200 characters in length. + """ + + class UpdateParamsCustomTextShippingAddress(TypedDict): + message: str + """ + Text may be up to 1200 characters in length. + """ + + class UpdateParamsCustomTextSubmit(TypedDict): + message: str + """ + Text may be up to 1200 characters in length. + """ + + class UpdateParamsCustomTextTermsOfServiceAcceptance(TypedDict): + message: str + """ + Text may be up to 1200 characters in length. + """ + + class UpdateParamsInvoiceCreation(TypedDict): + enabled: bool + """ + Whether the feature is enabled + """ + invoice_data: NotRequired[ + "PaymentLinkService.UpdateParamsInvoiceCreationInvoiceData" + ] + """ + Invoice PDF configuration. + """ + + class UpdateParamsInvoiceCreationInvoiceData(TypedDict): + account_tax_ids: NotRequired["Literal['']|List[str]"] + """ + The account tax IDs associated with the invoice. + """ + custom_fields: NotRequired[ + "Literal['']|List[PaymentLinkService.UpdateParamsInvoiceCreationInvoiceDataCustomField]" + ] + """ + Default custom fields to be displayed on invoices for this customer. + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + footer: NotRequired["str"] + """ + Default footer to be displayed on invoices for this customer. + """ + issuer: NotRequired[ + "PaymentLinkService.UpdateParamsInvoiceCreationInvoiceDataIssuer" + ] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + rendering_options: NotRequired[ + "Literal['']|PaymentLinkService.UpdateParamsInvoiceCreationInvoiceDataRenderingOptions" + ] + """ + Default options for invoice PDF rendering for this customer. + """ + + class UpdateParamsInvoiceCreationInvoiceDataCustomField(TypedDict): + name: str + """ + The name of the custom field. This may be up to 30 characters. + """ + value: str + """ + The value of the custom field. This may be up to 30 characters. + """ + + class UpdateParamsInvoiceCreationInvoiceDataIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpdateParamsInvoiceCreationInvoiceDataRenderingOptions(TypedDict): + amount_tax_display: NotRequired[ + "Literal['']|Literal['exclude_tax', 'include_inclusive_tax']" + ] + """ + How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + """ + + class UpdateParamsLineItem(TypedDict): + adjustable_quantity: NotRequired[ + "PaymentLinkService.UpdateParamsLineItemAdjustableQuantity" + ] + """ + When set, provides configuration for this item's quantity to be adjusted by the customer during checkout. + """ + id: str + """ + The ID of an existing line item on the payment link. + """ + quantity: NotRequired["int"] + """ + The quantity of the line item being purchased. + """ + + class UpdateParamsLineItemAdjustableQuantity(TypedDict): + enabled: bool + """ + Set to true if the quantity can be adjusted to any non-negative Integer. + """ + maximum: NotRequired["int"] + """ + The maximum quantity the customer can purchase. By default this value is 99. You can specify a value up to 999. + """ + minimum: NotRequired["int"] + """ + The minimum quantity the customer can purchase. By default this value is 0. If there is only one item in the cart then that item's quantity cannot go down to 0. + """ + + class UpdateParamsPaymentIntentData(TypedDict): + description: NotRequired["Literal['']|str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will declaratively set metadata on [Payment Intents](https://stripe.com/docs/api/payment_intents) generated from this payment link. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + """ + statement_descriptor: NotRequired["Literal['']|str"] + """ + Extra information about the payment. This will appear on your customer's statement when this payment succeeds in creating a charge. + """ + statement_descriptor_suffix: NotRequired["Literal['']|str"] + """ + Provides information about the charge that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. + """ + transfer_group: NotRequired["Literal['']|str"] + """ + A string that identifies the resulting payment as part of a group. See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/connect/separate-charges-and-transfers) for details. + """ + + class UpdateParamsRestrictions(TypedDict): + completed_sessions: "PaymentLinkService.UpdateParamsRestrictionsCompletedSessions" + """ + Configuration for the `completed_sessions` restriction type. + """ + + class UpdateParamsRestrictionsCompletedSessions(TypedDict): + limit: int + """ + The maximum number of checkout sessions that can be completed for the `completed_sessions` restriction to be met. + """ + + class UpdateParamsShippingAddressCollection(TypedDict): + allowed_countries: List[ + Literal[ + "AC", + "AD", + "AE", + "AF", + "AG", + "AI", + "AL", + "AM", + "AO", + "AQ", + "AR", + "AT", + "AU", + "AW", + "AX", + "AZ", + "BA", + "BB", + "BD", + "BE", + "BF", + "BG", + "BH", + "BI", + "BJ", + "BL", + "BM", + "BN", + "BO", + "BQ", + "BR", + "BS", + "BT", + "BV", + "BW", + "BY", + "BZ", + "CA", + "CD", + "CF", + "CG", + "CH", + "CI", + "CK", + "CL", + "CM", + "CN", + "CO", + "CR", + "CV", + "CW", + "CY", + "CZ", + "DE", + "DJ", + "DK", + "DM", + "DO", + "DZ", + "EC", + "EE", + "EG", + "EH", + "ER", + "ES", + "ET", + "FI", + "FJ", + "FK", + "FO", + "FR", + "GA", + "GB", + "GD", + "GE", + "GF", + "GG", + "GH", + "GI", + "GL", + "GM", + "GN", + "GP", + "GQ", + "GR", + "GS", + "GT", + "GU", + "GW", + "GY", + "HK", + "HN", + "HR", + "HT", + "HU", + "ID", + "IE", + "IL", + "IM", + "IN", + "IO", + "IQ", + "IS", + "IT", + "JE", + "JM", + "JO", + "JP", + "KE", + "KG", + "KH", + "KI", + "KM", + "KN", + "KR", + "KW", + "KY", + "KZ", + "LA", + "LB", + "LC", + "LI", + "LK", + "LR", + "LS", + "LT", + "LU", + "LV", + "LY", + "MA", + "MC", + "MD", + "ME", + "MF", + "MG", + "MK", + "ML", + "MM", + "MN", + "MO", + "MQ", + "MR", + "MS", + "MT", + "MU", + "MV", + "MW", + "MX", + "MY", + "MZ", + "NA", + "NC", + "NE", + "NG", + "NI", + "NL", + "NO", + "NP", + "NR", + "NU", + "NZ", + "OM", + "PA", + "PE", + "PF", + "PG", + "PH", + "PK", + "PL", + "PM", + "PN", + "PR", + "PS", + "PT", + "PY", + "QA", + "RE", + "RO", + "RS", + "RU", + "RW", + "SA", + "SB", + "SC", + "SE", + "SG", + "SH", + "SI", + "SJ", + "SK", + "SL", + "SM", + "SN", + "SO", + "SR", + "SS", + "ST", + "SV", + "SX", + "SZ", + "TA", + "TC", + "TD", + "TF", + "TG", + "TH", + "TJ", + "TK", + "TL", + "TM", + "TN", + "TO", + "TR", + "TT", + "TV", + "TW", + "TZ", + "UA", + "UG", + "US", + "UY", + "UZ", + "VA", + "VC", + "VE", + "VG", + "VN", + "VU", + "WF", + "WS", + "XK", + "YE", + "YT", + "ZA", + "ZM", + "ZW", + "ZZ", + ] + ] + """ + An array of two-letter ISO country codes representing which countries Checkout should provide as options for + shipping locations. Unsupported country codes: `AS, CX, CC, CU, HM, IR, KP, MH, FM, NF, MP, PW, SD, SY, UM, VI`. + """ + + class UpdateParamsSubscriptionData(TypedDict): + invoice_settings: NotRequired[ + "PaymentLinkService.UpdateParamsSubscriptionDataInvoiceSettings" + ] + """ + All invoices will be billed using the specified settings. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will declaratively set metadata on [Subscriptions](https://stripe.com/docs/api/subscriptions) generated from this payment link. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + """ + trial_settings: NotRequired[ + "Literal['']|PaymentLinkService.UpdateParamsSubscriptionDataTrialSettings" + ] + """ + Settings related to subscription trials. + """ + + class UpdateParamsSubscriptionDataInvoiceSettings(TypedDict): + issuer: NotRequired[ + "PaymentLinkService.UpdateParamsSubscriptionDataInvoiceSettingsIssuer" + ] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + + class UpdateParamsSubscriptionDataInvoiceSettingsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpdateParamsSubscriptionDataTrialSettings(TypedDict): + end_behavior: "PaymentLinkService.UpdateParamsSubscriptionDataTrialSettingsEndBehavior" + """ + Defines how the subscription should behave when the user's free trial ends. + """ + + class UpdateParamsSubscriptionDataTrialSettingsEndBehavior(TypedDict): + missing_payment_method: Literal["cancel", "create_invoice", "pause"] + """ + Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + """ + + def list( + self, + params: "PaymentLinkService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[PaymentLink]: + """ + Returns a list of your payment links. + """ + return cast( + ListObject[PaymentLink], + self._requestor.request( + "get", + "/v1/payment_links", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "PaymentLinkService.CreateParams", + options: RequestOptions = {}, + ) -> PaymentLink: + """ + Creates a payment link. + """ + return cast( + PaymentLink, + self._requestor.request( + "post", + "/v1/payment_links", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + payment_link: str, + params: "PaymentLinkService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> PaymentLink: + """ + Retrieve a payment link. + """ + return cast( + PaymentLink, + self._requestor.request( + "get", + "/v1/payment_links/{payment_link}".format( + payment_link=_util.sanitize_id(payment_link), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + payment_link: str, + params: "PaymentLinkService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> PaymentLink: + """ + Updates a payment link. + """ + return cast( + PaymentLink, + self._requestor.request( + "post", + "/v1/payment_links/{payment_link}".format( + payment_link=_util.sanitize_id(payment_link), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_payment_method.py b/stripe/_payment_method.py index e6802c80d..54d9cfc07 100644 --- a/stripe/_payment_method.py +++ b/stripe/_payment_method.py @@ -1691,12 +1691,7 @@ class RetrieveParams(RequestOptions): def _cls_attach( cls, payment_method: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentMethod.AttachParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["PaymentMethod.AttachParams"] ) -> "PaymentMethod": """ Attaches a PaymentMethod object to a Customer. @@ -1720,9 +1715,6 @@ def _cls_attach( "/v1/payment_methods/{payment_method}/attach".format( payment_method=_util.sanitize_id(payment_method) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1730,13 +1722,7 @@ def _cls_attach( @overload @staticmethod def attach( - payment_method: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentMethod.AttachParams" - ] # pyright: ignore[reportGeneralTypeIssues] + payment_method: str, **params: Unpack["PaymentMethod.AttachParams"] ) -> "PaymentMethod": """ Attaches a PaymentMethod object to a Customer. @@ -1757,11 +1743,7 @@ def attach( @overload def attach( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentMethod.AttachParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentMethod.AttachParams"] ) -> "PaymentMethod": """ Attaches a PaymentMethod object to a Customer. @@ -1782,11 +1764,7 @@ def attach( @class_method_variant("_cls_attach") def attach( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentMethod.AttachParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentMethod.AttachParams"] ) -> "PaymentMethod": """ Attaches a PaymentMethod object to a Customer. @@ -1810,21 +1788,13 @@ def attach( # pyright: ignore[reportGeneralTypeIssues] "/v1/payment_methods/{payment_method}/attach".format( payment_method=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentMethod.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["PaymentMethod.CreateParams"] ) -> "PaymentMethod": """ Creates a PaymentMethod object. Read the [Stripe.js reference](https://stripe.com/docs/stripe-js/reference#stripe-create-payment-method) to learn how to create PaymentMethods via Stripe.js. @@ -1836,10 +1806,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -1848,12 +1814,7 @@ def create( def _cls_detach( cls, payment_method: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentMethod.DetachParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["PaymentMethod.DetachParams"] ) -> "PaymentMethod": """ Detaches a PaymentMethod object from a Customer. After a PaymentMethod is detached, it can no longer be used for a payment or re-attached to a Customer. @@ -1865,9 +1826,6 @@ def _cls_detach( "/v1/payment_methods/{payment_method}/detach".format( payment_method=_util.sanitize_id(payment_method) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1875,13 +1833,7 @@ def _cls_detach( @overload @staticmethod def detach( - payment_method: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentMethod.DetachParams" - ] # pyright: ignore[reportGeneralTypeIssues] + payment_method: str, **params: Unpack["PaymentMethod.DetachParams"] ) -> "PaymentMethod": """ Detaches a PaymentMethod object from a Customer. After a PaymentMethod is detached, it can no longer be used for a payment or re-attached to a Customer. @@ -1890,11 +1842,7 @@ def detach( @overload def detach( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentMethod.DetachParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentMethod.DetachParams"] ) -> "PaymentMethod": """ Detaches a PaymentMethod object from a Customer. After a PaymentMethod is detached, it can no longer be used for a payment or re-attached to a Customer. @@ -1903,11 +1851,7 @@ def detach( @class_method_variant("_cls_detach") def detach( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentMethod.DetachParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentMethod.DetachParams"] ) -> "PaymentMethod": """ Detaches a PaymentMethod object from a Customer. After a PaymentMethod is detached, it can no longer be used for a payment or re-attached to a Customer. @@ -1919,20 +1863,13 @@ def detach( # pyright: ignore[reportGeneralTypeIssues] "/v1/payment_methods/{payment_method}/detach".format( payment_method=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentMethod.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["PaymentMethod.ListParams"] ) -> ListObject["PaymentMethod"]: """ Returns a list of PaymentMethods for Treasury flows. If you want to list the PaymentMethods attached to a Customer for payments, you should use the [List a Customer's PaymentMethods](https://stripe.com/docs/api/payment_methods/customer_list) API instead. @@ -1940,9 +1877,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_payment_method_configuration.py b/stripe/_payment_method_configuration.py index 428d9ff9d..72f0226b0 100644 --- a/stripe/_payment_method_configuration.py +++ b/stripe/_payment_method_configuration.py @@ -2333,14 +2333,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentMethodConfiguration.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["PaymentMethodConfiguration.CreateParams"] ) -> "PaymentMethodConfiguration": """ Creates a payment method configuration @@ -2350,23 +2343,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentMethodConfiguration.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["PaymentMethodConfiguration.ListParams"] ) -> ListObject["PaymentMethodConfiguration"]: """ List payment method configurations @@ -2374,9 +2357,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_payment_method_configuration_service.py b/stripe/_payment_method_configuration_service.py new file mode 100644 index 000000000..29e3c585c --- /dev/null +++ b/stripe/_payment_method_configuration_service.py @@ -0,0 +1,1509 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._payment_method_configuration import PaymentMethodConfiguration +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class PaymentMethodConfigurationService(StripeService): + class CreateParams(TypedDict): + acss_debit: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsAcssDebit" + ] + """ + Canadian pre-authorized debit payments, check this [page](https://stripe.com/docs/payments/acss-debit) for more details like country availability. + """ + affirm: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsAffirm" + ] + """ + [Affirm](https://www.affirm.com/) gives your customers a way to split purchases over a series of payments. Depending on the purchase, they can pay with four interest-free payments (Split Pay) or pay over a longer term (Installments), which might include interest. Check this [page](https://stripe.com/docs/payments/affirm) for more details like country availability. + """ + afterpay_clearpay: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsAfterpayClearpay" + ] + """ + Afterpay gives your customers a way to pay for purchases in installments, check this [page](https://stripe.com/docs/payments/afterpay-clearpay) for more details like country availability. Afterpay is particularly popular among businesses selling fashion, beauty, and sports products. + """ + alipay: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsAlipay" + ] + """ + Alipay is a digital wallet in China that has more than a billion active users worldwide. Alipay users can pay on the web or on a mobile device using login credentials or their Alipay app. Alipay has a low dispute rate and reduces fraud by authenticating payments using the customer's login credentials. Check this [page](https://stripe.com/docs/payments/alipay) for more details. + """ + apple_pay: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsApplePay" + ] + """ + Stripe users can accept [Apple Pay](https://stripe.com/payments/apple-pay) in iOS applications in iOS 9 and later, and on the web in Safari starting with iOS 10 or macOS Sierra. There are no additional fees to process Apple Pay payments, and the [pricing](https://stripe.com/pricing) is the same as other card transactions. Check this [page](https://stripe.com/docs/apple-pay) for more details. + """ + apple_pay_later: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsApplePayLater" + ] + """ + Apple Pay Later, a payment method for customers to buy now and pay later, gives your customers a way to split purchases into four installments across six weeks. + """ + au_becs_debit: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsAuBecsDebit" + ] + """ + Stripe users in Australia can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with an Australian bank account. Check this [page](https://stripe.com/docs/payments/au-becs-debit) for more details. + """ + bacs_debit: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsBacsDebit" + ] + """ + Stripe users in the UK can accept Bacs Direct Debit payments from customers with a UK bank account, check this [page](https://stripe.com/docs/payments/payment-methods/bacs-debit) for more details. + """ + bancontact: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsBancontact" + ] + """ + Bancontact is the most popular online payment method in Belgium, with over 15 million cards in circulation. [Customers](https://stripe.com/docs/api/customers) use a Bancontact card or mobile app linked to a Belgian bank account to make online payments that are secure, guaranteed, and confirmed immediately. Check this [page](https://stripe.com/docs/payments/bancontact) for more details. + """ + blik: NotRequired["PaymentMethodConfigurationService.CreateParamsBlik"] + """ + BLIK is a [single use](https://stripe.com/docs/payments/payment-methods#usage) payment method that requires customers to authenticate their payments. When customers want to pay online using BLIK, they request a six-digit code from their banking application and enter it into the payment collection form. Check this [page](https://stripe.com/docs/payments/blik) for more details. + """ + boleto: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsBoleto" + ] + """ + Boleto is an official (regulated by the Central Bank of Brazil) payment method in Brazil. Check this [page](https://stripe.com/docs/payments/boleto) for more details. + """ + card: NotRequired["PaymentMethodConfigurationService.CreateParamsCard"] + """ + Cards are a popular way for consumers and businesses to pay online or in person. Stripe supports global and local card networks. + """ + cartes_bancaires: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsCartesBancaires" + ] + """ + Cartes Bancaires is France's local card network. More than 95% of these cards are co-branded with either Visa or Mastercard, meaning you can process these cards over either Cartes Bancaires or the Visa or Mastercard networks. Check this [page](https://stripe.com/docs/payments/cartes-bancaires) for more details. + """ + cashapp: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsCashapp" + ] + """ + Cash App is a popular consumer app in the US that allows customers to bank, invest, send, and receive money using their digital wallet. Check this [page](https://stripe.com/docs/payments/cash-app-pay) for more details. + """ + customer_balance: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsCustomerBalance" + ] + """ + Uses a customer's [cash balance](https://stripe.com/docs/payments/customer-balance) for the payment. The cash balance can be funded via a bank transfer. Check this [page](https://stripe.com/docs/payments/bank-transfers) for more details. + """ + eps: NotRequired["PaymentMethodConfigurationService.CreateParamsEps"] + """ + EPS is an Austria-based payment method that allows customers to complete transactions online using their bank credentials. EPS is supported by all Austrian banks and is accepted by over 80% of Austrian online retailers. Check this [page](https://stripe.com/docs/payments/eps) for more details. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + fpx: NotRequired["PaymentMethodConfigurationService.CreateParamsFpx"] + """ + Financial Process Exchange (FPX) is a Malaysia-based payment method that allows customers to complete transactions online using their bank credentials. Bank Negara Malaysia (BNM), the Central Bank of Malaysia, and eleven other major Malaysian financial institutions are members of the PayNet Group, which owns and operates FPX. It is one of the most popular online payment methods in Malaysia, with nearly 90 million transactions in 2018 according to BNM. Check this [page](https://stripe.com/docs/payments/fpx) for more details. + """ + giropay: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsGiropay" + ] + """ + giropay is a German payment method based on online banking, introduced in 2006. It allows customers to complete transactions online using their online banking environment, with funds debited from their bank account. Depending on their bank, customers confirm payments on giropay using a second factor of authentication or a PIN. giropay accounts for 10% of online checkouts in Germany. Check this [page](https://stripe.com/docs/payments/giropay) for more details. + """ + google_pay: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsGooglePay" + ] + """ + Google Pay allows customers to make payments in your app or website using any credit or debit card saved to their Google Account, including those from Google Play, YouTube, Chrome, or an Android device. Use the Google Pay API to request any credit or debit card stored in your customer's Google account. Check this [page](https://stripe.com/docs/google-pay) for more details. + """ + grabpay: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsGrabpay" + ] + """ + GrabPay is a payment method developed by [Grab](https://www.grab.com/sg/consumer/finance/pay/). GrabPay is a digital wallet - customers maintain a balance in their wallets that they pay out with. Check this [page](https://stripe.com/docs/payments/grabpay) for more details. + """ + ideal: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsIdeal" + ] + """ + iDEAL is a Netherlands-based payment method that allows customers to complete transactions online using their bank credentials. All major Dutch banks are members of Currence, the scheme that operates iDEAL, making it the most popular online payment method in the Netherlands with a share of online transactions close to 55%. Check this [page](https://stripe.com/docs/payments/ideal) for more details. + """ + jcb: NotRequired["PaymentMethodConfigurationService.CreateParamsJcb"] + """ + JCB is a credit card company based in Japan. JCB is currently available in Japan to businesses approved by JCB, and available to all businesses in Australia, Canada, Hong Kong, Japan, New Zealand, Singapore, Switzerland, United Kingdom, United States, and all countries in the European Economic Area except Iceland. Check this [page](https://support.stripe.com/questions/accepting-japan-credit-bureau-%28jcb%29-payments) for more details. + """ + klarna: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsKlarna" + ] + """ + Klarna gives customers a range of [payment options](https://stripe.com/docs/payments/klarna#payment-options) during checkout. Available payment options vary depending on the customer's billing address and the transaction amount. These payment options make it convenient for customers to purchase items in all price ranges. Check this [page](https://stripe.com/docs/payments/klarna) for more details. + """ + konbini: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsKonbini" + ] + """ + Konbini allows customers in Japan to pay for bills and online purchases at convenience stores with cash. Check this [page](https://stripe.com/docs/payments/konbini) for more details. + """ + link: NotRequired["PaymentMethodConfigurationService.CreateParamsLink"] + """ + [Link](https://stripe.com/docs/payments/link) is a payment method network. With Link, users save their payment details once, then reuse that information to pay with one click for any business on the network. + """ + name: NotRequired["str"] + """ + Configuration name. + """ + oxxo: NotRequired["PaymentMethodConfigurationService.CreateParamsOxxo"] + """ + OXXO is a Mexican chain of convenience stores with thousands of locations across Latin America and represents nearly 20% of online transactions in Mexico. OXXO allows customers to pay bills and online purchases in-store with cash. Check this [page](https://stripe.com/docs/payments/oxxo) for more details. + """ + p24: NotRequired["PaymentMethodConfigurationService.CreateParamsP24"] + """ + Przelewy24 is a Poland-based payment method aggregator that allows customers to complete transactions online using bank transfers and other methods. Bank transfers account for 30% of online payments in Poland and Przelewy24 provides a way for customers to pay with over 165 banks. Check this [page](https://stripe.com/docs/payments/p24) for more details. + """ + parent: NotRequired["str"] + """ + Configuration's parent configuration. Specify to create a child configuration. + """ + paynow: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsPaynow" + ] + """ + PayNow is a Singapore-based payment method that allows customers to make a payment using their preferred app from participating banks and participating non-bank financial institutions. Check this [page](https://stripe.com/docs/payments/paynow) for more details. + """ + paypal: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsPaypal" + ] + """ + PayPal, a digital wallet popular with customers in Europe, allows your customers worldwide to pay using their PayPal account. Check this [page](https://stripe.com/docs/payments/paypal) for more details. + """ + promptpay: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsPromptpay" + ] + """ + PromptPay is a Thailand-based payment method that allows customers to make a payment using their preferred app from participating banks. Check this [page](https://stripe.com/docs/payments/promptpay) for more details. + """ + revolut_pay: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsRevolutPay" + ] + """ + Revolut Pay, developed by Revolut, a global finance app, is a digital wallet payment method. Revolut Pay uses the customer's stored balance or cards to fund the payment, and offers the option for non-Revolut customers to save their details after their first purchase. + """ + sepa_debit: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsSepaDebit" + ] + """ + The [Single Euro Payments Area (SEPA)](https://en.wikipedia.org/wiki/Single_Euro_Payments_Area) is an initiative of the European Union to simplify payments within and across member countries. SEPA established and enforced banking standards to allow for the direct debiting of every EUR-denominated bank account within the SEPA region, check this [page](https://stripe.com/docs/payments/sepa-debit) for more details. + """ + sofort: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsSofort" + ] + """ + Stripe users in Europe and the United States can use the [Payment Intents API](https://stripe.com/docs/payments/payment-intents)—a single integration path for creating payments using any supported method—to accept [Sofort](https://www.sofort.com/) payments from customers. Check this [page](https://stripe.com/docs/payments/sofort) for more details. + """ + us_bank_account: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsUsBankAccount" + ] + """ + Stripe users in the United States can accept ACH direct debit payments from customers with a US bank account using the Automated Clearing House (ACH) payments system operated by Nacha. Check this [page](https://stripe.com/docs/payments/ach-debit) for more details. + """ + wechat_pay: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsWechatPay" + ] + """ + WeChat, owned by Tencent, is China's leading mobile app with over 1 billion monthly active users. Chinese consumers can use WeChat Pay to pay for goods and services inside of businesses' apps and websites. WeChat Pay users buy most frequently in gaming, e-commerce, travel, online education, and food/nutrition. Check this [page](https://stripe.com/docs/payments/wechat-pay) for more details. + """ + + class CreateParamsAcssDebit(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsAcssDebitDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsAcssDebitDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsAffirm(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsAffirmDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsAffirmDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsAfterpayClearpay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsAfterpayClearpayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsAfterpayClearpayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsAlipay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsAlipayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsAlipayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsApplePay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsApplePayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsApplePayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsApplePayLater(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsApplePayLaterDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsApplePayLaterDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsAuBecsDebit(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsAuBecsDebitDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsAuBecsDebitDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsBacsDebit(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsBacsDebitDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsBacsDebitDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsBancontact(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsBancontactDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsBancontactDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsBlik(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsBlikDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsBlikDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsBoleto(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsBoletoDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsBoletoDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsCard(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsCardDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsCardDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsCartesBancaires(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsCartesBancairesDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsCartesBancairesDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsCashapp(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsCashappDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsCashappDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsCustomerBalance(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsCustomerBalanceDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsCustomerBalanceDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsEps(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsEpsDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsEpsDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsFpx(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsFpxDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsFpxDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsGiropay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsGiropayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsGiropayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsGooglePay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsGooglePayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsGooglePayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsGrabpay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsGrabpayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsGrabpayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsIdeal(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsIdealDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsIdealDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsJcb(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsJcbDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsJcbDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsKlarna(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsKlarnaDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsKlarnaDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsKonbini(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsKonbiniDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsKonbiniDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsLink(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsLinkDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsLinkDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsOxxo(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsOxxoDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsOxxoDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsP24(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsP24DisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsP24DisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsPaynow(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsPaynowDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsPaynowDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsPaypal(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsPaypalDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsPaypalDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsPromptpay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsPromptpayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsPromptpayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsRevolutPay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsRevolutPayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsRevolutPayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsSepaDebit(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsSepaDebitDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsSepaDebitDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsSofort(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsSofortDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsSofortDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsUsBankAccount(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsUsBankAccountDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsUsBankAccountDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class CreateParamsWechatPay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.CreateParamsWechatPayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class CreateParamsWechatPayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class ListParams(TypedDict): + application: NotRequired["Literal['']|str"] + """ + The Connect application to filter by. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + acss_debit: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsAcssDebit" + ] + """ + Canadian pre-authorized debit payments, check this [page](https://stripe.com/docs/payments/acss-debit) for more details like country availability. + """ + active: NotRequired["bool"] + """ + Whether the configuration can be used for new payments. + """ + affirm: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsAffirm" + ] + """ + [Affirm](https://www.affirm.com/) gives your customers a way to split purchases over a series of payments. Depending on the purchase, they can pay with four interest-free payments (Split Pay) or pay over a longer term (Installments), which might include interest. Check this [page](https://stripe.com/docs/payments/affirm) for more details like country availability. + """ + afterpay_clearpay: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsAfterpayClearpay" + ] + """ + Afterpay gives your customers a way to pay for purchases in installments, check this [page](https://stripe.com/docs/payments/afterpay-clearpay) for more details like country availability. Afterpay is particularly popular among businesses selling fashion, beauty, and sports products. + """ + alipay: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsAlipay" + ] + """ + Alipay is a digital wallet in China that has more than a billion active users worldwide. Alipay users can pay on the web or on a mobile device using login credentials or their Alipay app. Alipay has a low dispute rate and reduces fraud by authenticating payments using the customer's login credentials. Check this [page](https://stripe.com/docs/payments/alipay) for more details. + """ + apple_pay: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsApplePay" + ] + """ + Stripe users can accept [Apple Pay](https://stripe.com/payments/apple-pay) in iOS applications in iOS 9 and later, and on the web in Safari starting with iOS 10 or macOS Sierra. There are no additional fees to process Apple Pay payments, and the [pricing](https://stripe.com/pricing) is the same as other card transactions. Check this [page](https://stripe.com/docs/apple-pay) for more details. + """ + apple_pay_later: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsApplePayLater" + ] + """ + Apple Pay Later, a payment method for customers to buy now and pay later, gives your customers a way to split purchases into four installments across six weeks. + """ + au_becs_debit: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsAuBecsDebit" + ] + """ + Stripe users in Australia can accept Bulk Electronic Clearing System (BECS) direct debit payments from customers with an Australian bank account. Check this [page](https://stripe.com/docs/payments/au-becs-debit) for more details. + """ + bacs_debit: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsBacsDebit" + ] + """ + Stripe users in the UK can accept Bacs Direct Debit payments from customers with a UK bank account, check this [page](https://stripe.com/docs/payments/payment-methods/bacs-debit) for more details. + """ + bancontact: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsBancontact" + ] + """ + Bancontact is the most popular online payment method in Belgium, with over 15 million cards in circulation. [Customers](https://stripe.com/docs/api/customers) use a Bancontact card or mobile app linked to a Belgian bank account to make online payments that are secure, guaranteed, and confirmed immediately. Check this [page](https://stripe.com/docs/payments/bancontact) for more details. + """ + blik: NotRequired["PaymentMethodConfigurationService.UpdateParamsBlik"] + """ + BLIK is a [single use](https://stripe.com/docs/payments/payment-methods#usage) payment method that requires customers to authenticate their payments. When customers want to pay online using BLIK, they request a six-digit code from their banking application and enter it into the payment collection form. Check this [page](https://stripe.com/docs/payments/blik) for more details. + """ + boleto: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsBoleto" + ] + """ + Boleto is an official (regulated by the Central Bank of Brazil) payment method in Brazil. Check this [page](https://stripe.com/docs/payments/boleto) for more details. + """ + card: NotRequired["PaymentMethodConfigurationService.UpdateParamsCard"] + """ + Cards are a popular way for consumers and businesses to pay online or in person. Stripe supports global and local card networks. + """ + cartes_bancaires: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsCartesBancaires" + ] + """ + Cartes Bancaires is France's local card network. More than 95% of these cards are co-branded with either Visa or Mastercard, meaning you can process these cards over either Cartes Bancaires or the Visa or Mastercard networks. Check this [page](https://stripe.com/docs/payments/cartes-bancaires) for more details. + """ + cashapp: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsCashapp" + ] + """ + Cash App is a popular consumer app in the US that allows customers to bank, invest, send, and receive money using their digital wallet. Check this [page](https://stripe.com/docs/payments/cash-app-pay) for more details. + """ + customer_balance: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsCustomerBalance" + ] + """ + Uses a customer's [cash balance](https://stripe.com/docs/payments/customer-balance) for the payment. The cash balance can be funded via a bank transfer. Check this [page](https://stripe.com/docs/payments/bank-transfers) for more details. + """ + eps: NotRequired["PaymentMethodConfigurationService.UpdateParamsEps"] + """ + EPS is an Austria-based payment method that allows customers to complete transactions online using their bank credentials. EPS is supported by all Austrian banks and is accepted by over 80% of Austrian online retailers. Check this [page](https://stripe.com/docs/payments/eps) for more details. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + fpx: NotRequired["PaymentMethodConfigurationService.UpdateParamsFpx"] + """ + Financial Process Exchange (FPX) is a Malaysia-based payment method that allows customers to complete transactions online using their bank credentials. Bank Negara Malaysia (BNM), the Central Bank of Malaysia, and eleven other major Malaysian financial institutions are members of the PayNet Group, which owns and operates FPX. It is one of the most popular online payment methods in Malaysia, with nearly 90 million transactions in 2018 according to BNM. Check this [page](https://stripe.com/docs/payments/fpx) for more details. + """ + giropay: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsGiropay" + ] + """ + giropay is a German payment method based on online banking, introduced in 2006. It allows customers to complete transactions online using their online banking environment, with funds debited from their bank account. Depending on their bank, customers confirm payments on giropay using a second factor of authentication or a PIN. giropay accounts for 10% of online checkouts in Germany. Check this [page](https://stripe.com/docs/payments/giropay) for more details. + """ + google_pay: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsGooglePay" + ] + """ + Google Pay allows customers to make payments in your app or website using any credit or debit card saved to their Google Account, including those from Google Play, YouTube, Chrome, or an Android device. Use the Google Pay API to request any credit or debit card stored in your customer's Google account. Check this [page](https://stripe.com/docs/google-pay) for more details. + """ + grabpay: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsGrabpay" + ] + """ + GrabPay is a payment method developed by [Grab](https://www.grab.com/sg/consumer/finance/pay/). GrabPay is a digital wallet - customers maintain a balance in their wallets that they pay out with. Check this [page](https://stripe.com/docs/payments/grabpay) for more details. + """ + ideal: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsIdeal" + ] + """ + iDEAL is a Netherlands-based payment method that allows customers to complete transactions online using their bank credentials. All major Dutch banks are members of Currence, the scheme that operates iDEAL, making it the most popular online payment method in the Netherlands with a share of online transactions close to 55%. Check this [page](https://stripe.com/docs/payments/ideal) for more details. + """ + jcb: NotRequired["PaymentMethodConfigurationService.UpdateParamsJcb"] + """ + JCB is a credit card company based in Japan. JCB is currently available in Japan to businesses approved by JCB, and available to all businesses in Australia, Canada, Hong Kong, Japan, New Zealand, Singapore, Switzerland, United Kingdom, United States, and all countries in the European Economic Area except Iceland. Check this [page](https://support.stripe.com/questions/accepting-japan-credit-bureau-%28jcb%29-payments) for more details. + """ + klarna: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsKlarna" + ] + """ + Klarna gives customers a range of [payment options](https://stripe.com/docs/payments/klarna#payment-options) during checkout. Available payment options vary depending on the customer's billing address and the transaction amount. These payment options make it convenient for customers to purchase items in all price ranges. Check this [page](https://stripe.com/docs/payments/klarna) for more details. + """ + konbini: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsKonbini" + ] + """ + Konbini allows customers in Japan to pay for bills and online purchases at convenience stores with cash. Check this [page](https://stripe.com/docs/payments/konbini) for more details. + """ + link: NotRequired["PaymentMethodConfigurationService.UpdateParamsLink"] + """ + [Link](https://stripe.com/docs/payments/link) is a payment method network. With Link, users save their payment details once, then reuse that information to pay with one click for any business on the network. + """ + name: NotRequired["str"] + """ + Configuration name. + """ + oxxo: NotRequired["PaymentMethodConfigurationService.UpdateParamsOxxo"] + """ + OXXO is a Mexican chain of convenience stores with thousands of locations across Latin America and represents nearly 20% of online transactions in Mexico. OXXO allows customers to pay bills and online purchases in-store with cash. Check this [page](https://stripe.com/docs/payments/oxxo) for more details. + """ + p24: NotRequired["PaymentMethodConfigurationService.UpdateParamsP24"] + """ + Przelewy24 is a Poland-based payment method aggregator that allows customers to complete transactions online using bank transfers and other methods. Bank transfers account for 30% of online payments in Poland and Przelewy24 provides a way for customers to pay with over 165 banks. Check this [page](https://stripe.com/docs/payments/p24) for more details. + """ + paynow: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsPaynow" + ] + """ + PayNow is a Singapore-based payment method that allows customers to make a payment using their preferred app from participating banks and participating non-bank financial institutions. Check this [page](https://stripe.com/docs/payments/paynow) for more details. + """ + paypal: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsPaypal" + ] + """ + PayPal, a digital wallet popular with customers in Europe, allows your customers worldwide to pay using their PayPal account. Check this [page](https://stripe.com/docs/payments/paypal) for more details. + """ + promptpay: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsPromptpay" + ] + """ + PromptPay is a Thailand-based payment method that allows customers to make a payment using their preferred app from participating banks. Check this [page](https://stripe.com/docs/payments/promptpay) for more details. + """ + revolut_pay: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsRevolutPay" + ] + """ + Revolut Pay, developed by Revolut, a global finance app, is a digital wallet payment method. Revolut Pay uses the customer's stored balance or cards to fund the payment, and offers the option for non-Revolut customers to save their details after their first purchase. + """ + sepa_debit: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsSepaDebit" + ] + """ + The [Single Euro Payments Area (SEPA)](https://en.wikipedia.org/wiki/Single_Euro_Payments_Area) is an initiative of the European Union to simplify payments within and across member countries. SEPA established and enforced banking standards to allow for the direct debiting of every EUR-denominated bank account within the SEPA region, check this [page](https://stripe.com/docs/payments/sepa-debit) for more details. + """ + sofort: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsSofort" + ] + """ + Stripe users in Europe and the United States can use the [Payment Intents API](https://stripe.com/docs/payments/payment-intents)—a single integration path for creating payments using any supported method—to accept [Sofort](https://www.sofort.com/) payments from customers. Check this [page](https://stripe.com/docs/payments/sofort) for more details. + """ + us_bank_account: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsUsBankAccount" + ] + """ + Stripe users in the United States can accept ACH direct debit payments from customers with a US bank account using the Automated Clearing House (ACH) payments system operated by Nacha. Check this [page](https://stripe.com/docs/payments/ach-debit) for more details. + """ + wechat_pay: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsWechatPay" + ] + """ + WeChat, owned by Tencent, is China's leading mobile app with over 1 billion monthly active users. Chinese consumers can use WeChat Pay to pay for goods and services inside of businesses' apps and websites. WeChat Pay users buy most frequently in gaming, e-commerce, travel, online education, and food/nutrition. Check this [page](https://stripe.com/docs/payments/wechat-pay) for more details. + """ + + class UpdateParamsAcssDebit(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsAcssDebitDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsAcssDebitDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsAffirm(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsAffirmDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsAffirmDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsAfterpayClearpay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsAfterpayClearpayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsAfterpayClearpayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsAlipay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsAlipayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsAlipayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsApplePay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsApplePayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsApplePayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsApplePayLater(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsApplePayLaterDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsApplePayLaterDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsAuBecsDebit(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsAuBecsDebitDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsAuBecsDebitDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsBacsDebit(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsBacsDebitDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsBacsDebitDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsBancontact(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsBancontactDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsBancontactDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsBlik(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsBlikDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsBlikDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsBoleto(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsBoletoDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsBoletoDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsCard(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsCardDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsCardDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsCartesBancaires(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsCartesBancairesDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsCartesBancairesDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsCashapp(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsCashappDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsCashappDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsCustomerBalance(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsCustomerBalanceDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsCustomerBalanceDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsEps(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsEpsDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsEpsDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsFpx(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsFpxDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsFpxDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsGiropay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsGiropayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsGiropayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsGooglePay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsGooglePayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsGooglePayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsGrabpay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsGrabpayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsGrabpayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsIdeal(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsIdealDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsIdealDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsJcb(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsJcbDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsJcbDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsKlarna(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsKlarnaDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsKlarnaDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsKonbini(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsKonbiniDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsKonbiniDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsLink(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsLinkDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsLinkDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsOxxo(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsOxxoDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsOxxoDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsP24(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsP24DisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsP24DisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsPaynow(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsPaynowDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsPaynowDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsPaypal(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsPaypalDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsPaypalDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsPromptpay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsPromptpayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsPromptpayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsRevolutPay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsRevolutPayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsRevolutPayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsSepaDebit(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsSepaDebitDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsSepaDebitDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsSofort(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsSofortDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsSofortDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsUsBankAccount(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsUsBankAccountDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsUsBankAccountDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + class UpdateParamsWechatPay(TypedDict): + display_preference: NotRequired[ + "PaymentMethodConfigurationService.UpdateParamsWechatPayDisplayPreference" + ] + """ + Whether or not the payment method should be displayed. + """ + + class UpdateParamsWechatPayDisplayPreference(TypedDict): + preference: NotRequired["Literal['none', 'off', 'on']"] + """ + The account's preference for whether or not to display this payment method. + """ + + def list( + self, + params: "PaymentMethodConfigurationService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[PaymentMethodConfiguration]: + """ + List payment method configurations + """ + return cast( + ListObject[PaymentMethodConfiguration], + self._requestor.request( + "get", + "/v1/payment_method_configurations", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "PaymentMethodConfigurationService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> PaymentMethodConfiguration: + """ + Creates a payment method configuration + """ + return cast( + PaymentMethodConfiguration, + self._requestor.request( + "post", + "/v1/payment_method_configurations", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + configuration: str, + params: "PaymentMethodConfigurationService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> PaymentMethodConfiguration: + """ + Retrieve payment method configuration + """ + return cast( + PaymentMethodConfiguration, + self._requestor.request( + "get", + "/v1/payment_method_configurations/{configuration}".format( + configuration=_util.sanitize_id(configuration), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + configuration: str, + params: "PaymentMethodConfigurationService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> PaymentMethodConfiguration: + """ + Update payment method configuration + """ + return cast( + PaymentMethodConfiguration, + self._requestor.request( + "post", + "/v1/payment_method_configurations/{configuration}".format( + configuration=_util.sanitize_id(configuration), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_payment_method_domain.py b/stripe/_payment_method_domain.py index b9a8e6c35..558dc295e 100644 --- a/stripe/_payment_method_domain.py +++ b/stripe/_payment_method_domain.py @@ -202,14 +202,7 @@ class ValidateParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentMethodDomain.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["PaymentMethodDomain.CreateParams"] ) -> "PaymentMethodDomain": """ Creates a payment method domain. @@ -219,23 +212,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentMethodDomain.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["PaymentMethodDomain.ListParams"] ) -> ListObject["PaymentMethodDomain"]: """ Lists the details of existing payment method domains. @@ -243,9 +226,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -285,12 +265,7 @@ def retrieve( def _cls_validate( cls, payment_method_domain: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentMethodDomain.ValidateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["PaymentMethodDomain.ValidateParams"] ) -> "PaymentMethodDomain": """ Some payment methods such as Apple Pay require additional steps to verify a domain. If the requirements weren't satisfied when the domain was created, the payment method will be inactive on the domain. @@ -309,9 +284,6 @@ def _cls_validate( payment_method_domain ) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -320,12 +292,7 @@ def _cls_validate( @staticmethod def validate( payment_method_domain: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PaymentMethodDomain.ValidateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["PaymentMethodDomain.ValidateParams"] ) -> "PaymentMethodDomain": """ Some payment methods such as Apple Pay require additional steps to verify a domain. If the requirements weren't satisfied when the domain was created, the payment method will be inactive on the domain. @@ -339,11 +306,7 @@ def validate( @overload def validate( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentMethodDomain.ValidateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentMethodDomain.ValidateParams"] ) -> "PaymentMethodDomain": """ Some payment methods such as Apple Pay require additional steps to verify a domain. If the requirements weren't satisfied when the domain was created, the payment method will be inactive on the domain. @@ -357,11 +320,7 @@ def validate( @class_method_variant("_cls_validate") def validate( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "PaymentMethodDomain.ValidateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["PaymentMethodDomain.ValidateParams"] ) -> "PaymentMethodDomain": """ Some payment methods such as Apple Pay require additional steps to verify a domain. If the requirements weren't satisfied when the domain was created, the payment method will be inactive on the domain. @@ -378,7 +337,6 @@ def validate( # pyright: ignore[reportGeneralTypeIssues] "/v1/payment_method_domains/{payment_method_domain}/validate".format( payment_method_domain=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/_payment_method_domain_service.py b/stripe/_payment_method_domain_service.py new file mode 100644 index 000000000..41c9bc5e5 --- /dev/null +++ b/stripe/_payment_method_domain_service.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._payment_method_domain import PaymentMethodDomain +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class PaymentMethodDomainService(StripeService): + class CreateParams(TypedDict): + domain_name: str + """ + The domain name that this payment method domain object represents. + """ + enabled: NotRequired["bool"] + """ + Whether this payment method domain is enabled. If the domain is not enabled, payment methods that require a payment method domain will not appear in Elements. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ListParams(TypedDict): + domain_name: NotRequired["str"] + """ + The domain name that this payment method domain object represents. + """ + enabled: NotRequired["bool"] + """ + Whether this payment method domain is enabled. If the domain is not enabled, payment methods will not appear in Elements + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + enabled: NotRequired["bool"] + """ + Whether this payment method domain is enabled. If the domain is not enabled, payment methods that require a payment method domain will not appear in Elements. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ValidateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "PaymentMethodDomainService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[PaymentMethodDomain]: + """ + Lists the details of existing payment method domains. + """ + return cast( + ListObject[PaymentMethodDomain], + self._requestor.request( + "get", + "/v1/payment_method_domains", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "PaymentMethodDomainService.CreateParams", + options: RequestOptions = {}, + ) -> PaymentMethodDomain: + """ + Creates a payment method domain. + """ + return cast( + PaymentMethodDomain, + self._requestor.request( + "post", + "/v1/payment_method_domains", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + payment_method_domain: str, + params: "PaymentMethodDomainService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> PaymentMethodDomain: + """ + Retrieves the details of an existing payment method domain. + """ + return cast( + PaymentMethodDomain, + self._requestor.request( + "get", + "/v1/payment_method_domains/{payment_method_domain}".format( + payment_method_domain=_util.sanitize_id( + payment_method_domain + ), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + payment_method_domain: str, + params: "PaymentMethodDomainService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> PaymentMethodDomain: + """ + Updates an existing payment method domain. + """ + return cast( + PaymentMethodDomain, + self._requestor.request( + "post", + "/v1/payment_method_domains/{payment_method_domain}".format( + payment_method_domain=_util.sanitize_id( + payment_method_domain + ), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def validate( + self, + payment_method_domain: str, + params: "PaymentMethodDomainService.ValidateParams" = {}, + options: RequestOptions = {}, + ) -> PaymentMethodDomain: + """ + Some payment methods such as Apple Pay require additional steps to verify a domain. If the requirements weren't satisfied when the domain was created, the payment method will be inactive on the domain. + The payment method doesn't appear in Elements for this domain until it is active. + + To activate a payment method on an existing payment method domain, complete the required validation steps specific to the payment method, and then validate the payment method domain with this endpoint. + + Related guides: [Payment method domains](https://stripe.com/docs/payments/payment-methods/pmd-registration). + """ + return cast( + PaymentMethodDomain, + self._requestor.request( + "post", + "/v1/payment_method_domains/{payment_method_domain}/validate".format( + payment_method_domain=_util.sanitize_id( + payment_method_domain + ), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_payment_method_service.py b/stripe/_payment_method_service.py new file mode 100644 index 000000000..d10c92fa1 --- /dev/null +++ b/stripe/_payment_method_service.py @@ -0,0 +1,769 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._payment_method import PaymentMethod +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class PaymentMethodService(StripeService): + class AttachParams(TypedDict): + customer: str + """ + The ID of the customer to which to attach the PaymentMethod. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CreateParams(TypedDict): + acss_debit: NotRequired["PaymentMethodService.CreateParamsAcssDebit"] + """ + If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + """ + affirm: NotRequired["PaymentMethodService.CreateParamsAffirm"] + """ + If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + """ + afterpay_clearpay: NotRequired[ + "PaymentMethodService.CreateParamsAfterpayClearpay" + ] + """ + If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + """ + alipay: NotRequired["PaymentMethodService.CreateParamsAlipay"] + """ + If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + """ + au_becs_debit: NotRequired[ + "PaymentMethodService.CreateParamsAuBecsDebit" + ] + """ + If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + """ + bacs_debit: NotRequired["PaymentMethodService.CreateParamsBacsDebit"] + """ + If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + """ + bancontact: NotRequired["PaymentMethodService.CreateParamsBancontact"] + """ + If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + """ + billing_details: NotRequired[ + "PaymentMethodService.CreateParamsBillingDetails" + ] + """ + Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + """ + blik: NotRequired["PaymentMethodService.CreateParamsBlik"] + """ + If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + """ + boleto: NotRequired["PaymentMethodService.CreateParamsBoleto"] + """ + If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + """ + card: NotRequired["PaymentMethodService.CreateParamsCard"] + """ + If this is a `card` PaymentMethod, this hash contains the user's card details. For backwards compatibility, you can alternatively provide a Stripe token (e.g., for Apple Pay, Amex Express Checkout, or legacy Checkout) into the card hash with format `card: {token: "tok_visa"}`. When providing a card number, you must meet the requirements for [PCI compliance](https://stripe.com/docs/security#validating-pci-compliance). We strongly recommend using Stripe.js instead of interacting with this API directly. + """ + cashapp: NotRequired["PaymentMethodService.CreateParamsCashapp"] + """ + If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + """ + customer: NotRequired["str"] + """ + The `Customer` to whom the original PaymentMethod is attached. + """ + customer_balance: NotRequired[ + "PaymentMethodService.CreateParamsCustomerBalance" + ] + """ + If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + """ + eps: NotRequired["PaymentMethodService.CreateParamsEps"] + """ + If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + fpx: NotRequired["PaymentMethodService.CreateParamsFpx"] + """ + If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + """ + giropay: NotRequired["PaymentMethodService.CreateParamsGiropay"] + """ + If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + """ + grabpay: NotRequired["PaymentMethodService.CreateParamsGrabpay"] + """ + If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + """ + ideal: NotRequired["PaymentMethodService.CreateParamsIdeal"] + """ + If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + """ + interac_present: NotRequired[ + "PaymentMethodService.CreateParamsInteracPresent" + ] + """ + If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + """ + klarna: NotRequired["PaymentMethodService.CreateParamsKlarna"] + """ + If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + """ + konbini: NotRequired["PaymentMethodService.CreateParamsKonbini"] + """ + If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + """ + link: NotRequired["PaymentMethodService.CreateParamsLink"] + """ + If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + oxxo: NotRequired["PaymentMethodService.CreateParamsOxxo"] + """ + If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + """ + p24: NotRequired["PaymentMethodService.CreateParamsP24"] + """ + If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + """ + payment_method: NotRequired["str"] + """ + The PaymentMethod to share. + """ + paynow: NotRequired["PaymentMethodService.CreateParamsPaynow"] + """ + If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + """ + paypal: NotRequired["PaymentMethodService.CreateParamsPaypal"] + """ + If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + """ + pix: NotRequired["PaymentMethodService.CreateParamsPix"] + """ + If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + """ + promptpay: NotRequired["PaymentMethodService.CreateParamsPromptpay"] + """ + If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + """ + radar_options: NotRequired[ + "PaymentMethodService.CreateParamsRadarOptions" + ] + """ + Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + """ + revolut_pay: NotRequired["PaymentMethodService.CreateParamsRevolutPay"] + """ + If this is a `Revolut Pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + """ + sepa_debit: NotRequired["PaymentMethodService.CreateParamsSepaDebit"] + """ + If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + """ + sofort: NotRequired["PaymentMethodService.CreateParamsSofort"] + """ + If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + """ + type: NotRequired[ + "Literal['acss_debit', 'affirm', 'afterpay_clearpay', 'alipay', 'au_becs_debit', 'bacs_debit', 'bancontact', 'blik', 'boleto', 'card', 'cashapp', 'customer_balance', 'eps', 'fpx', 'giropay', 'grabpay', 'ideal', 'klarna', 'konbini', 'link', 'oxxo', 'p24', 'paynow', 'paypal', 'pix', 'promptpay', 'revolut_pay', 'sepa_debit', 'sofort', 'us_bank_account', 'wechat_pay', 'zip']" + ] + """ + The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + """ + us_bank_account: NotRequired[ + "PaymentMethodService.CreateParamsUsBankAccount" + ] + """ + If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + """ + wechat_pay: NotRequired["PaymentMethodService.CreateParamsWechatPay"] + """ + If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + """ + zip: NotRequired["PaymentMethodService.CreateParamsZip"] + """ + If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + """ + + class CreateParamsAcssDebit(TypedDict): + account_number: str + """ + Customer's bank account number. + """ + institution_number: str + """ + Institution number of the customer's bank. + """ + transit_number: str + """ + Transit number of the customer's bank. + """ + + class CreateParamsAffirm(TypedDict): + pass + + class CreateParamsAfterpayClearpay(TypedDict): + pass + + class CreateParamsAlipay(TypedDict): + pass + + class CreateParamsAuBecsDebit(TypedDict): + account_number: str + """ + The account number for the bank account. + """ + bsb_number: str + """ + Bank-State-Branch number of the bank account. + """ + + class CreateParamsBacsDebit(TypedDict): + account_number: NotRequired["str"] + """ + Account number of the bank account that the funds will be debited from. + """ + sort_code: NotRequired["str"] + """ + Sort code of the bank account. (e.g., `10-20-30`) + """ + + class CreateParamsBancontact(TypedDict): + pass + + class CreateParamsBillingDetails(TypedDict): + address: NotRequired[ + "Literal['']|PaymentMethodService.CreateParamsBillingDetailsAddress" + ] + """ + Billing address. + """ + email: NotRequired["Literal['']|str"] + """ + Email address. + """ + name: NotRequired["Literal['']|str"] + """ + Full name. + """ + phone: NotRequired["Literal['']|str"] + """ + Billing phone number (including extension). + """ + + class CreateParamsBillingDetailsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsBlik(TypedDict): + pass + + class CreateParamsBoleto(TypedDict): + tax_id: str + """ + The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + """ + + class CreateParamsCard(TypedDict): + cvc: NotRequired["str"] + """ + The card's CVC. It is highly recommended to always include this value. + """ + exp_month: NotRequired["int"] + """ + Two-digit number representing the card's expiration month. + """ + exp_year: NotRequired["int"] + """ + Four-digit number representing the card's expiration year. + """ + number: NotRequired["str"] + """ + The card number, as a string without any separators. + """ + token: NotRequired["str"] + """ + For backwards compatibility, you can alternatively provide a Stripe token (e.g., for Apple Pay, Amex Express Checkout, or legacy Checkout) into the card hash with format card: {token: "tok_visa"}. + """ + + class CreateParamsCashapp(TypedDict): + pass + + class CreateParamsCustomerBalance(TypedDict): + pass + + class CreateParamsEps(TypedDict): + bank: NotRequired[ + "Literal['arzte_und_apotheker_bank', 'austrian_anadi_bank_ag', 'bank_austria', 'bankhaus_carl_spangler', 'bankhaus_schelhammer_und_schattera_ag', 'bawag_psk_ag', 'bks_bank_ag', 'brull_kallmus_bank_ag', 'btv_vier_lander_bank', 'capital_bank_grawe_gruppe_ag', 'deutsche_bank_ag', 'dolomitenbank', 'easybank_ag', 'erste_bank_und_sparkassen', 'hypo_alpeadriabank_international_ag', 'hypo_bank_burgenland_aktiengesellschaft', 'hypo_noe_lb_fur_niederosterreich_u_wien', 'hypo_oberosterreich_salzburg_steiermark', 'hypo_tirol_bank_ag', 'hypo_vorarlberg_bank_ag', 'marchfelder_bank', 'oberbank_ag', 'raiffeisen_bankengruppe_osterreich', 'schoellerbank_ag', 'sparda_bank_wien', 'volksbank_gruppe', 'volkskreditbank_ag', 'vr_bank_braunau']" + ] + """ + The customer's bank. + """ + + class CreateParamsFpx(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type for FPX transaction + """ + bank: Literal[ + "affin_bank", + "agrobank", + "alliance_bank", + "ambank", + "bank_islam", + "bank_muamalat", + "bank_of_china", + "bank_rakyat", + "bsn", + "cimb", + "deutsche_bank", + "hong_leong_bank", + "hsbc", + "kfh", + "maybank2e", + "maybank2u", + "ocbc", + "pb_enterprise", + "public_bank", + "rhb", + "standard_chartered", + "uob", + ] + """ + The customer's bank. + """ + + class CreateParamsGiropay(TypedDict): + pass + + class CreateParamsGrabpay(TypedDict): + pass + + class CreateParamsIdeal(TypedDict): + bank: NotRequired[ + "Literal['abn_amro', 'asn_bank', 'bunq', 'handelsbanken', 'ing', 'knab', 'moneyou', 'n26', 'nn', 'rabobank', 'regiobank', 'revolut', 'sns_bank', 'triodos_bank', 'van_lanschot', 'yoursafe']" + ] + """ + The customer's bank. + """ + + class CreateParamsInteracPresent(TypedDict): + pass + + class CreateParamsKlarna(TypedDict): + dob: NotRequired["PaymentMethodService.CreateParamsKlarnaDob"] + """ + Customer's date of birth + """ + + class CreateParamsKlarnaDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class CreateParamsKonbini(TypedDict): + pass + + class CreateParamsLink(TypedDict): + pass + + class CreateParamsOxxo(TypedDict): + pass + + class CreateParamsP24(TypedDict): + bank: NotRequired[ + "Literal['alior_bank', 'bank_millennium', 'bank_nowy_bfg_sa', 'bank_pekao_sa', 'banki_spbdzielcze', 'blik', 'bnp_paribas', 'boz', 'citi_handlowy', 'credit_agricole', 'envelobank', 'etransfer_pocztowy24', 'getin_bank', 'ideabank', 'ing', 'inteligo', 'mbank_mtransfer', 'nest_przelew', 'noble_pay', 'pbac_z_ipko', 'plus_bank', 'santander_przelew24', 'tmobile_usbugi_bankowe', 'toyota_bank', 'volkswagen_bank']" + ] + """ + The customer's bank. + """ + + class CreateParamsPaynow(TypedDict): + pass + + class CreateParamsPaypal(TypedDict): + pass + + class CreateParamsPix(TypedDict): + pass + + class CreateParamsPromptpay(TypedDict): + pass + + class CreateParamsRadarOptions(TypedDict): + session: NotRequired["str"] + """ + A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + """ + + class CreateParamsRevolutPay(TypedDict): + pass + + class CreateParamsSepaDebit(TypedDict): + iban: str + """ + IBAN of the bank account. + """ + + class CreateParamsSofort(TypedDict): + country: Literal["AT", "BE", "DE", "ES", "IT", "NL"] + """ + Two-letter ISO code representing the country the bank account is located in. + """ + + class CreateParamsUsBankAccount(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type: individual or company. + """ + account_number: NotRequired["str"] + """ + Account number of the bank account. + """ + account_type: NotRequired["Literal['checking', 'savings']"] + """ + Account type: checkings or savings. Defaults to checking if omitted. + """ + financial_connections_account: NotRequired["str"] + """ + The ID of a Financial Connections Account to use as a payment method. + """ + routing_number: NotRequired["str"] + """ + Routing number of the bank account. + """ + + class CreateParamsWechatPay(TypedDict): + pass + + class CreateParamsZip(TypedDict): + pass + + class DetachParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ListParams(TypedDict): + customer: NotRequired["str"] + """ + The ID of the customer whose PaymentMethods will be retrieved. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + type: NotRequired[ + "Literal['acss_debit', 'affirm', 'afterpay_clearpay', 'alipay', 'au_becs_debit', 'bacs_debit', 'bancontact', 'blik', 'boleto', 'card', 'cashapp', 'customer_balance', 'eps', 'fpx', 'giropay', 'grabpay', 'ideal', 'klarna', 'konbini', 'link', 'oxxo', 'p24', 'paynow', 'paypal', 'pix', 'promptpay', 'revolut_pay', 'sepa_debit', 'sofort', 'us_bank_account', 'wechat_pay', 'zip']" + ] + """ + An optional filter on the list, based on the object `type` field. Without the filter, the list includes all current and future payment method types. If your integration expects only one type of payment method in the response, make sure to provide a type value in the request. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + billing_details: NotRequired[ + "PaymentMethodService.UpdateParamsBillingDetails" + ] + """ + Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + """ + card: NotRequired["PaymentMethodService.UpdateParamsCard"] + """ + If this is a `card` PaymentMethod, this hash contains the user's card details. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + link: NotRequired["PaymentMethodService.UpdateParamsLink"] + """ + If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + us_bank_account: NotRequired[ + "PaymentMethodService.UpdateParamsUsBankAccount" + ] + """ + If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + """ + + class UpdateParamsBillingDetails(TypedDict): + address: NotRequired[ + "Literal['']|PaymentMethodService.UpdateParamsBillingDetailsAddress" + ] + """ + Billing address. + """ + email: NotRequired["Literal['']|str"] + """ + Email address. + """ + name: NotRequired["Literal['']|str"] + """ + Full name. + """ + phone: NotRequired["Literal['']|str"] + """ + Billing phone number (including extension). + """ + + class UpdateParamsBillingDetailsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsCard(TypedDict): + exp_month: NotRequired["int"] + """ + Two-digit number representing the card's expiration month. + """ + exp_year: NotRequired["int"] + """ + Four-digit number representing the card's expiration year. + """ + + class UpdateParamsLink(TypedDict): + pass + + class UpdateParamsUsBankAccount(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Bank account holder type. + """ + account_type: NotRequired["Literal['checking', 'savings']"] + """ + Bank account type. + """ + + def list( + self, + params: "PaymentMethodService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[PaymentMethod]: + """ + Returns a list of PaymentMethods for Treasury flows. If you want to list the PaymentMethods attached to a Customer for payments, you should use the [List a Customer's PaymentMethods](https://stripe.com/docs/api/payment_methods/customer_list) API instead. + """ + return cast( + ListObject[PaymentMethod], + self._requestor.request( + "get", + "/v1/payment_methods", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "PaymentMethodService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> PaymentMethod: + """ + Creates a PaymentMethod object. Read the [Stripe.js reference](https://stripe.com/docs/stripe-js/reference#stripe-create-payment-method) to learn how to create PaymentMethods via Stripe.js. + + Instead of creating a PaymentMethod directly, we recommend using the [PaymentIntents API to accept a payment immediately or the SetupIntent](https://stripe.com/docs/payments/accept-a-payment) API to collect payment method details ahead of a future payment. + """ + return cast( + PaymentMethod, + self._requestor.request( + "post", + "/v1/payment_methods", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + payment_method: str, + params: "PaymentMethodService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> PaymentMethod: + """ + Retrieves a PaymentMethod object attached to the StripeAccount. To retrieve a payment method attached to a Customer, you should use [Retrieve a Customer's PaymentMethods](https://stripe.com/docs/api/payment_methods/customer) + """ + return cast( + PaymentMethod, + self._requestor.request( + "get", + "/v1/payment_methods/{payment_method}".format( + payment_method=_util.sanitize_id(payment_method), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + payment_method: str, + params: "PaymentMethodService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> PaymentMethod: + """ + Updates a PaymentMethod object. A PaymentMethod must be attached a customer to be updated. + """ + return cast( + PaymentMethod, + self._requestor.request( + "post", + "/v1/payment_methods/{payment_method}".format( + payment_method=_util.sanitize_id(payment_method), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def attach( + self, + payment_method: str, + params: "PaymentMethodService.AttachParams", + options: RequestOptions = {}, + ) -> PaymentMethod: + """ + Attaches a PaymentMethod object to a Customer. + + To attach a new PaymentMethod to a customer for future payments, we recommend you use a [SetupIntent](https://stripe.com/docs/api/setup_intents) + or a PaymentIntent with [setup_future_usage](https://stripe.com/docs/api/payment_intents/create#create_payment_intent-setup_future_usage). + These approaches will perform any necessary steps to set up the PaymentMethod for future payments. Using the /v1/payment_methods/:id/attach + endpoint without first using a SetupIntent or PaymentIntent with setup_future_usage does not optimize the PaymentMethod for + future use, which makes later declines and payment friction more likely. + See [Optimizing cards for future payments](https://stripe.com/docs/payments/payment-intents#future-usage) for more information about setting up + future payments. + + To use this PaymentMethod as the default for invoice or subscription payments, + set [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/update#update_customer-invoice_settings-default_payment_method), + on the Customer to the PaymentMethod's ID. + """ + return cast( + PaymentMethod, + self._requestor.request( + "post", + "/v1/payment_methods/{payment_method}/attach".format( + payment_method=_util.sanitize_id(payment_method), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def detach( + self, + payment_method: str, + params: "PaymentMethodService.DetachParams" = {}, + options: RequestOptions = {}, + ) -> PaymentMethod: + """ + Detaches a PaymentMethod object from a Customer. After a PaymentMethod is detached, it can no longer be used for a payment or re-attached to a Customer. + """ + return cast( + PaymentMethod, + self._requestor.request( + "post", + "/v1/payment_methods/{payment_method}/detach".format( + payment_method=_util.sanitize_id(payment_method), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_payout.py b/stripe/_payout.py index eeeffd84d..9843e1406 100644 --- a/stripe/_payout.py +++ b/stripe/_payout.py @@ -275,14 +275,7 @@ class ReverseParams(RequestOptions): @classmethod def _cls_cancel( - cls, - payout: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Payout.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, payout: str, **params: Unpack["Payout.CancelParams"] ) -> "Payout": """ You can cancel a previously created payout if its status is pending. Stripe refunds the funds to your available balance. You can't cancel automatic Stripe payouts. @@ -294,9 +287,6 @@ def _cls_cancel( "/v1/payouts/{payout}/cancel".format( payout=_util.sanitize_id(payout) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -304,13 +294,7 @@ def _cls_cancel( @overload @staticmethod def cancel( - payout: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Payout.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + payout: str, **params: Unpack["Payout.CancelParams"] ) -> "Payout": """ You can cancel a previously created payout if its status is pending. Stripe refunds the funds to your available balance. You can't cancel automatic Stripe payouts. @@ -318,13 +302,7 @@ def cancel( ... @overload - def cancel( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Payout.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Payout": + def cancel(self, **params: Unpack["Payout.CancelParams"]) -> "Payout": """ You can cancel a previously created payout if its status is pending. Stripe refunds the funds to your available balance. You can't cancel automatic Stripe payouts. """ @@ -332,11 +310,7 @@ def cancel( @class_method_variant("_cls_cancel") def cancel( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Payout.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Payout.CancelParams"] ) -> "Payout": """ You can cancel a previously created payout if its status is pending. Stripe refunds the funds to your available balance. You can't cancel automatic Stripe payouts. @@ -348,22 +322,12 @@ def cancel( # pyright: ignore[reportGeneralTypeIssues] "/v1/payouts/{payout}/cancel".format( payout=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Payout.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Payout": + def create(cls, **params: Unpack["Payout.CreateParams"]) -> "Payout": """ To send funds to your own bank account, create a new payout object. Your [Stripe balance](https://stripe.com/docs/api#balance) must cover the payout amount. If it doesn't, you receive an “Insufficient Funds” error. @@ -376,23 +340,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Payout.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Payout.ListParams"] ) -> ListObject["Payout"]: """ Returns a list of existing payouts sent to third-party bank accounts or payouts that Stripe sent to you. The payouts return in sorted order, with the most recently created payouts appearing first. @@ -400,9 +354,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -440,14 +391,7 @@ def retrieve( @classmethod def _cls_reverse( - cls, - payout: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Payout.ReverseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, payout: str, **params: Unpack["Payout.ReverseParams"] ) -> "Payout": """ Reverses a payout by debiting the destination bank account. At this time, you can only reverse payouts for connected accounts to US bank accounts. If the payout is manual and in the pending status, use /v1/payouts/:id/cancel instead. @@ -461,9 +405,6 @@ def _cls_reverse( "/v1/payouts/{payout}/reverse".format( payout=_util.sanitize_id(payout) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -471,13 +412,7 @@ def _cls_reverse( @overload @staticmethod def reverse( - payout: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Payout.ReverseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + payout: str, **params: Unpack["Payout.ReverseParams"] ) -> "Payout": """ Reverses a payout by debiting the destination bank account. At this time, you can only reverse payouts for connected accounts to US bank accounts. If the payout is manual and in the pending status, use /v1/payouts/:id/cancel instead. @@ -487,13 +422,7 @@ def reverse( ... @overload - def reverse( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Payout.ReverseParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Payout": + def reverse(self, **params: Unpack["Payout.ReverseParams"]) -> "Payout": """ Reverses a payout by debiting the destination bank account. At this time, you can only reverse payouts for connected accounts to US bank accounts. If the payout is manual and in the pending status, use /v1/payouts/:id/cancel instead. @@ -503,11 +432,7 @@ def reverse( @class_method_variant("_cls_reverse") def reverse( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Payout.ReverseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Payout.ReverseParams"] ) -> "Payout": """ Reverses a payout by debiting the destination bank account. At this time, you can only reverse payouts for connected accounts to US bank accounts. If the payout is manual and in the pending status, use /v1/payouts/:id/cancel instead. @@ -521,7 +446,6 @@ def reverse( # pyright: ignore[reportGeneralTypeIssues] "/v1/payouts/{payout}/reverse".format( payout=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/_payout_service.py b/stripe/_payout_service.py new file mode 100644 index 000000000..a263f93de --- /dev/null +++ b/stripe/_payout_service.py @@ -0,0 +1,283 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._payout import Payout +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class PayoutService(StripeService): + class CancelParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CreateParams(TypedDict): + amount: int + """ + A positive integer in cents representing how much to payout. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + destination: NotRequired["str"] + """ + The ID of a bank account or a card to send the payout to. If you don't provide a destination, we use the default external account for the specified currency. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + method: NotRequired["Literal['instant', 'standard']"] + """ + The method used to send this payout, which is `standard` or `instant`. We support `instant` for payouts to debit cards and bank accounts in certain countries. Learn more about [bank support for Instant Payouts](https://stripe.com/docs/payouts/instant-payouts-banks). + """ + source_type: NotRequired["Literal['bank_account', 'card', 'fpx']"] + """ + The balance type of your Stripe balance to draw this payout from. Balances for different payment sources are kept separately. You can find the amounts with the Balances API. One of `bank_account`, `card`, or `fpx`. + """ + statement_descriptor: NotRequired["str"] + """ + A string that displays on the recipient's bank or card statement (up to 22 characters). A `statement_descriptor` that's longer than 22 characters return an error. Most banks truncate this information and display it inconsistently. Some banks might not display it at all. + """ + + class ListParams(TypedDict): + arrival_date: NotRequired["PayoutService.ListParamsArrivalDate|int"] + created: NotRequired["PayoutService.ListParamsCreated|int"] + destination: NotRequired["str"] + """ + The ID of an external account - only return payouts sent to this external account. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired["str"] + """ + Only return payouts that have the given status: `pending`, `paid`, `failed`, or `canceled`. + """ + + class ListParamsArrivalDate(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ReverseParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + def list( + self, + params: "PayoutService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Payout]: + """ + Returns a list of existing payouts sent to third-party bank accounts or payouts that Stripe sent to you. The payouts return in sorted order, with the most recently created payouts appearing first. + """ + return cast( + ListObject[Payout], + self._requestor.request( + "get", + "/v1/payouts", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "PayoutService.CreateParams", + options: RequestOptions = {}, + ) -> Payout: + """ + To send funds to your own bank account, create a new payout object. Your [Stripe balance](https://stripe.com/docs/api#balance) must cover the payout amount. If it doesn't, you receive an “Insufficient Funds” error. + + If your API key is in test mode, money won't actually be sent, though every other action occurs as if you're in live mode. + + If you create a manual payout on a Stripe account that uses multiple payment source types, you need to specify the source type balance that the payout draws from. The [balance object](https://stripe.com/docs/api#balance_object) details available and pending amounts by source type. + """ + return cast( + Payout, + self._requestor.request( + "post", + "/v1/payouts", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + payout: str, + params: "PayoutService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Payout: + """ + Retrieves the details of an existing payout. Supply the unique payout ID from either a payout creation request or the payout list. Stripe returns the corresponding payout information. + """ + return cast( + Payout, + self._requestor.request( + "get", + "/v1/payouts/{payout}".format( + payout=_util.sanitize_id(payout) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + payout: str, + params: "PayoutService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Payout: + """ + Updates the specified payout by setting the values of the parameters you pass. We don't change parameters that you don't provide. This request only accepts the metadata as arguments. + """ + return cast( + Payout, + self._requestor.request( + "post", + "/v1/payouts/{payout}".format( + payout=_util.sanitize_id(payout) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def cancel( + self, + payout: str, + params: "PayoutService.CancelParams" = {}, + options: RequestOptions = {}, + ) -> Payout: + """ + You can cancel a previously created payout if its status is pending. Stripe refunds the funds to your available balance. You can't cancel automatic Stripe payouts. + """ + return cast( + Payout, + self._requestor.request( + "post", + "/v1/payouts/{payout}/cancel".format( + payout=_util.sanitize_id(payout), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def reverse( + self, + payout: str, + params: "PayoutService.ReverseParams" = {}, + options: RequestOptions = {}, + ) -> Payout: + """ + Reverses a payout by debiting the destination bank account. At this time, you can only reverse payouts for connected accounts to US bank accounts. If the payout is manual and in the pending status, use /v1/payouts/:id/cancel instead. + + By requesting a reversal through /v1/payouts/:id/reverse, you confirm that the authorized signatory of the selected bank account authorizes the debit on the bank account and that no other authorization is required. + """ + return cast( + Payout, + self._requestor.request( + "post", + "/v1/payouts/{payout}/reverse".format( + payout=_util.sanitize_id(payout), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_person.py b/stripe/_person.py index 29754e5b5..cc16e1353 100644 --- a/stripe/_person.py +++ b/stripe/_person.py @@ -664,7 +664,7 @@ def modify(cls, sid, **params): ) @classmethod - def retrieve(cls, id, api_key=None, **params): + def retrieve(cls, id, **params): raise NotImplementedError( "Can't retrieve a person without an account ID. " "Use stripe.Account.retrieve_person('account_id', 'person_id') " diff --git a/stripe/_plan.py b/stripe/_plan.py index 37abd66d4..bcee1427e 100644 --- a/stripe/_plan.py +++ b/stripe/_plan.py @@ -382,16 +382,7 @@ class RetrieveParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Plan.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Plan": + def create(cls, **params: Unpack["Plan.CreateParams"]) -> "Plan": """ You can now model subscriptions more flexibly using the [Prices API](https://stripe.com/docs/api#prices). It replaces the Plans API and is backwards compatible to simplify your migration. """ @@ -400,10 +391,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -450,24 +437,13 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] ) @classmethod - def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Plan.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> ListObject["Plan"]: + def list(cls, **params: Unpack["Plan.ListParams"]) -> ListObject["Plan"]: """ Returns a list of your plans. """ result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_plan_service.py b/stripe/_plan_service.py new file mode 100644 index 000000000..9873ad1c6 --- /dev/null +++ b/stripe/_plan_service.py @@ -0,0 +1,332 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._plan import Plan +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, Union, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class PlanService(StripeService): + class CreateParams(TypedDict): + active: NotRequired["bool"] + """ + Whether the plan is currently available for new subscriptions. Defaults to `true`. + """ + aggregate_usage: NotRequired[ + "Literal['last_during_period', 'last_ever', 'max', 'sum']" + ] + """ + Specifies a usage aggregation strategy for plans of `usage_type=metered`. Allowed values are `sum` for summing up all usage during a period, `last_during_period` for using the last usage record reported within a period, `last_ever` for using the last usage record ever (across period bounds) or `max` which uses the usage record with the maximum reported usage during a period. Defaults to `sum`. + """ + amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free plan) representing how much to charge on a recurring basis. + """ + amount_decimal: NotRequired["str"] + """ + Same as `amount`, but accepts a decimal value with at most 12 decimal places. Only one of `amount` and `amount_decimal` can be set. + """ + billing_scheme: NotRequired["Literal['per_unit', 'tiered']"] + """ + Describes how to compute the price per period. Either `per_unit` or `tiered`. `per_unit` indicates that the fixed amount (specified in `amount`) will be charged per unit in `quantity` (for plans with `usage_type=licensed`), or per unit of total usage (for plans with `usage_type=metered`). `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + id: NotRequired["str"] + """ + An identifier randomly generated by Stripe. Used to identify this plan when subscribing a customer. You can optionally override this ID, but the ID must be unique across all plans in your Stripe account. You can, however, use the same plan ID in both live and test modes. + """ + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + nickname: NotRequired["str"] + """ + A brief description of the plan, hidden from customers. + """ + product: NotRequired["PlanService.CreateParamsProduct|str"] + tiers: NotRequired["List[PlanService.CreateParamsTier]"] + """ + Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + """ + tiers_mode: NotRequired["Literal['graduated', 'volume']"] + """ + Defines if the tiering price should be `graduated` or `volume` based. In `volume`-based tiering, the maximum quantity within a period determines the per unit price, in `graduated` tiering pricing can successively change as the quantity grows. + """ + transform_usage: NotRequired["PlanService.CreateParamsTransformUsage"] + """ + Apply a transformation to the reported usage or set quantity before computing the billed price. Cannot be combined with `tiers`. + """ + trial_period_days: NotRequired["int"] + """ + Default number of trial days when subscribing a customer to this plan using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan). + """ + usage_type: NotRequired["Literal['licensed', 'metered']"] + """ + Configures how the quantity per period should be determined. Can be either `metered` or `licensed`. `licensed` automatically bills the `quantity` set when adding it to a subscription. `metered` aggregates the total usage based on usage records. Defaults to `licensed`. + """ + + class CreateParamsProduct(TypedDict): + active: NotRequired["bool"] + """ + Whether the product is currently available for purchase. Defaults to `true`. + """ + id: NotRequired["str"] + """ + The identifier for the product. Must be unique. If not provided, an identifier will be randomly generated. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: str + """ + The product's name, meant to be displayable to the customer. + """ + statement_descriptor: NotRequired["str"] + """ + An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all. + + This may be up to 22 characters. The statement description may not include `<`, `>`, `\\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + """ + tax_code: NotRequired["str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + """ + unit_label: NotRequired["str"] + """ + A label that represents units of this product. When set, this will be included in customers' receipts, invoices, Checkout, and the customer portal. + """ + + class CreateParamsTier(TypedDict): + flat_amount: NotRequired["int"] + """ + The flat billing amount for an entire tier, regardless of the number of units in the tier. + """ + flat_amount_decimal: NotRequired["str"] + """ + Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + """ + unit_amount: NotRequired["int"] + """ + The per unit billing amount for each individual unit for which this tier applies. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + up_to: Union[Literal["inf"], int] + """ + Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + """ + + class CreateParamsTransformUsage(TypedDict): + divide_by: int + """ + Divide usage by this number. + """ + round: Literal["down", "up"] + """ + After division, either round the result `up` or `down`. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + active: NotRequired["bool"] + """ + Only return plans that are active or inactive (e.g., pass `false` to list all inactive plans). + """ + created: NotRequired["PlanService.ListParamsCreated|int"] + """ + A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + product: NotRequired["str"] + """ + Only return plans for the given product. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + active: NotRequired["bool"] + """ + Whether the plan is currently available for new subscriptions. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + nickname: NotRequired["str"] + """ + A brief description of the plan, hidden from customers. + """ + product: NotRequired["str"] + """ + The product the plan belongs to. This cannot be changed once it has been used in a subscription or subscription schedule. + """ + trial_period_days: NotRequired["int"] + """ + Default number of trial days when subscribing a customer to this plan using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan). + """ + + def delete( + self, + plan: str, + params: "PlanService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> Plan: + """ + Deleting plans means new subscribers can't be added. Existing subscribers aren't affected. + """ + return cast( + Plan, + self._requestor.request( + "delete", + "/v1/plans/{plan}".format(plan=_util.sanitize_id(plan)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + plan: str, + params: "PlanService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Plan: + """ + Retrieves the plan with the given ID. + """ + return cast( + Plan, + self._requestor.request( + "get", + "/v1/plans/{plan}".format(plan=_util.sanitize_id(plan)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + plan: str, + params: "PlanService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Plan: + """ + Updates the specified plan by setting the values of the parameters passed. Any parameters not provided are left unchanged. By design, you cannot change a plan's ID, amount, currency, or billing cycle. + """ + return cast( + Plan, + self._requestor.request( + "post", + "/v1/plans/{plan}".format(plan=_util.sanitize_id(plan)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "PlanService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Plan]: + """ + Returns a list of your plans. + """ + return cast( + ListObject[Plan], + self._requestor.request( + "get", + "/v1/plans", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, params: "PlanService.CreateParams", options: RequestOptions = {} + ) -> Plan: + """ + You can now model subscriptions more flexibly using the [Prices API](https://stripe.com/docs/api#prices). It replaces the Plans API and is backwards compatible to simplify your migration. + """ + return cast( + Plan, + self._requestor.request( + "post", + "/v1/plans", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_price.py b/stripe/_price.py index 70bc35989..272b79131 100644 --- a/stripe/_price.py +++ b/stripe/_price.py @@ -720,16 +720,7 @@ class SearchParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Price.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Price": + def create(cls, **params: Unpack["Price.CreateParams"]) -> "Price": """ Creates a new price for an existing product. The price can be recurring or one-time. """ @@ -738,33 +729,18 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod - def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Price.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> ListObject["Price"]: + def list(cls, **params: Unpack["Price.ListParams"]) -> ListObject["Price"]: """ Returns a list of your active prices, excluding [inline prices](https://stripe.com/docs/products-prices/pricing-models#inline-pricing). For the list of inactive prices, set active to false. """ result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_price_service.py b/stripe/_price_service.py new file mode 100644 index 000000000..2748d1c46 --- /dev/null +++ b/stripe/_price_service.py @@ -0,0 +1,577 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._price import Price +from stripe._request_options import RequestOptions +from stripe._search_result_object import SearchResultObject +from stripe._stripe_service import StripeService +from typing import Dict, List, Union, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class PriceService(StripeService): + class CreateParams(TypedDict): + active: NotRequired["bool"] + """ + Whether the price can be used for new purchases. Defaults to `true`. + """ + billing_scheme: NotRequired["Literal['per_unit', 'tiered']"] + """ + Describes how to compute the price per period. Either `per_unit` or `tiered`. `per_unit` indicates that the fixed amount (specified in `unit_amount` or `unit_amount_decimal`) will be charged per unit in `quantity` (for prices with `usage_type=licensed`), or per unit of total usage (for prices with `usage_type=metered`). `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + currency_options: NotRequired[ + "Dict[str, PriceService.CreateParamsCurrencyOptions]" + ] + """ + Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + """ + custom_unit_amount: NotRequired[ + "PriceService.CreateParamsCustomUnitAmount" + ] + """ + When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + lookup_key: NotRequired["str"] + """ + A lookup key used to retrieve prices dynamically from a static string. This may be up to 200 characters. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + nickname: NotRequired["str"] + """ + A brief description of the price, hidden from customers. + """ + product: NotRequired["str"] + """ + The ID of the product that this price will belong to. + """ + product_data: NotRequired["PriceService.CreateParamsProductData"] + """ + These fields can be used to create a new product that this price will belong to. + """ + recurring: NotRequired["PriceService.CreateParamsRecurring"] + """ + The recurring components of a price such as `interval` and `usage_type`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + tiers: NotRequired["List[PriceService.CreateParamsTier]"] + """ + Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + """ + tiers_mode: NotRequired["Literal['graduated', 'volume']"] + """ + Defines if the tiering price should be `graduated` or `volume` based. In `volume`-based tiering, the maximum quantity within a period determines the per unit price, in `graduated` tiering pricing can successively change as the quantity grows. + """ + transfer_lookup_key: NotRequired["bool"] + """ + If set to true, will atomically remove the lookup key from the existing price, and assign it to this price. + """ + transform_quantity: NotRequired[ + "PriceService.CreateParamsTransformQuantity" + ] + """ + Apply a transformation to the reported usage or set quantity before computing the billed price. Cannot be combined with `tiers`. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. One of `unit_amount` or `custom_unit_amount` is required, unless `billing_scheme=tiered`. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class CreateParamsCurrencyOptions(TypedDict): + custom_unit_amount: NotRequired[ + "PriceService.CreateParamsCurrencyOptionsCustomUnitAmount" + ] + """ + When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + tiers: NotRequired[ + "List[PriceService.CreateParamsCurrencyOptionsTier]" + ] + """ + Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class CreateParamsCurrencyOptionsCustomUnitAmount(TypedDict): + enabled: bool + """ + Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + """ + maximum: NotRequired["int"] + """ + The maximum unit amount the customer can specify for this item. + """ + minimum: NotRequired["int"] + """ + The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + """ + preset: NotRequired["int"] + """ + The starting unit amount which can be updated by the customer. + """ + + class CreateParamsCurrencyOptionsTier(TypedDict): + flat_amount: NotRequired["int"] + """ + The flat billing amount for an entire tier, regardless of the number of units in the tier. + """ + flat_amount_decimal: NotRequired["str"] + """ + Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + """ + unit_amount: NotRequired["int"] + """ + The per unit billing amount for each individual unit for which this tier applies. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + up_to: Union[Literal["inf"], int] + """ + Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + """ + + class CreateParamsCustomUnitAmount(TypedDict): + enabled: bool + """ + Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + """ + maximum: NotRequired["int"] + """ + The maximum unit amount the customer can specify for this item. + """ + minimum: NotRequired["int"] + """ + The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + """ + preset: NotRequired["int"] + """ + The starting unit amount which can be updated by the customer. + """ + + class CreateParamsProductData(TypedDict): + active: NotRequired["bool"] + """ + Whether the product is currently available for purchase. Defaults to `true`. + """ + id: NotRequired["str"] + """ + The identifier for the product. Must be unique. If not provided, an identifier will be randomly generated. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: str + """ + The product's name, meant to be displayable to the customer. + """ + statement_descriptor: NotRequired["str"] + """ + An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all. + + This may be up to 22 characters. The statement description may not include `<`, `>`, `\\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + """ + tax_code: NotRequired["str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + """ + unit_label: NotRequired["str"] + """ + A label that represents units of this product. When set, this will be included in customers' receipts, invoices, Checkout, and the customer portal. + """ + + class CreateParamsRecurring(TypedDict): + aggregate_usage: NotRequired[ + "Literal['last_during_period', 'last_ever', 'max', 'sum']" + ] + """ + Specifies a usage aggregation strategy for prices of `usage_type=metered`. Defaults to `sum`. + """ + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + trial_period_days: NotRequired["int"] + """ + Default number of trial days when subscribing a customer to this price using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan). + """ + usage_type: NotRequired["Literal['licensed', 'metered']"] + """ + Configures how the quantity per period should be determined. Can be either `metered` or `licensed`. `licensed` automatically bills the `quantity` set when adding it to a subscription. `metered` aggregates the total usage based on usage records. Defaults to `licensed`. + """ + + class CreateParamsTier(TypedDict): + flat_amount: NotRequired["int"] + """ + The flat billing amount for an entire tier, regardless of the number of units in the tier. + """ + flat_amount_decimal: NotRequired["str"] + """ + Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + """ + unit_amount: NotRequired["int"] + """ + The per unit billing amount for each individual unit for which this tier applies. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + up_to: Union[Literal["inf"], int] + """ + Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + """ + + class CreateParamsTransformQuantity(TypedDict): + divide_by: int + """ + Divide usage by this number. + """ + round: Literal["down", "up"] + """ + After division, either round the result `up` or `down`. + """ + + class ListParams(TypedDict): + active: NotRequired["bool"] + """ + Only return prices that are active or inactive (e.g., pass `false` to list all inactive prices). + """ + created: NotRequired["PriceService.ListParamsCreated|int"] + """ + A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + """ + currency: NotRequired["str"] + """ + Only return prices for the given currency. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + lookup_keys: NotRequired["List[str]"] + """ + Only return the price with these lookup_keys, if any exist. + """ + product: NotRequired["str"] + """ + Only return prices for the given product. + """ + recurring: NotRequired["PriceService.ListParamsRecurring"] + """ + Only return prices with these recurring fields. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + type: NotRequired["Literal['one_time', 'recurring']"] + """ + Only return prices of type `recurring` or `one_time`. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ListParamsRecurring(TypedDict): + interval: NotRequired["Literal['day', 'month', 'week', 'year']"] + """ + Filter by billing frequency. Either `day`, `week`, `month` or `year`. + """ + usage_type: NotRequired["Literal['licensed', 'metered']"] + """ + Filter by the usage type for this price. Can be either `metered` or `licensed`. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class SearchParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + page: NotRequired["str"] + """ + A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + """ + query: str + """ + The search query string. See [search query language](https://stripe.com/docs/search#search-query-language) and the list of supported [query fields for prices](https://stripe.com/docs/search#query-fields-for-prices). + """ + + class UpdateParams(TypedDict): + active: NotRequired["bool"] + """ + Whether the price can be used for new purchases. Defaults to `true`. + """ + currency_options: NotRequired[ + "Literal['']|Dict[str, PriceService.UpdateParamsCurrencyOptions]" + ] + """ + Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + lookup_key: NotRequired["str"] + """ + A lookup key used to retrieve prices dynamically from a static string. This may be up to 200 characters. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + nickname: NotRequired["str"] + """ + A brief description of the price, hidden from customers. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + transfer_lookup_key: NotRequired["bool"] + """ + If set to true, will atomically remove the lookup key from the existing price, and assign it to this price. + """ + + class UpdateParamsCurrencyOptions(TypedDict): + custom_unit_amount: NotRequired[ + "PriceService.UpdateParamsCurrencyOptionsCustomUnitAmount" + ] + """ + When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + tiers: NotRequired[ + "List[PriceService.UpdateParamsCurrencyOptionsTier]" + ] + """ + Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class UpdateParamsCurrencyOptionsCustomUnitAmount(TypedDict): + enabled: bool + """ + Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + """ + maximum: NotRequired["int"] + """ + The maximum unit amount the customer can specify for this item. + """ + minimum: NotRequired["int"] + """ + The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + """ + preset: NotRequired["int"] + """ + The starting unit amount which can be updated by the customer. + """ + + class UpdateParamsCurrencyOptionsTier(TypedDict): + flat_amount: NotRequired["int"] + """ + The flat billing amount for an entire tier, regardless of the number of units in the tier. + """ + flat_amount_decimal: NotRequired["str"] + """ + Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + """ + unit_amount: NotRequired["int"] + """ + The per unit billing amount for each individual unit for which this tier applies. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + up_to: Union[Literal["inf"], int] + """ + Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + """ + + def list( + self, + params: "PriceService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Price]: + """ + Returns a list of your active prices, excluding [inline prices](https://stripe.com/docs/products-prices/pricing-models#inline-pricing). For the list of inactive prices, set active to false. + """ + return cast( + ListObject[Price], + self._requestor.request( + "get", + "/v1/prices", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, params: "PriceService.CreateParams", options: RequestOptions = {} + ) -> Price: + """ + Creates a new price for an existing product. The price can be recurring or one-time. + """ + return cast( + Price, + self._requestor.request( + "post", + "/v1/prices", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + price: str, + params: "PriceService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Price: + """ + Retrieves the price with the given ID. + """ + return cast( + Price, + self._requestor.request( + "get", + "/v1/prices/{price}".format(price=_util.sanitize_id(price)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + price: str, + params: "PriceService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Price: + """ + Updates the specified price by setting the values of the parameters passed. Any parameters not provided are left unchanged. + """ + return cast( + Price, + self._requestor.request( + "post", + "/v1/prices/{price}".format(price=_util.sanitize_id(price)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def search( + self, params: "PriceService.SearchParams", options: RequestOptions = {} + ) -> SearchResultObject[Price]: + """ + Search for prices you've previously created using Stripe's [Search Query Language](https://stripe.com/docs/search#search-query-language). + Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating + conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up + to an hour behind during outages. Search functionality is not available to merchants in India. + """ + return cast( + SearchResultObject[Price], + self._requestor.request( + "get", + "/v1/prices/search", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_product.py b/stripe/_product.py index fe48b6cfd..66554a456 100644 --- a/stripe/_product.py +++ b/stripe/_product.py @@ -540,16 +540,7 @@ class SearchParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Product.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Product": + def create(cls, **params: Unpack["Product.CreateParams"]) -> "Product": """ Creates a new product object. """ @@ -558,10 +549,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -611,13 +598,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Product.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Product.ListParams"] ) -> ListObject["Product"]: """ Returns a list of your products. The products are returned sorted by creation date, with the most recently created products appearing first. @@ -625,9 +606,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_product_service.py b/stripe/_product_service.py new file mode 100644 index 000000000..c21a2fc84 --- /dev/null +++ b/stripe/_product_service.py @@ -0,0 +1,523 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._product import Product +from stripe._request_options import RequestOptions +from stripe._search_result_object import SearchResultObject +from stripe._stripe_service import StripeService +from typing import Dict, List, Union, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ProductService(StripeService): + class CreateParams(TypedDict): + active: NotRequired["bool"] + """ + Whether the product is currently available for purchase. Defaults to `true`. + """ + default_price_data: NotRequired[ + "ProductService.CreateParamsDefaultPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object. This Price will be set as the default price for this product. + """ + description: NotRequired["str"] + """ + The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + features: NotRequired["List[ProductService.CreateParamsFeature]"] + """ + A list of up to 15 features for this product. These are displayed in [pricing tables](https://stripe.com/docs/payments/checkout/pricing-table). + """ + id: NotRequired["str"] + """ + An identifier will be randomly generated by Stripe. You can optionally override this ID, but the ID must be unique across all products in your Stripe account. + """ + images: NotRequired["List[str]"] + """ + A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: str + """ + The product's name, meant to be displayable to the customer. + """ + package_dimensions: NotRequired[ + "ProductService.CreateParamsPackageDimensions" + ] + """ + The dimensions of this product for shipping purposes. + """ + shippable: NotRequired["bool"] + """ + Whether this product is shipped (i.e., physical goods). + """ + statement_descriptor: NotRequired["str"] + """ + An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all. + + This may be up to 22 characters. The statement description may not include `<`, `>`, `\\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + It must contain at least one letter. + """ + tax_code: NotRequired["str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + """ + type: NotRequired["Literal['good', 'service']"] + """ + The type of the product. Defaults to `service` if not explicitly specified, enabling use of this product with Subscriptions and Plans. Set this parameter to `good` to use this product with Orders and SKUs. On API versions before `2018-02-05`, this field defaults to `good` for compatibility reasons. + """ + unit_label: NotRequired["str"] + """ + A label that represents units of this product. When set, this will be included in customers' receipts, invoices, Checkout, and the customer portal. + """ + url: NotRequired["str"] + """ + A URL of a publicly-accessible webpage for this product. + """ + + class CreateParamsDefaultPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + currency_options: NotRequired[ + "Dict[str, ProductService.CreateParamsDefaultPriceDataCurrencyOptions]" + ] + """ + Prices defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + """ + recurring: NotRequired[ + "ProductService.CreateParamsDefaultPriceDataRecurring" + ] + """ + The recurring components of a price such as `interval` and `interval_count`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. One of `unit_amount` or `unit_amount_decimal` is required. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class CreateParamsDefaultPriceDataCurrencyOptions(TypedDict): + custom_unit_amount: NotRequired[ + "ProductService.CreateParamsDefaultPriceDataCurrencyOptionsCustomUnitAmount" + ] + """ + When set, provides configuration for the amount to be adjusted by the customer during Checkout Sessions and Payment Links. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + tiers: NotRequired[ + "List[ProductService.CreateParamsDefaultPriceDataCurrencyOptionsTier]" + ] + """ + Each element represents a pricing tier. This parameter requires `billing_scheme` to be set to `tiered`. See also the documentation for `billing_scheme`. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class CreateParamsDefaultPriceDataCurrencyOptionsCustomUnitAmount( + TypedDict, + ): + enabled: bool + """ + Pass in `true` to enable `custom_unit_amount`, otherwise omit `custom_unit_amount`. + """ + maximum: NotRequired["int"] + """ + The maximum unit amount the customer can specify for this item. + """ + minimum: NotRequired["int"] + """ + The minimum unit amount the customer can specify for this item. Must be at least the minimum charge amount. + """ + preset: NotRequired["int"] + """ + The starting unit amount which can be updated by the customer. + """ + + class CreateParamsDefaultPriceDataCurrencyOptionsTier(TypedDict): + flat_amount: NotRequired["int"] + """ + The flat billing amount for an entire tier, regardless of the number of units in the tier. + """ + flat_amount_decimal: NotRequired["str"] + """ + Same as `flat_amount`, but accepts a decimal value representing an integer in the minor units of the currency. Only one of `flat_amount` and `flat_amount_decimal` can be set. + """ + unit_amount: NotRequired["int"] + """ + The per unit billing amount for each individual unit for which this tier applies. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + up_to: Union[Literal["inf"], int] + """ + Specifies the upper bound of this tier. The lower bound of a tier is the upper bound of the previous tier adding one. Use `inf` to define a fallback tier. + """ + + class CreateParamsDefaultPriceDataRecurring(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + + class CreateParamsFeature(TypedDict): + name: str + """ + The feature's name. Up to 80 characters long. + """ + + class CreateParamsPackageDimensions(TypedDict): + height: float + """ + Height, in inches. Maximum precision is 2 decimal places. + """ + length: float + """ + Length, in inches. Maximum precision is 2 decimal places. + """ + weight: float + """ + Weight, in ounces. Maximum precision is 2 decimal places. + """ + width: float + """ + Width, in inches. Maximum precision is 2 decimal places. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + active: NotRequired["bool"] + """ + Only return products that are active or inactive (e.g., pass `false` to list all inactive products). + """ + created: NotRequired["ProductService.ListParamsCreated|int"] + """ + Only return products that were created during the given date interval. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + ids: NotRequired["List[str]"] + """ + Only return products with the given IDs. Cannot be used with [starting_after](https://stripe.com/docs/api#list_products-starting_after) or [ending_before](https://stripe.com/docs/api#list_products-ending_before). + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + shippable: NotRequired["bool"] + """ + Only return products that can be shipped (i.e., physical, not digital products). + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + type: NotRequired["Literal['good', 'service']"] + """ + Only return products of this type. + """ + url: NotRequired["str"] + """ + Only return products with the given url. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class SearchParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + page: NotRequired["str"] + """ + A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + """ + query: str + """ + The search query string. See [search query language](https://stripe.com/docs/search#search-query-language) and the list of supported [query fields for products](https://stripe.com/docs/search#query-fields-for-products). + """ + + class UpdateParams(TypedDict): + active: NotRequired["bool"] + """ + Whether the product is available for purchase. + """ + default_price: NotRequired["str"] + """ + The ID of the [Price](https://stripe.com/docs/api/prices) object that is the default price for this product. + """ + description: NotRequired["Literal['']|str"] + """ + The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + features: NotRequired[ + "Literal['']|List[ProductService.UpdateParamsFeature]" + ] + """ + A list of up to 15 features for this product. These are displayed in [pricing tables](https://stripe.com/docs/payments/checkout/pricing-table). + """ + images: NotRequired["Literal['']|List[str]"] + """ + A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: NotRequired["str"] + """ + The product's name, meant to be displayable to the customer. + """ + package_dimensions: NotRequired[ + "Literal['']|ProductService.UpdateParamsPackageDimensions" + ] + """ + The dimensions of this product for shipping purposes. + """ + shippable: NotRequired["bool"] + """ + Whether this product is shipped (i.e., physical goods). + """ + statement_descriptor: NotRequired["str"] + """ + An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all. + + This may be up to 22 characters. The statement description may not include `<`, `>`, `\\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + It must contain at least one letter. May only be set if `type=service`. + """ + tax_code: NotRequired["Literal['']|str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + """ + unit_label: NotRequired["Literal['']|str"] + """ + A label that represents units of this product. When set, this will be included in customers' receipts, invoices, Checkout, and the customer portal. May only be set if `type=service`. + """ + url: NotRequired["Literal['']|str"] + """ + A URL of a publicly-accessible webpage for this product. + """ + + class UpdateParamsFeature(TypedDict): + name: str + """ + The feature's name. Up to 80 characters long. + """ + + class UpdateParamsPackageDimensions(TypedDict): + height: float + """ + Height, in inches. Maximum precision is 2 decimal places. + """ + length: float + """ + Length, in inches. Maximum precision is 2 decimal places. + """ + weight: float + """ + Weight, in ounces. Maximum precision is 2 decimal places. + """ + width: float + """ + Width, in inches. Maximum precision is 2 decimal places. + """ + + def delete( + self, + id: str, + params: "ProductService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> Product: + """ + Delete a product. Deleting a product is only possible if it has no prices associated with it. Additionally, deleting a product with type=good is only possible if it has no SKUs associated with it. + """ + return cast( + Product, + self._requestor.request( + "delete", + "/v1/products/{id}".format(id=_util.sanitize_id(id)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + id: str, + params: "ProductService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Product: + """ + Retrieves the details of an existing product. Supply the unique product ID from either a product creation request or the product list, and Stripe will return the corresponding product information. + """ + return cast( + Product, + self._requestor.request( + "get", + "/v1/products/{id}".format(id=_util.sanitize_id(id)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + id: str, + params: "ProductService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Product: + """ + Updates the specific product by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + """ + return cast( + Product, + self._requestor.request( + "post", + "/v1/products/{id}".format(id=_util.sanitize_id(id)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "ProductService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Product]: + """ + Returns a list of your products. The products are returned sorted by creation date, with the most recently created products appearing first. + """ + return cast( + ListObject[Product], + self._requestor.request( + "get", + "/v1/products", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "ProductService.CreateParams", + options: RequestOptions = {}, + ) -> Product: + """ + Creates a new product object. + """ + return cast( + Product, + self._requestor.request( + "post", + "/v1/products", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def search( + self, + params: "ProductService.SearchParams", + options: RequestOptions = {}, + ) -> SearchResultObject[Product]: + """ + Search for products you've previously created using Stripe's [Search Query Language](https://stripe.com/docs/search#search-query-language). + Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating + conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up + to an hour behind during outages. Search functionality is not available to merchants in India. + """ + return cast( + SearchResultObject[Product], + self._requestor.request( + "get", + "/v1/products/search", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_promotion_code.py b/stripe/_promotion_code.py index 33a84505a..0d96e0329 100644 --- a/stripe/_promotion_code.py +++ b/stripe/_promotion_code.py @@ -272,14 +272,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PromotionCode.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["PromotionCode.CreateParams"] ) -> "PromotionCode": """ A promotion code points to a coupon. You can optionally restrict the code to a specific customer, redemption limit, and expiration date. @@ -289,23 +282,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "PromotionCode.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["PromotionCode.ListParams"] ) -> ListObject["PromotionCode"]: """ Returns a list of your promotion codes. @@ -313,9 +296,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_promotion_code_service.py b/stripe/_promotion_code_service.py new file mode 100644 index 000000000..2c96e7d7f --- /dev/null +++ b/stripe/_promotion_code_service.py @@ -0,0 +1,259 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._promotion_code import PromotionCode +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class PromotionCodeService(StripeService): + class CreateParams(TypedDict): + active: NotRequired["bool"] + """ + Whether the promotion code is currently active. + """ + code: NotRequired["str"] + """ + The customer-facing code. Regardless of case, this code must be unique across all active promotion codes for a specific customer. If left blank, we will generate one automatically. + """ + coupon: str + """ + The coupon for this promotion code. + """ + customer: NotRequired["str"] + """ + The customer that this promotion code can be used by. If not set, the promotion code can be used by all customers. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + expires_at: NotRequired["int"] + """ + The timestamp at which this promotion code will expire. If the coupon has specified a `redeems_by`, then this value cannot be after the coupon's `redeems_by`. + """ + max_redemptions: NotRequired["int"] + """ + A positive integer specifying the number of times the promotion code can be redeemed. If the coupon has specified a `max_redemptions`, then this value cannot be greater than the coupon's `max_redemptions`. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + restrictions: NotRequired[ + "PromotionCodeService.CreateParamsRestrictions" + ] + """ + Settings that restrict the redemption of the promotion code. + """ + + class CreateParamsRestrictions(TypedDict): + currency_options: NotRequired[ + "Dict[str, PromotionCodeService.CreateParamsRestrictionsCurrencyOptions]" + ] + """ + Promotion codes defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + """ + first_time_transaction: NotRequired["bool"] + """ + A Boolean indicating if the Promotion Code should only be redeemed for Customers without any successful payments or invoices + """ + minimum_amount: NotRequired["int"] + """ + Minimum amount required to redeem this Promotion Code into a Coupon (e.g., a purchase must be $100 or more to work). + """ + minimum_amount_currency: NotRequired["str"] + """ + Three-letter [ISO code](https://stripe.com/docs/currencies) for minimum_amount + """ + + class CreateParamsRestrictionsCurrencyOptions(TypedDict): + minimum_amount: NotRequired["int"] + """ + Minimum amount required to redeem this Promotion Code into a Coupon (e.g., a purchase must be $100 or more to work). + """ + + class ListParams(TypedDict): + active: NotRequired["bool"] + """ + Filter promotion codes by whether they are active. + """ + code: NotRequired["str"] + """ + Only return promotion codes that have this case-insensitive code. + """ + coupon: NotRequired["str"] + """ + Only return promotion codes for this coupon. + """ + created: NotRequired["PromotionCodeService.ListParamsCreated|int"] + """ + A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + """ + customer: NotRequired["str"] + """ + Only return promotion codes that are restricted to this customer. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + active: NotRequired["bool"] + """ + Whether the promotion code is currently active. A promotion code can only be reactivated when the coupon is still valid and the promotion code is otherwise redeemable. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + restrictions: NotRequired[ + "PromotionCodeService.UpdateParamsRestrictions" + ] + """ + Settings that restrict the redemption of the promotion code. + """ + + class UpdateParamsRestrictions(TypedDict): + currency_options: NotRequired[ + "Dict[str, PromotionCodeService.UpdateParamsRestrictionsCurrencyOptions]" + ] + """ + Promotion codes defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + """ + + class UpdateParamsRestrictionsCurrencyOptions(TypedDict): + minimum_amount: NotRequired["int"] + """ + Minimum amount required to redeem this Promotion Code into a Coupon (e.g., a purchase must be $100 or more to work). + """ + + def list( + self, + params: "PromotionCodeService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[PromotionCode]: + """ + Returns a list of your promotion codes. + """ + return cast( + ListObject[PromotionCode], + self._requestor.request( + "get", + "/v1/promotion_codes", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "PromotionCodeService.CreateParams", + options: RequestOptions = {}, + ) -> PromotionCode: + """ + A promotion code points to a coupon. You can optionally restrict the code to a specific customer, redemption limit, and expiration date. + """ + return cast( + PromotionCode, + self._requestor.request( + "post", + "/v1/promotion_codes", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + promotion_code: str, + params: "PromotionCodeService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> PromotionCode: + """ + Retrieves the promotion code with the given ID. In order to retrieve a promotion code by the customer-facing code use [list](https://stripe.com/docs/api/promotion_codes/list) with the desired code. + """ + return cast( + PromotionCode, + self._requestor.request( + "get", + "/v1/promotion_codes/{promotion_code}".format( + promotion_code=_util.sanitize_id(promotion_code), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + promotion_code: str, + params: "PromotionCodeService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> PromotionCode: + """ + Updates the specified promotion code by setting the values of the parameters passed. Most fields are, by design, not editable. + """ + return cast( + PromotionCode, + self._requestor.request( + "post", + "/v1/promotion_codes/{promotion_code}".format( + promotion_code=_util.sanitize_id(promotion_code), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_quote.py b/stripe/_quote.py index d6129482a..2bdf32861 100644 --- a/stripe/_quote.py +++ b/stripe/_quote.py @@ -1,8 +1,6 @@ # -*- coding: utf-8 -*- # File generated from our OpenAPI spec -import stripe from stripe import _util -from stripe._api_requestor import APIRequestor from stripe._createable_api_resource import CreateableAPIResource from stripe._expandable_field import ExpandableField from stripe._list_object import ListObject @@ -11,7 +9,7 @@ from stripe._stripe_object import StripeObject from stripe._updateable_api_resource import UpdateableAPIResource from stripe._util import class_method_variant -from typing import ClassVar, Dict, List, Optional, cast, overload +from typing import Any, ClassVar, Dict, List, Optional, cast, overload from typing_extensions import ( Literal, NotRequired, @@ -971,6 +969,12 @@ class ModifyParamsTransferData(TypedDict): ID of an existing, connected Stripe account. """ + class PdfParams(RequestOptions): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + class RetrieveParams(RequestOptions): expand: NotRequired["List[str]"] """ @@ -1102,14 +1106,7 @@ class RetrieveParams(RequestOptions): @classmethod def _cls_accept( - cls, - quote: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Quote.AcceptParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, quote: str, **params: Unpack["Quote.AcceptParams"] ) -> "Quote": """ Accepts the specified quote. @@ -1121,37 +1118,20 @@ def _cls_accept( "/v1/quotes/{quote}/accept".format( quote=_util.sanitize_id(quote) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @overload @staticmethod - def accept( - quote: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Quote.AcceptParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Quote": + def accept(quote: str, **params: Unpack["Quote.AcceptParams"]) -> "Quote": """ Accepts the specified quote. """ ... @overload - def accept( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Quote.AcceptParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Quote": + def accept(self, **params: Unpack["Quote.AcceptParams"]) -> "Quote": """ Accepts the specified quote. """ @@ -1159,11 +1139,7 @@ def accept( @class_method_variant("_cls_accept") def accept( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Quote.AcceptParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Quote.AcceptParams"] ) -> "Quote": """ Accepts the specified quote. @@ -1175,21 +1151,13 @@ def accept( # pyright: ignore[reportGeneralTypeIssues] "/v1/quotes/{quote}/accept".format( quote=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_cancel( - cls, - quote: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Quote.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, quote: str, **params: Unpack["Quote.CancelParams"] ) -> "Quote": """ Cancels the quote. @@ -1201,37 +1169,20 @@ def _cls_cancel( "/v1/quotes/{quote}/cancel".format( quote=_util.sanitize_id(quote) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @overload @staticmethod - def cancel( - quote: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Quote.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Quote": + def cancel(quote: str, **params: Unpack["Quote.CancelParams"]) -> "Quote": """ Cancels the quote. """ ... @overload - def cancel( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Quote.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Quote": + def cancel(self, **params: Unpack["Quote.CancelParams"]) -> "Quote": """ Cancels the quote. """ @@ -1239,11 +1190,7 @@ def cancel( @class_method_variant("_cls_cancel") def cancel( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Quote.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Quote.CancelParams"] ) -> "Quote": """ Cancels the quote. @@ -1255,22 +1202,12 @@ def cancel( # pyright: ignore[reportGeneralTypeIssues] "/v1/quotes/{quote}/cancel".format( quote=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Quote.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Quote": + def create(cls, **params: Unpack["Quote.CreateParams"]) -> "Quote": """ A quote models prices and services for a customer. Default options for header, description, footer, and expires_at can be set in the dashboard via the [quote template](https://dashboard.stripe.com/settings/billing/quote). """ @@ -1279,24 +1216,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def _cls_finalize_quote( - cls, - quote: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Quote.FinalizeQuoteParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, quote: str, **params: Unpack["Quote.FinalizeQuoteParams"] ) -> "Quote": """ Finalizes the quote. @@ -1308,9 +1234,6 @@ def _cls_finalize_quote( "/v1/quotes/{quote}/finalize".format( quote=_util.sanitize_id(quote) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1318,13 +1241,7 @@ def _cls_finalize_quote( @overload @staticmethod def finalize_quote( - quote: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Quote.FinalizeQuoteParams" - ] # pyright: ignore[reportGeneralTypeIssues] + quote: str, **params: Unpack["Quote.FinalizeQuoteParams"] ) -> "Quote": """ Finalizes the quote. @@ -1333,11 +1250,7 @@ def finalize_quote( @overload def finalize_quote( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Quote.FinalizeQuoteParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Quote.FinalizeQuoteParams"] ) -> "Quote": """ Finalizes the quote. @@ -1346,11 +1259,7 @@ def finalize_quote( @class_method_variant("_cls_finalize_quote") def finalize_quote( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Quote.FinalizeQuoteParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Quote.FinalizeQuoteParams"] ) -> "Quote": """ Finalizes the quote. @@ -1362,30 +1271,18 @@ def finalize_quote( # pyright: ignore[reportGeneralTypeIssues] "/v1/quotes/{quote}/finalize".format( quote=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod - def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Quote.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> ListObject["Quote"]: + def list(cls, **params: Unpack["Quote.ListParams"]) -> ListObject["Quote"]: """ Returns a list of your quotes. """ result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -1401,12 +1298,7 @@ def list( def _cls_list_computed_upfront_line_items( cls, quote: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Quote.ListComputedUpfrontLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Quote.ListComputedUpfrontLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a quote, there is an includable [computed.upfront.line_items](https://stripe.com/docs/api/quotes/object#quote_object-computed-upfront-line_items) property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of upfront line items. @@ -1418,9 +1310,6 @@ def _cls_list_computed_upfront_line_items( "/v1/quotes/{quote}/computed_upfront_line_items".format( quote=_util.sanitize_id(quote) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1429,12 +1318,7 @@ def _cls_list_computed_upfront_line_items( @staticmethod def list_computed_upfront_line_items( quote: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Quote.ListComputedUpfrontLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Quote.ListComputedUpfrontLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a quote, there is an includable [computed.upfront.line_items](https://stripe.com/docs/api/quotes/object#quote_object-computed-upfront-line_items) property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of upfront line items. @@ -1443,11 +1327,7 @@ def list_computed_upfront_line_items( @overload def list_computed_upfront_line_items( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Quote.ListComputedUpfrontLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Quote.ListComputedUpfrontLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a quote, there is an includable [computed.upfront.line_items](https://stripe.com/docs/api/quotes/object#quote_object-computed-upfront-line_items) property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of upfront line items. @@ -1456,11 +1336,7 @@ def list_computed_upfront_line_items( @class_method_variant("_cls_list_computed_upfront_line_items") def list_computed_upfront_line_items( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Quote.ListComputedUpfrontLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Quote.ListComputedUpfrontLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a quote, there is an includable [computed.upfront.line_items](https://stripe.com/docs/api/quotes/object#quote_object-computed-upfront-line_items) property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of upfront line items. @@ -1472,21 +1348,13 @@ def list_computed_upfront_line_items( # pyright: ignore[reportGeneralTypeIssues "/v1/quotes/{quote}/computed_upfront_line_items".format( quote=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_list_line_items( - cls, - quote: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Quote.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, quote: str, **params: Unpack["Quote.ListLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a quote, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -1498,9 +1366,6 @@ def _cls_list_line_items( "/v1/quotes/{quote}/line_items".format( quote=_util.sanitize_id(quote) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1508,13 +1373,7 @@ def _cls_list_line_items( @overload @staticmethod def list_line_items( - quote: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Quote.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + quote: str, **params: Unpack["Quote.ListLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a quote, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -1523,11 +1382,7 @@ def list_line_items( @overload def list_line_items( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Quote.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Quote.ListLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a quote, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -1536,11 +1391,7 @@ def list_line_items( @class_method_variant("_cls_list_line_items") def list_line_items( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Quote.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Quote.ListLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a quote, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -1552,7 +1403,6 @@ def list_line_items( # pyright: ignore[reportGeneralTypeIssues] "/v1/quotes/{quote}/line_items".format( quote=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -1571,82 +1421,65 @@ def modify( ) @classmethod - def retrieve( - cls, id: str, **params: Unpack["Quote.RetrieveParams"] - ) -> "Quote": + def _cls_pdf(cls, quote: str, **params: Unpack["Quote.PdfParams"]) -> Any: """ - Retrieves the quote with the given ID. + Download the PDF for a finalized quote """ - instance = cls(id, **params) - instance.refresh() - return instance - - @classmethod - def _cls_pdf( - cls, - sid, - api_key=None, - idempotency_key=None, - stripe_version=None, - stripe_account=None, - **params - ): - url = "%s/%s/%s" % ( - cls.class_url(), - quote_plus(sid), - "pdf", - ) - requestor = APIRequestor( - api_key, - api_base=stripe.upload_api_base, - api_version=stripe_version, - account=stripe_account, + return cast( + Any, + cls._static_request_stream( + "get", + "/v1/quotes/{quote}/pdf".format( + quote=_util.sanitize_id(quote) + ), + params=params, + base_address="files", + ), ) - headers = _util.populate_headers(idempotency_key) - response, _ = requestor.request_stream("get", url, params, headers) - return response @overload @staticmethod - def pdf( - sid, - api_key=None, - idempotency_key=None, - stripe_version=None, - stripe_account=None, - **params - ): + def pdf(quote: str, **params: Unpack["Quote.PdfParams"]) -> Any: + """ + Download the PDF for a finalized quote + """ ... @overload - def pdf( - self, - api_key=None, - api_version=None, - stripe_version=None, - stripe_account=None, - **params - ): + def pdf(self, **params: Unpack["Quote.PdfParams"]) -> Any: + """ + Download the PDF for a finalized quote + """ ... - @_util.class_method_variant("_cls_pdf") - def pdf( # pyright: ignore - self, - api_key=None, - api_version=None, - stripe_version=None, - stripe_account=None, - **params - ): - version = api_version or stripe_version - requestor = APIRequestor( - api_key, - api_base=stripe.upload_api_base, - api_version=version, - account=stripe_account, + @class_method_variant("_cls_pdf") + def pdf( # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Quote.PdfParams"] + ) -> Any: + """ + Download the PDF for a finalized quote + """ + return cast( + Any, + self._request_stream( + "get", + "/v1/quotes/{quote}/pdf".format( + quote=_util.sanitize_id(self.get("id")) + ), + params=params, + ), ) - url = self.instance_url() + "/pdf" - return requestor.request_stream("get", url, params=params) + + @classmethod + def retrieve( + cls, id: str, **params: Unpack["Quote.RetrieveParams"] + ) -> "Quote": + """ + Retrieves the quote with the given ID. + """ + instance = cls(id, **params) + instance.refresh() + return instance _inner_class_types = { "automatic_tax": AutomaticTax, diff --git a/stripe/_quote_computed_upfront_line_items_service.py b/stripe/_quote_computed_upfront_line_items_service.py new file mode 100644 index 000000000..1aa0487c6 --- /dev/null +++ b/stripe/_quote_computed_upfront_line_items_service.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._line_item import LineItem +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class QuoteComputedUpfrontLineItemsService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + def list( + self, + quote: str, + params: "QuoteComputedUpfrontLineItemsService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[LineItem]: + """ + When retrieving a quote, there is an includable [computed.upfront.line_items](https://stripe.com/docs/api/quotes/object#quote_object-computed-upfront-line_items) property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of upfront line items. + """ + return cast( + ListObject[LineItem], + self._requestor.request( + "get", + "/v1/quotes/{quote}/computed_upfront_line_items".format( + quote=_util.sanitize_id(quote), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_quote_line_item_service.py b/stripe/_quote_line_item_service.py new file mode 100644 index 000000000..dd3d61de6 --- /dev/null +++ b/stripe/_quote_line_item_service.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._line_item import LineItem +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class QuoteLineItemService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + def list( + self, + quote: str, + params: "QuoteLineItemService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[LineItem]: + """ + When retrieving a quote, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. + """ + return cast( + ListObject[LineItem], + self._requestor.request( + "get", + "/v1/quotes/{quote}/line_items".format( + quote=_util.sanitize_id(quote), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_quote_service.py b/stripe/_quote_service.py new file mode 100644 index 000000000..0584404c6 --- /dev/null +++ b/stripe/_quote_service.py @@ -0,0 +1,740 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._quote import Quote +from stripe._quote_computed_upfront_line_items_service import ( + QuoteComputedUpfrontLineItemsService, +) +from stripe._quote_line_item_service import QuoteLineItemService +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Any, Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class QuoteService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.line_items = QuoteLineItemService(self._requestor) + self.computed_upfront_line_items = ( + QuoteComputedUpfrontLineItemsService( + self._requestor, + ) + ) + + class AcceptParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CancelParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CreateParams(TypedDict): + application_fee_amount: NotRequired["Literal['']|int"] + """ + The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. There cannot be any line items with recurring prices when using this field. + """ + application_fee_percent: NotRequired["Literal['']|float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. There must be at least 1 line item with a recurring price to use this field. + """ + automatic_tax: NotRequired["QuoteService.CreateParamsAutomaticTax"] + """ + Settings for automatic tax lookup for this quote and resulting invoices and subscriptions. + """ + collection_method: NotRequired[ + "Literal['charge_automatically', 'send_invoice']" + ] + """ + Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay invoices at the end of the subscription cycle or at invoice finalization using the default payment method attached to the subscription or customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically`. + """ + customer: NotRequired["str"] + """ + The customer for which this quote belongs to. A customer is required before finalizing the quote. Once specified, it cannot be changed. + """ + default_tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates that will apply to any line item that does not have `tax_rates` set. + """ + description: NotRequired["Literal['']|str"] + """ + A description that will be displayed on the quote PDF. If no value is passed, the default description configured in your [quote template settings](https://dashboard.stripe.com/settings/billing/quote) will be used. + """ + discounts: NotRequired[ + "Literal['']|List[QuoteService.CreateParamsDiscount]" + ] + """ + The discounts applied to the quote. You can only set up to one discount. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + expires_at: NotRequired["int"] + """ + A future timestamp on which the quote will be canceled if in `open` or `draft` status. Measured in seconds since the Unix epoch. If no value is passed, the default expiration date configured in your [quote template settings](https://dashboard.stripe.com/settings/billing/quote) will be used. + """ + footer: NotRequired["Literal['']|str"] + """ + A footer that will be displayed on the quote PDF. If no value is passed, the default footer configured in your [quote template settings](https://dashboard.stripe.com/settings/billing/quote) will be used. + """ + from_quote: NotRequired["QuoteService.CreateParamsFromQuote"] + """ + Clone an existing quote. The new quote will be created in `status=draft`. When using this parameter, you cannot specify any other parameters except for `expires_at`. + """ + header: NotRequired["Literal['']|str"] + """ + A header that will be displayed on the quote PDF. If no value is passed, the default header configured in your [quote template settings](https://dashboard.stripe.com/settings/billing/quote) will be used. + """ + invoice_settings: NotRequired[ + "QuoteService.CreateParamsInvoiceSettings" + ] + """ + All invoices will be billed using the specified settings. + """ + line_items: NotRequired["List[QuoteService.CreateParamsLineItem]"] + """ + A list of line items the customer is being quoted for. Each line item includes information about the product, the quantity, and the resulting cost. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + on_behalf_of: NotRequired["Literal['']|str"] + """ + The account on behalf of which to charge. + """ + subscription_data: NotRequired[ + "QuoteService.CreateParamsSubscriptionData" + ] + """ + When creating a subscription or subscription schedule, the specified configuration data will be used. There must be at least one line item with a recurring price for a subscription or subscription schedule to be created. A subscription schedule is created if `subscription_data[effective_date]` is present and in the future, otherwise a subscription is created. + """ + test_clock: NotRequired["str"] + """ + ID of the test clock to attach to the quote. + """ + transfer_data: NotRequired[ + "Literal['']|QuoteService.CreateParamsTransferData" + ] + """ + The data with which to automatically create a Transfer for each of the invoices. + """ + + class CreateParamsAutomaticTax(TypedDict): + enabled: bool + """ + Controls whether Stripe will automatically compute tax on the resulting invoices or subscriptions as well as the quote itself. + """ + liability: NotRequired[ + "QuoteService.CreateParamsAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class CreateParamsAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsDiscount(TypedDict): + coupon: NotRequired["str"] + """ + ID of the coupon to create a new discount for. + """ + discount: NotRequired["str"] + """ + ID of an existing discount on the object (or one of its ancestors) to reuse. + """ + + class CreateParamsFromQuote(TypedDict): + is_revision: NotRequired["bool"] + """ + Whether this quote is a revision of the previous quote. + """ + quote: str + """ + The `id` of the quote that will be cloned. + """ + + class CreateParamsInvoiceSettings(TypedDict): + days_until_due: NotRequired["int"] + """ + Number of days within which a customer must pay the invoice generated by this quote. This value will be `null` for quotes where `collection_method=charge_automatically`. + """ + issuer: NotRequired["QuoteService.CreateParamsInvoiceSettingsIssuer"] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + + class CreateParamsInvoiceSettingsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsLineItem(TypedDict): + price: NotRequired["str"] + """ + The ID of the price object. One of `price` or `price_data` is required. + """ + price_data: NotRequired["QuoteService.CreateParamsLineItemPriceData"] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + """ + quantity: NotRequired["int"] + """ + The quantity of the line item. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates which apply to the line item. When set, the `default_tax_rates` on the quote do not apply to this line item. + """ + + class CreateParamsLineItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + recurring: NotRequired[ + "QuoteService.CreateParamsLineItemPriceDataRecurring" + ] + """ + The recurring components of a price such as `interval` and `interval_count`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class CreateParamsLineItemPriceDataRecurring(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + + class CreateParamsSubscriptionData(TypedDict): + description: NotRequired["str"] + """ + The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + """ + effective_date: NotRequired[ + "Literal['']|Literal['current_period_end']|int" + ] + """ + When creating a new subscription, the date of which the subscription schedule will start after the quote is accepted. When updating a subscription, the date of which the subscription will be updated using a subscription schedule. The special value `current_period_end` can be provided to update a subscription at the end of its current period. The `effective_date` is ignored if it is in the past when the quote is accepted. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will set metadata on the subscription or subscription schedule when the quote is accepted. If a recurring price is included in `line_items`, this field will be passed to the resulting subscription's `metadata` field. If `subscription_data.effective_date` is used, this field will be passed to the resulting subscription schedule's `phases.metadata` field. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + """ + trial_period_days: NotRequired["Literal['']|int"] + """ + Integer representing the number of trial period days before the customer is charged for the first time. + """ + + class CreateParamsTransferData(TypedDict): + amount: NotRequired["int"] + """ + The amount that will be transferred automatically when the invoice is paid. If no amount is set, the full amount is transferred. There cannot be any line items with recurring prices when using this field. + """ + amount_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. There must be at least 1 line item with a recurring price to use this field. + """ + destination: str + """ + ID of an existing, connected Stripe account. + """ + + class FinalizeQuoteParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + expires_at: NotRequired["int"] + """ + A future timestamp on which the quote will be canceled if in `open` or `draft` status. Measured in seconds since the Unix epoch. + """ + + class ListParams(TypedDict): + customer: NotRequired["str"] + """ + The ID of the customer whose quotes will be retrieved. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired["Literal['accepted', 'canceled', 'draft', 'open']"] + """ + The status of the quote. + """ + test_clock: NotRequired["str"] + """ + Provides a list of quotes that are associated with the specified test clock. The response will not include quotes with test clocks if this and the customer parameter is not set. + """ + + class PdfParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + application_fee_amount: NotRequired["Literal['']|int"] + """ + The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. There cannot be any line items with recurring prices when using this field. + """ + application_fee_percent: NotRequired["Literal['']|float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. There must be at least 1 line item with a recurring price to use this field. + """ + automatic_tax: NotRequired["QuoteService.UpdateParamsAutomaticTax"] + """ + Settings for automatic tax lookup for this quote and resulting invoices and subscriptions. + """ + collection_method: NotRequired[ + "Literal['charge_automatically', 'send_invoice']" + ] + """ + Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay invoices at the end of the subscription cycle or at invoice finalization using the default payment method attached to the subscription or customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically`. + """ + customer: NotRequired["str"] + """ + The customer for which this quote belongs to. A customer is required before finalizing the quote. Once specified, it cannot be changed. + """ + default_tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates that will apply to any line item that does not have `tax_rates` set. + """ + description: NotRequired["Literal['']|str"] + """ + A description that will be displayed on the quote PDF. + """ + discounts: NotRequired[ + "Literal['']|List[QuoteService.UpdateParamsDiscount]" + ] + """ + The discounts applied to the quote. You can only set up to one discount. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + expires_at: NotRequired["int"] + """ + A future timestamp on which the quote will be canceled if in `open` or `draft` status. Measured in seconds since the Unix epoch. + """ + footer: NotRequired["Literal['']|str"] + """ + A footer that will be displayed on the quote PDF. + """ + header: NotRequired["Literal['']|str"] + """ + A header that will be displayed on the quote PDF. + """ + invoice_settings: NotRequired[ + "QuoteService.UpdateParamsInvoiceSettings" + ] + """ + All invoices will be billed using the specified settings. + """ + line_items: NotRequired["List[QuoteService.UpdateParamsLineItem]"] + """ + A list of line items the customer is being quoted for. Each line item includes information about the product, the quantity, and the resulting cost. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + on_behalf_of: NotRequired["Literal['']|str"] + """ + The account on behalf of which to charge. + """ + subscription_data: NotRequired[ + "QuoteService.UpdateParamsSubscriptionData" + ] + """ + When creating a subscription or subscription schedule, the specified configuration data will be used. There must be at least one line item with a recurring price for a subscription or subscription schedule to be created. A subscription schedule is created if `subscription_data[effective_date]` is present and in the future, otherwise a subscription is created. + """ + transfer_data: NotRequired[ + "Literal['']|QuoteService.UpdateParamsTransferData" + ] + """ + The data with which to automatically create a Transfer for each of the invoices. + """ + + class UpdateParamsAutomaticTax(TypedDict): + enabled: bool + """ + Controls whether Stripe will automatically compute tax on the resulting invoices or subscriptions as well as the quote itself. + """ + liability: NotRequired[ + "QuoteService.UpdateParamsAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class UpdateParamsAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpdateParamsDiscount(TypedDict): + coupon: NotRequired["str"] + """ + ID of the coupon to create a new discount for. + """ + discount: NotRequired["str"] + """ + ID of an existing discount on the object (or one of its ancestors) to reuse. + """ + + class UpdateParamsInvoiceSettings(TypedDict): + days_until_due: NotRequired["int"] + """ + Number of days within which a customer must pay the invoice generated by this quote. This value will be `null` for quotes where `collection_method=charge_automatically`. + """ + issuer: NotRequired["QuoteService.UpdateParamsInvoiceSettingsIssuer"] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + + class UpdateParamsInvoiceSettingsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpdateParamsLineItem(TypedDict): + id: NotRequired["str"] + """ + The ID of an existing line item on the quote. + """ + price: NotRequired["str"] + """ + The ID of the price object. One of `price` or `price_data` is required. + """ + price_data: NotRequired["QuoteService.UpdateParamsLineItemPriceData"] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + """ + quantity: NotRequired["int"] + """ + The quantity of the line item. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates which apply to the line item. When set, the `default_tax_rates` on the quote do not apply to this line item. + """ + + class UpdateParamsLineItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + recurring: NotRequired[ + "QuoteService.UpdateParamsLineItemPriceDataRecurring" + ] + """ + The recurring components of a price such as `interval` and `interval_count`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class UpdateParamsLineItemPriceDataRecurring(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + + class UpdateParamsSubscriptionData(TypedDict): + description: NotRequired["Literal['']|str"] + """ + The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + """ + effective_date: NotRequired[ + "Literal['']|Literal['current_period_end']|int" + ] + """ + When creating a new subscription, the date of which the subscription schedule will start after the quote is accepted. When updating a subscription, the date of which the subscription will be updated using a subscription schedule. The special value `current_period_end` can be provided to update a subscription at the end of its current period. The `effective_date` is ignored if it is in the past when the quote is accepted. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that will set metadata on the subscription or subscription schedule when the quote is accepted. If a recurring price is included in `line_items`, this field will be passed to the resulting subscription's `metadata` field. If `subscription_data.effective_date` is used, this field will be passed to the resulting subscription schedule's `phases.metadata` field. Unlike object-level metadata, this field is declarative. Updates will clear prior values. + """ + trial_period_days: NotRequired["Literal['']|int"] + """ + Integer representing the number of trial period days before the customer is charged for the first time. + """ + + class UpdateParamsTransferData(TypedDict): + amount: NotRequired["int"] + """ + The amount that will be transferred automatically when the invoice is paid. If no amount is set, the full amount is transferred. There cannot be any line items with recurring prices when using this field. + """ + amount_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. There must be at least 1 line item with a recurring price to use this field. + """ + destination: str + """ + ID of an existing, connected Stripe account. + """ + + def list( + self, + params: "QuoteService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Quote]: + """ + Returns a list of your quotes. + """ + return cast( + ListObject[Quote], + self._requestor.request( + "get", + "/v1/quotes", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "QuoteService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Quote: + """ + A quote models prices and services for a customer. Default options for header, description, footer, and expires_at can be set in the dashboard via the [quote template](https://dashboard.stripe.com/settings/billing/quote). + """ + return cast( + Quote, + self._requestor.request( + "post", + "/v1/quotes", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + quote: str, + params: "QuoteService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Quote: + """ + Retrieves the quote with the given ID. + """ + return cast( + Quote, + self._requestor.request( + "get", + "/v1/quotes/{quote}".format(quote=_util.sanitize_id(quote)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + quote: str, + params: "QuoteService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Quote: + """ + A quote models prices and services for a customer. + """ + return cast( + Quote, + self._requestor.request( + "post", + "/v1/quotes/{quote}".format(quote=_util.sanitize_id(quote)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def accept( + self, + quote: str, + params: "QuoteService.AcceptParams" = {}, + options: RequestOptions = {}, + ) -> Quote: + """ + Accepts the specified quote. + """ + return cast( + Quote, + self._requestor.request( + "post", + "/v1/quotes/{quote}/accept".format( + quote=_util.sanitize_id(quote), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def cancel( + self, + quote: str, + params: "QuoteService.CancelParams" = {}, + options: RequestOptions = {}, + ) -> Quote: + """ + Cancels the quote. + """ + return cast( + Quote, + self._requestor.request( + "post", + "/v1/quotes/{quote}/cancel".format( + quote=_util.sanitize_id(quote), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def finalize_quote( + self, + quote: str, + params: "QuoteService.FinalizeQuoteParams" = {}, + options: RequestOptions = {}, + ) -> Quote: + """ + Finalizes the quote. + """ + return cast( + Quote, + self._requestor.request( + "post", + "/v1/quotes/{quote}/finalize".format( + quote=_util.sanitize_id(quote), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def pdf( + self, + quote: str, + params: "QuoteService.PdfParams" = {}, + options: RequestOptions = {}, + ) -> Any: + """ + Download the PDF for a finalized quote + """ + return cast( + Any, + self._requestor.request_stream( + "get", + "/v1/quotes/{quote}/pdf".format( + quote=_util.sanitize_id(quote) + ), + api_mode="V1", + base_address="files", + params=params, + options=options, + ), + ) diff --git a/stripe/_radar_service.py b/stripe/_radar_service.py new file mode 100644 index 000000000..599d7521e --- /dev/null +++ b/stripe/_radar_service.py @@ -0,0 +1,14 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.radar._early_fraud_warning_service import EarlyFraudWarningService +from stripe.radar._value_list_item_service import ValueListItemService +from stripe.radar._value_list_service import ValueListService + + +class RadarService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.early_fraud_warnings = EarlyFraudWarningService(self._requestor) + self.value_lists = ValueListService(self._requestor) + self.value_list_items = ValueListItemService(self._requestor) diff --git a/stripe/_refund.py b/stripe/_refund.py index f96b26f4b..df4aa7510 100644 --- a/stripe/_refund.py +++ b/stripe/_refund.py @@ -469,14 +469,7 @@ class RetrieveParams(RequestOptions): @classmethod def _cls_cancel( - cls, - refund: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Refund.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, refund: str, **params: Unpack["Refund.CancelParams"] ) -> "Refund": """ Cancels a refund with a status of requires_action. @@ -490,9 +483,6 @@ def _cls_cancel( "/v1/refunds/{refund}/cancel".format( refund=_util.sanitize_id(refund) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -500,13 +490,7 @@ def _cls_cancel( @overload @staticmethod def cancel( - refund: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Refund.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + refund: str, **params: Unpack["Refund.CancelParams"] ) -> "Refund": """ Cancels a refund with a status of requires_action. @@ -516,13 +500,7 @@ def cancel( ... @overload - def cancel( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Refund.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Refund": + def cancel(self, **params: Unpack["Refund.CancelParams"]) -> "Refund": """ Cancels a refund with a status of requires_action. @@ -532,11 +510,7 @@ def cancel( @class_method_variant("_cls_cancel") def cancel( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Refund.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Refund.CancelParams"] ) -> "Refund": """ Cancels a refund with a status of requires_action. @@ -550,22 +524,12 @@ def cancel( # pyright: ignore[reportGeneralTypeIssues] "/v1/refunds/{refund}/cancel".format( refund=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Refund.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Refund": + def create(cls, **params: Unpack["Refund.CreateParams"]) -> "Refund": """ When you create a new refund, you must specify a Charge or a PaymentIntent object on which to create it. @@ -584,23 +548,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Refund.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Refund.ListParams"] ) -> ListObject["Refund"]: """ You can see a list of the refunds belonging to a specific charge. Note that the 10 most recent refunds are always available by default on the charge object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page through additional refunds. @@ -608,9 +562,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -653,14 +604,7 @@ class TestHelpers(APIResourceTestHelpers["Refund"]): @classmethod def _cls_expire( - cls, - refund: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Refund.ExpireParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, refund: str, **params: Unpack["Refund.ExpireParams"] ) -> "Refund": """ Expire a refund with a status of requires_action. @@ -672,9 +616,6 @@ def _cls_expire( "/v1/test_helpers/refunds/{refund}/expire".format( refund=_util.sanitize_id(refund) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -682,13 +623,7 @@ def _cls_expire( @overload @staticmethod def expire( - refund: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Refund.ExpireParams" - ] # pyright: ignore[reportGeneralTypeIssues] + refund: str, **params: Unpack["Refund.ExpireParams"] ) -> "Refund": """ Expire a refund with a status of requires_action. @@ -696,13 +631,7 @@ def expire( ... @overload - def expire( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Refund.ExpireParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Refund": + def expire(self, **params: Unpack["Refund.ExpireParams"]) -> "Refund": """ Expire a refund with a status of requires_action. """ @@ -710,11 +639,7 @@ def expire( @class_method_variant("_cls_expire") def expire( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Refund.ExpireParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Refund.ExpireParams"] ) -> "Refund": """ Expire a refund with a status of requires_action. @@ -726,7 +651,6 @@ def expire( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/refunds/{refund}/expire".format( refund=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/_refund_service.py b/stripe/_refund_service.py new file mode 100644 index 000000000..9f74d74e1 --- /dev/null +++ b/stripe/_refund_service.py @@ -0,0 +1,252 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._refund import Refund +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class RefundService(StripeService): + class CancelParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CreateParams(TypedDict): + amount: NotRequired["int"] + charge: NotRequired["str"] + """ + The identifier of the charge to refund. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + customer: NotRequired["str"] + """ + Customer whose customer balance to refund from. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + instructions_email: NotRequired["str"] + """ + For payment methods without native refund support (e.g., Konbini, PromptPay), use this email from the customer to receive refund instructions. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + origin: NotRequired["Literal['customer_balance']"] + """ + Origin of the refund + """ + payment_intent: NotRequired["str"] + """ + The identifier of the PaymentIntent to refund. + """ + reason: NotRequired[ + "Literal['duplicate', 'fraudulent', 'requested_by_customer']" + ] + """ + String indicating the reason for the refund. If set, possible values are `duplicate`, `fraudulent`, and `requested_by_customer`. If you believe the charge to be fraudulent, specifying `fraudulent` as the reason will add the associated card and email to your [block lists](https://stripe.com/docs/radar/lists), and will also help us improve our fraud detection algorithms. + """ + refund_application_fee: NotRequired["bool"] + """ + Boolean indicating whether the application fee should be refunded when refunding this charge. If a full charge refund is given, the full application fee will be refunded. Otherwise, the application fee will be refunded in an amount proportional to the amount of the charge refunded. An application fee can be refunded only by the application that created the charge. + """ + reverse_transfer: NotRequired["bool"] + """ + Boolean indicating whether the transfer should be reversed when refunding this charge. The transfer will be reversed proportionally to the amount being refunded (either the entire or partial amount). + + A transfer can be reversed only by the application that created the charge. + """ + + class ListParams(TypedDict): + charge: NotRequired["str"] + """ + Only return refunds for the charge specified by this charge ID. + """ + created: NotRequired["RefundService.ListParamsCreated|int"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + payment_intent: NotRequired["str"] + """ + Only return refunds for the PaymentIntent specified by this ID. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + def list( + self, + params: "RefundService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Refund]: + """ + Returns a list of all refunds you created. We return the refunds in sorted order, with the most recent refunds appearing first The 10 most recent refunds are always available by default on the Charge object. + """ + return cast( + ListObject[Refund], + self._requestor.request( + "get", + "/v1/refunds", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "RefundService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Refund: + """ + When you create a new refund, you must specify a Charge or a PaymentIntent object on which to create it. + + Creating a new refund will refund a charge that has previously been created but not yet refunded. + Funds will be refunded to the credit or debit card that was originally charged. + + You can optionally refund only part of a charge. + You can do so multiple times, until the entire charge has been refunded. + + Once entirely refunded, a charge can't be refunded again. + This method will raise an error when called on an already-refunded charge, + or when trying to refund more money than is left on a charge. + """ + return cast( + Refund, + self._requestor.request( + "post", + "/v1/refunds", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + refund: str, + params: "RefundService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Refund: + """ + Retrieves the details of an existing refund. + """ + return cast( + Refund, + self._requestor.request( + "get", + "/v1/refunds/{refund}".format( + refund=_util.sanitize_id(refund) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + refund: str, + params: "RefundService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Refund: + """ + Updates the refund that you specify by setting the values of the passed parameters. Any parameters that you don't provide remain unchanged. + + This request only accepts metadata as an argument. + """ + return cast( + Refund, + self._requestor.request( + "post", + "/v1/refunds/{refund}".format( + refund=_util.sanitize_id(refund) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def cancel( + self, + refund: str, + params: "RefundService.CancelParams" = {}, + options: RequestOptions = {}, + ) -> Refund: + """ + Cancels a refund with a status of requires_action. + + You can't cancel refunds in other states. Only refunds for payment methods that require customer action can enter the requires_action state. + """ + return cast( + Refund, + self._requestor.request( + "post", + "/v1/refunds/{refund}/cancel".format( + refund=_util.sanitize_id(refund), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_reporting_service.py b/stripe/_reporting_service.py new file mode 100644 index 000000000..69057c15e --- /dev/null +++ b/stripe/_reporting_service.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.reporting._report_run_service import ReportRunService +from stripe.reporting._report_type_service import ReportTypeService + + +class ReportingService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.report_runs = ReportRunService(self._requestor) + self.report_types = ReportTypeService(self._requestor) diff --git a/stripe/_request_options.py b/stripe/_request_options.py index 715eef768..0d39e885a 100644 --- a/stripe/_request_options.py +++ b/stripe/_request_options.py @@ -1,10 +1,69 @@ -from typing import Optional, Dict +from stripe._requestor_options import RequestorOptions +from typing import Mapping, Optional, Dict, Tuple, Any from typing_extensions import NotRequired, TypedDict class RequestOptions(TypedDict): - api_key: NotRequired[Optional[str]] - stripe_version: NotRequired[Optional[str]] - stripe_account: NotRequired[Optional[str]] - idempotency_key: NotRequired[Optional[str]] - headers: NotRequired[Optional[Dict[str, str]]] + api_key: NotRequired["str|None"] + stripe_version: NotRequired["str|None"] + stripe_account: NotRequired["str|None"] + max_network_retries: NotRequired["int|None"] + idempotency_key: NotRequired["str|None"] + headers: NotRequired["Mapping[str, str]|None"] + + +def merge_options( + requestor: RequestorOptions, + request: Optional[RequestOptions], +) -> RequestOptions: + """ + Merge a client and request object, giving precedence to the values from + the request object. + """ + if request is None: + return { + "api_key": requestor.api_key, + "stripe_account": requestor.stripe_account, + "stripe_version": requestor.stripe_version, + "max_network_retries": requestor.max_network_retries, + "idempotency_key": None, + "headers": None, + } + + return { + "api_key": request.get("api_key") or requestor.api_key, + "stripe_account": request.get("stripe_account") + or requestor.stripe_account, + "stripe_version": request.get("stripe_version") + or requestor.stripe_version, + "max_network_retries": request.get("max_network_retries") + if request.get("max_network_retries") is not None + else requestor.max_network_retries, + "idempotency_key": request.get("idempotency_key"), + "headers": request.get("headers"), + } + + +def extract_options_from_dict( + d: Optional[Mapping[str, Any]] +) -> Tuple[RequestOptions, Dict[str, Any]]: + """ + Extracts a RequestOptions object from a dict, and returns a tuple of + the RequestOptions object and the remaining dict. + """ + if not d: + return {}, {} + options: RequestOptions = {} + d_copy = dict(d) + for key in [ + "api_key", + "stripe_version", + "stripe_account", + "max_network_retries", + "idempotency_key", + "headers", + ]: + if key in d_copy: + options[key] = d_copy.pop(key) + + return options, d_copy diff --git a/stripe/_requestor_options.py b/stripe/_requestor_options.py new file mode 100644 index 000000000..1314a8a71 --- /dev/null +++ b/stripe/_requestor_options.py @@ -0,0 +1,78 @@ +# using global variables +import stripe # noqa: IMP101 +from stripe._base_address import BaseAddresses + +from typing import Optional + + +class RequestorOptions(object): + api_key: Optional[str] + stripe_account: Optional[str] + stripe_version: Optional[str] + base_addresses: BaseAddresses + max_network_retries: Optional[int] + + def __init__( + self, + api_key: Optional[str] = None, + stripe_account: Optional[str] = None, + stripe_version: Optional[str] = None, + base_addresses: BaseAddresses = {}, + max_network_retries: Optional[int] = None, + ): + self.api_key = api_key + self.stripe_account = stripe_account + self.stripe_version = stripe_version + self.base_addresses = {} + + # Base addresses can be unset (for correct merging). + # If they are not set, then we will use default API bases defined on stripe. + if base_addresses.get("api"): + self.base_addresses["api"] = base_addresses.get("api") + if base_addresses.get("connect") is not None: + self.base_addresses["connect"] = base_addresses.get("connect") + if base_addresses.get("files") is not None: + self.base_addresses["files"] = base_addresses.get("files") + + self.max_network_retries = max_network_retries + + def to_dict(self): + """ + Returns a dict representation of the object. + """ + return { + "api_key": self.api_key, + "stripe_account": self.stripe_account, + "stripe_version": self.stripe_version, + "base_addresses": self.base_addresses, + "max_network_retries": self.max_network_retries, + } + + +class _GlobalRequestorOptions(RequestorOptions): + def __init__(self): + pass + + @property + def base_addresses(self): + return { + "api": stripe.api_base, + "connect": stripe.connect_api_base, + "files": stripe.upload_api_base, + } + + @property + def api_key(self): + return stripe.api_key + + @property + def stripe_version(self): + return stripe.api_version + + @property + def stripe_account(self): + return None + + @property + def max_network_retries(self): + return stripe.max_network_retries diff --git a/stripe/_reversal.py b/stripe/_reversal.py index 329d8b09b..5193235e4 100644 --- a/stripe/_reversal.py +++ b/stripe/_reversal.py @@ -90,7 +90,7 @@ def modify(cls, sid, **params): ) @classmethod - def retrieve(cls, id, api_key=None, **params): + def retrieve(cls, id, **params): raise NotImplementedError( "Can't retrieve a reversal without a transfer ID. " "Use stripe.Transfer.retrieve_reversal('transfer_id', 'reversal_id') " diff --git a/stripe/_review.py b/stripe/_review.py index aff1cfad1..e7983b2fa 100644 --- a/stripe/_review.py +++ b/stripe/_review.py @@ -183,14 +183,7 @@ class RetrieveParams(RequestOptions): @classmethod def _cls_approve( - cls, - review: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Review.ApproveParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, review: str, **params: Unpack["Review.ApproveParams"] ) -> "Review": """ Approves a Review object, closing it and removing it from the list of reviews. @@ -202,9 +195,6 @@ def _cls_approve( "/v1/reviews/{review}/approve".format( review=_util.sanitize_id(review) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -212,13 +202,7 @@ def _cls_approve( @overload @staticmethod def approve( - review: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Review.ApproveParams" - ] # pyright: ignore[reportGeneralTypeIssues] + review: str, **params: Unpack["Review.ApproveParams"] ) -> "Review": """ Approves a Review object, closing it and removing it from the list of reviews. @@ -226,13 +210,7 @@ def approve( ... @overload - def approve( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Review.ApproveParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Review": + def approve(self, **params: Unpack["Review.ApproveParams"]) -> "Review": """ Approves a Review object, closing it and removing it from the list of reviews. """ @@ -240,11 +218,7 @@ def approve( @class_method_variant("_cls_approve") def approve( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Review.ApproveParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Review.ApproveParams"] ) -> "Review": """ Approves a Review object, closing it and removing it from the list of reviews. @@ -256,20 +230,13 @@ def approve( # pyright: ignore[reportGeneralTypeIssues] "/v1/reviews/{review}/approve".format( review=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Review.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Review.ListParams"] ) -> ListObject["Review"]: """ Returns a list of Review objects that have open set to true. The objects are sorted in descending order by creation date, with the most recently created object appearing first. @@ -277,9 +244,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_review_service.py b/stripe/_review_service.py new file mode 100644 index 000000000..532e2c531 --- /dev/null +++ b/stripe/_review_service.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._review import Review +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class ReviewService(StripeService): + class ApproveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ListParams(TypedDict): + created: NotRequired["ReviewService.ListParamsCreated|int"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "ReviewService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Review]: + """ + Returns a list of Review objects that have open set to true. The objects are sorted in descending order by creation date, with the most recently created object appearing first. + """ + return cast( + ListObject[Review], + self._requestor.request( + "get", + "/v1/reviews", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + review: str, + params: "ReviewService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Review: + """ + Retrieves a Review object. + """ + return cast( + Review, + self._requestor.request( + "get", + "/v1/reviews/{review}".format( + review=_util.sanitize_id(review) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def approve( + self, + review: str, + params: "ReviewService.ApproveParams" = {}, + options: RequestOptions = {}, + ) -> Review: + """ + Approves a Review object, closing it and removing it from the list of reviews. + """ + return cast( + Review, + self._requestor.request( + "post", + "/v1/reviews/{review}/approve".format( + review=_util.sanitize_id(review), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_search_result_object.py b/stripe/_search_result_object.py index 43e0a8e7c..dbef55f4a 100644 --- a/stripe/_search_result_object.py +++ b/stripe/_search_result_object.py @@ -1,19 +1,22 @@ # pyright: strict -from typing_extensions import Self +from typing_extensions import Self, Unpack from typing import ( Generic, List, TypeVar, cast, - Optional, Any, Mapping, Iterator, ) +from stripe._api_requestor import ( + _APIRequestor, # pyright: ignore[reportPrivateUsage] +) from stripe._stripe_object import StripeObject from stripe import _util import warnings +from stripe._request_options import RequestOptions, extract_options_from_dict T = TypeVar("T", bound=StripeObject) @@ -24,32 +27,17 @@ class SearchResultObject(StripeObject, Generic[T]): has_more: bool next_page: str - def _search( - self, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Mapping[str, Any] - ) -> Self: + def _search(self, **params: Mapping[str, Any]) -> Self: with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) return self.search( # pyright: ignore[reportDeprecated] - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, **params, ) @_util.deprecated( "This will be removed in a future version of stripe-python. Please call the `search` method on the corresponding resource directly, instead of the generic search on SearchResultObject." ) - def search( - self, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Mapping[str, Any] - ) -> Self: + def search(self, **params: Mapping[str, Any]) -> Self: url = self.get("url") if not isinstance(url, str): raise ValueError( @@ -60,10 +48,9 @@ def search( self._request( "get", url, - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, + base_address="api", + api_mode="V1", ), ) @@ -101,32 +88,15 @@ def auto_paging_iter(self) -> Iterator[T]: @classmethod def _empty_search_result( cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, + **params: Unpack[RequestOptions], ) -> Self: - return cls.construct_from( - {"data": [], "has_more": False, "next_page": None}, - key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, + return cls._construct_from( + values={"data": [], "has_more": False, "next_page": None}, last_response=None, - ) - - @classmethod - @_util.deprecated( - "For internal stripe-python use only. This will be removed in a future version." - ) - def empty_search_result( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - ) -> Self: - return cls._empty_search_result( - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, + requestor=_APIRequestor._global_with_options( # pyright: ignore[reportPrivateUsage] + **params, + ), + api_mode="V1", ) @property @@ -134,26 +104,20 @@ def is_empty(self) -> bool: return not self.data def next_search_result_page( - self, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Mapping[str, Any] + self, **params: Unpack[RequestOptions] ) -> Self: if not self.has_more: + options, _ = extract_options_from_dict(params) return self._empty_search_result( - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, + api_key=options.get("api_key"), + stripe_version=options.get("stripe_version"), + stripe_account=options.get("stripe_account"), ) - params_with_filters = self._retrieve_params.copy() + params_with_filters = dict(self._retrieve_params) params_with_filters.update({"page": self.next_page}) params_with_filters.update(params) return self._search( - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, **params_with_filters, ) diff --git a/stripe/_searchable_api_resource.py b/stripe/_searchable_api_resource.py index b39501806..8aab0bdb9 100644 --- a/stripe/_searchable_api_resource.py +++ b/stripe/_searchable_api_resource.py @@ -11,20 +11,10 @@ class SearchableAPIResource(APIResource[T]): @classmethod - def _search( - cls, - search_url, - api_key=None, - stripe_version=None, - stripe_account=None, - **params - ): + def _search(cls, search_url, **params): ret = cls._static_request( "get", search_url, - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(ret, SearchResultObject): diff --git a/stripe/_setup_attempt.py b/stripe/_setup_attempt.py index a6e97383b..573d9267e 100644 --- a/stripe/_setup_attempt.py +++ b/stripe/_setup_attempt.py @@ -768,13 +768,7 @@ class ListParamsCreated(TypedDict): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SetupAttempt.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["SetupAttempt.ListParams"] ) -> ListObject["SetupAttempt"]: """ Returns a list of SetupAttempts that associate with a provided SetupIntent. @@ -782,9 +776,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_setup_attempt_service.py b/stripe/_setup_attempt_service.py new file mode 100644 index 000000000..38f34cbde --- /dev/null +++ b/stripe/_setup_attempt_service.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._setup_attempt import SetupAttempt +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class SetupAttemptService(StripeService): + class ListParams(TypedDict): + created: NotRequired["SetupAttemptService.ListParamsCreated|int"] + """ + A filter on the list, based on the object `created` field. The value + can be a string with an integer Unix timestamp or a + dictionary with a number of different query options. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + setup_intent: str + """ + Only return SetupAttempts created by the SetupIntent specified by + this ID. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + def list( + self, + params: "SetupAttemptService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[SetupAttempt]: + """ + Returns a list of SetupAttempts that associate with a provided SetupIntent. + """ + return cast( + ListObject[SetupAttempt], + self._requestor.request( + "get", + "/v1/setup_attempts", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_setup_intent.py b/stripe/_setup_intent.py index 24a86940a..c1c4b3e6b 100644 --- a/stripe/_setup_intent.py +++ b/stripe/_setup_intent.py @@ -3469,14 +3469,7 @@ class VerifyMicrodepositsParams(RequestOptions): @classmethod def _cls_cancel( - cls, - intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SetupIntent.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, intent: str, **params: Unpack["SetupIntent.CancelParams"] ) -> "SetupIntent": """ You can cancel a SetupIntent object when it's in one of these statuses: requires_payment_method, requires_confirmation, or requires_action. @@ -3490,9 +3483,6 @@ def _cls_cancel( "/v1/setup_intents/{intent}/cancel".format( intent=_util.sanitize_id(intent) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -3500,13 +3490,7 @@ def _cls_cancel( @overload @staticmethod def cancel( - intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SetupIntent.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + intent: str, **params: Unpack["SetupIntent.CancelParams"] ) -> "SetupIntent": """ You can cancel a SetupIntent object when it's in one of these statuses: requires_payment_method, requires_confirmation, or requires_action. @@ -3517,11 +3501,7 @@ def cancel( @overload def cancel( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "SetupIntent.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["SetupIntent.CancelParams"] ) -> "SetupIntent": """ You can cancel a SetupIntent object when it's in one of these statuses: requires_payment_method, requires_confirmation, or requires_action. @@ -3532,11 +3512,7 @@ def cancel( @class_method_variant("_cls_cancel") def cancel( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "SetupIntent.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["SetupIntent.CancelParams"] ) -> "SetupIntent": """ You can cancel a SetupIntent object when it's in one of these statuses: requires_payment_method, requires_confirmation, or requires_action. @@ -3550,21 +3526,13 @@ def cancel( # pyright: ignore[reportGeneralTypeIssues] "/v1/setup_intents/{intent}/cancel".format( intent=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_confirm( - cls, - intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SetupIntent.ConfirmParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, intent: str, **params: Unpack["SetupIntent.ConfirmParams"] ) -> "SetupIntent": """ Confirm that your customer intends to set up the current or @@ -3589,9 +3557,6 @@ def _cls_confirm( "/v1/setup_intents/{intent}/confirm".format( intent=_util.sanitize_id(intent) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -3599,13 +3564,7 @@ def _cls_confirm( @overload @staticmethod def confirm( - intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SetupIntent.ConfirmParams" - ] # pyright: ignore[reportGeneralTypeIssues] + intent: str, **params: Unpack["SetupIntent.ConfirmParams"] ) -> "SetupIntent": """ Confirm that your customer intends to set up the current or @@ -3627,11 +3586,7 @@ def confirm( @overload def confirm( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "SetupIntent.ConfirmParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["SetupIntent.ConfirmParams"] ) -> "SetupIntent": """ Confirm that your customer intends to set up the current or @@ -3653,11 +3608,7 @@ def confirm( @class_method_variant("_cls_confirm") def confirm( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "SetupIntent.ConfirmParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["SetupIntent.ConfirmParams"] ) -> "SetupIntent": """ Confirm that your customer intends to set up the current or @@ -3682,21 +3633,13 @@ def confirm( # pyright: ignore[reportGeneralTypeIssues] "/v1/setup_intents/{intent}/confirm".format( intent=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SetupIntent.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["SetupIntent.CreateParams"] ) -> "SetupIntent": """ Creates a SetupIntent object. @@ -3709,23 +3652,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SetupIntent.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["SetupIntent.ListParams"] ) -> ListObject["SetupIntent"]: """ Returns a list of SetupIntents. @@ -3733,9 +3666,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -3779,12 +3709,7 @@ def retrieve( def _cls_verify_microdeposits( cls, intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SetupIntent.VerifyMicrodepositsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["SetupIntent.VerifyMicrodepositsParams"] ) -> "SetupIntent": """ Verifies microdeposits on a SetupIntent object. @@ -3796,9 +3721,6 @@ def _cls_verify_microdeposits( "/v1/setup_intents/{intent}/verify_microdeposits".format( intent=_util.sanitize_id(intent) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -3806,13 +3728,7 @@ def _cls_verify_microdeposits( @overload @staticmethod def verify_microdeposits( - intent: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SetupIntent.VerifyMicrodepositsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + intent: str, **params: Unpack["SetupIntent.VerifyMicrodepositsParams"] ) -> "SetupIntent": """ Verifies microdeposits on a SetupIntent object. @@ -3821,11 +3737,7 @@ def verify_microdeposits( @overload def verify_microdeposits( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "SetupIntent.VerifyMicrodepositsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["SetupIntent.VerifyMicrodepositsParams"] ) -> "SetupIntent": """ Verifies microdeposits on a SetupIntent object. @@ -3834,11 +3746,7 @@ def verify_microdeposits( @class_method_variant("_cls_verify_microdeposits") def verify_microdeposits( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "SetupIntent.VerifyMicrodepositsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["SetupIntent.VerifyMicrodepositsParams"] ) -> "SetupIntent": """ Verifies microdeposits on a SetupIntent object. @@ -3850,7 +3758,6 @@ def verify_microdeposits( # pyright: ignore[reportGeneralTypeIssues] "/v1/setup_intents/{intent}/verify_microdeposits".format( intent=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/_setup_intent_service.py b/stripe/_setup_intent_service.py new file mode 100644 index 000000000..ff5762aec --- /dev/null +++ b/stripe/_setup_intent_service.py @@ -0,0 +1,3025 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._setup_intent import SetupIntent +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class SetupIntentService(StripeService): + class CancelParams(TypedDict): + cancellation_reason: NotRequired[ + "Literal['abandoned', 'duplicate', 'requested_by_customer']" + ] + """ + Reason for canceling this SetupIntent. Possible values are: `abandoned`, `requested_by_customer`, or `duplicate` + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ConfirmParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + mandate_data: NotRequired[ + "Literal['']|SetupIntentService.ConfirmParamsMandateData" + ] + payment_method: NotRequired["str"] + """ + ID of the payment method (a PaymentMethod, Card, or saved Source object) to attach to this SetupIntent. + """ + payment_method_data: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodData" + ] + """ + When included, this hash creates a PaymentMethod that is set as the [`payment_method`](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-payment_method) + value in the SetupIntent. + """ + payment_method_options: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptions" + ] + """ + Payment method-specific configuration for this SetupIntent. + """ + return_url: NotRequired["str"] + """ + The URL to redirect your customer back to after they authenticate on the payment method's app or site. + If you'd prefer to redirect to a mobile application, you can alternatively supply an application URI scheme. + This parameter is only used for cards and other redirect-based payment methods. + """ + use_stripe_sdk: NotRequired["bool"] + """ + Set to `true` when confirming server-side and using Stripe.js, iOS, or Android client-side SDKs to handle the next actions. + """ + + class ConfirmParamsMandateData(TypedDict): + customer_acceptance: NotRequired[ + "SetupIntentService.ConfirmParamsMandateDataCustomerAcceptance" + ] + """ + This hash contains details about the customer acceptance of the Mandate. + """ + + class ConfirmParamsMandateDataCustomerAcceptance(TypedDict): + accepted_at: NotRequired["int"] + """ + The time at which the customer accepted the Mandate. + """ + offline: NotRequired[ + "SetupIntentService.ConfirmParamsMandateDataCustomerAcceptanceOffline" + ] + """ + If this is a Mandate accepted offline, this hash contains details about the offline acceptance. + """ + online: NotRequired[ + "SetupIntentService.ConfirmParamsMandateDataCustomerAcceptanceOnline" + ] + """ + If this is a Mandate accepted online, this hash contains details about the online acceptance. + """ + type: Literal["offline", "online"] + """ + The type of customer acceptance information included with the Mandate. One of `online` or `offline`. + """ + + class ConfirmParamsMandateDataCustomerAcceptanceOffline(TypedDict): + pass + + class ConfirmParamsMandateDataCustomerAcceptanceOnline(TypedDict): + ip_address: NotRequired["str"] + """ + The IP address from which the Mandate was accepted by the customer. + """ + user_agent: NotRequired["str"] + """ + The user agent of the browser from which the Mandate was accepted by the customer. + """ + + class ConfirmParamsPaymentMethodData(TypedDict): + acss_debit: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataAcssDebit" + ] + """ + If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + """ + affirm: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataAffirm" + ] + """ + If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + """ + afterpay_clearpay: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataAfterpayClearpay" + ] + """ + If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + """ + alipay: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataAlipay" + ] + """ + If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + """ + au_becs_debit: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataAuBecsDebit" + ] + """ + If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + """ + bacs_debit: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataBacsDebit" + ] + """ + If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + """ + bancontact: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataBancontact" + ] + """ + If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + """ + billing_details: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataBillingDetails" + ] + """ + Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + """ + blik: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataBlik" + ] + """ + If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + """ + boleto: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataBoleto" + ] + """ + If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + """ + cashapp: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataCashapp" + ] + """ + If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + """ + customer_balance: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataCustomerBalance" + ] + """ + If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + """ + eps: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataEps" + ] + """ + If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + """ + fpx: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataFpx" + ] + """ + If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + """ + giropay: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataGiropay" + ] + """ + If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + """ + grabpay: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataGrabpay" + ] + """ + If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + """ + ideal: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataIdeal" + ] + """ + If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + """ + interac_present: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataInteracPresent" + ] + """ + If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + """ + klarna: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataKlarna" + ] + """ + If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + """ + konbini: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataKonbini" + ] + """ + If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + """ + link: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataLink" + ] + """ + If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + oxxo: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataOxxo" + ] + """ + If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + """ + p24: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataP24" + ] + """ + If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + """ + paynow: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataPaynow" + ] + """ + If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + """ + paypal: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataPaypal" + ] + """ + If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + """ + pix: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataPix" + ] + """ + If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + """ + promptpay: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataPromptpay" + ] + """ + If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + """ + radar_options: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataRadarOptions" + ] + """ + Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + """ + revolut_pay: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataRevolutPay" + ] + """ + If this is a `Revolut Pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + """ + sepa_debit: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataSepaDebit" + ] + """ + If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + """ + sofort: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataSofort" + ] + """ + If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + """ + type: Literal[ + "acss_debit", + "affirm", + "afterpay_clearpay", + "alipay", + "au_becs_debit", + "bacs_debit", + "bancontact", + "blik", + "boleto", + "cashapp", + "customer_balance", + "eps", + "fpx", + "giropay", + "grabpay", + "ideal", + "klarna", + "konbini", + "link", + "oxxo", + "p24", + "paynow", + "paypal", + "pix", + "promptpay", + "revolut_pay", + "sepa_debit", + "sofort", + "us_bank_account", + "wechat_pay", + "zip", + ] + """ + The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + """ + us_bank_account: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataUsBankAccount" + ] + """ + If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + """ + wechat_pay: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataWechatPay" + ] + """ + If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + """ + zip: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataZip" + ] + """ + If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + """ + + class ConfirmParamsPaymentMethodDataAcssDebit(TypedDict): + account_number: str + """ + Customer's bank account number. + """ + institution_number: str + """ + Institution number of the customer's bank. + """ + transit_number: str + """ + Transit number of the customer's bank. + """ + + class ConfirmParamsPaymentMethodDataAffirm(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataAfterpayClearpay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataAlipay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataAuBecsDebit(TypedDict): + account_number: str + """ + The account number for the bank account. + """ + bsb_number: str + """ + Bank-State-Branch number of the bank account. + """ + + class ConfirmParamsPaymentMethodDataBacsDebit(TypedDict): + account_number: NotRequired["str"] + """ + Account number of the bank account that the funds will be debited from. + """ + sort_code: NotRequired["str"] + """ + Sort code of the bank account. (e.g., `10-20-30`) + """ + + class ConfirmParamsPaymentMethodDataBancontact(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataBillingDetails(TypedDict): + address: NotRequired[ + "Literal['']|SetupIntentService.ConfirmParamsPaymentMethodDataBillingDetailsAddress" + ] + """ + Billing address. + """ + email: NotRequired["Literal['']|str"] + """ + Email address. + """ + name: NotRequired["Literal['']|str"] + """ + Full name. + """ + phone: NotRequired["Literal['']|str"] + """ + Billing phone number (including extension). + """ + + class ConfirmParamsPaymentMethodDataBillingDetailsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class ConfirmParamsPaymentMethodDataBlik(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataBoleto(TypedDict): + tax_id: str + """ + The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + """ + + class ConfirmParamsPaymentMethodDataCashapp(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataCustomerBalance(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataEps(TypedDict): + bank: NotRequired[ + "Literal['arzte_und_apotheker_bank', 'austrian_anadi_bank_ag', 'bank_austria', 'bankhaus_carl_spangler', 'bankhaus_schelhammer_und_schattera_ag', 'bawag_psk_ag', 'bks_bank_ag', 'brull_kallmus_bank_ag', 'btv_vier_lander_bank', 'capital_bank_grawe_gruppe_ag', 'deutsche_bank_ag', 'dolomitenbank', 'easybank_ag', 'erste_bank_und_sparkassen', 'hypo_alpeadriabank_international_ag', 'hypo_bank_burgenland_aktiengesellschaft', 'hypo_noe_lb_fur_niederosterreich_u_wien', 'hypo_oberosterreich_salzburg_steiermark', 'hypo_tirol_bank_ag', 'hypo_vorarlberg_bank_ag', 'marchfelder_bank', 'oberbank_ag', 'raiffeisen_bankengruppe_osterreich', 'schoellerbank_ag', 'sparda_bank_wien', 'volksbank_gruppe', 'volkskreditbank_ag', 'vr_bank_braunau']" + ] + """ + The customer's bank. + """ + + class ConfirmParamsPaymentMethodDataFpx(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type for FPX transaction + """ + bank: Literal[ + "affin_bank", + "agrobank", + "alliance_bank", + "ambank", + "bank_islam", + "bank_muamalat", + "bank_of_china", + "bank_rakyat", + "bsn", + "cimb", + "deutsche_bank", + "hong_leong_bank", + "hsbc", + "kfh", + "maybank2e", + "maybank2u", + "ocbc", + "pb_enterprise", + "public_bank", + "rhb", + "standard_chartered", + "uob", + ] + """ + The customer's bank. + """ + + class ConfirmParamsPaymentMethodDataGiropay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataGrabpay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataIdeal(TypedDict): + bank: NotRequired[ + "Literal['abn_amro', 'asn_bank', 'bunq', 'handelsbanken', 'ing', 'knab', 'moneyou', 'n26', 'nn', 'rabobank', 'regiobank', 'revolut', 'sns_bank', 'triodos_bank', 'van_lanschot', 'yoursafe']" + ] + """ + The customer's bank. + """ + + class ConfirmParamsPaymentMethodDataInteracPresent(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataKlarna(TypedDict): + dob: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodDataKlarnaDob" + ] + """ + Customer's date of birth + """ + + class ConfirmParamsPaymentMethodDataKlarnaDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class ConfirmParamsPaymentMethodDataKonbini(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataLink(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataOxxo(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataP24(TypedDict): + bank: NotRequired[ + "Literal['alior_bank', 'bank_millennium', 'bank_nowy_bfg_sa', 'bank_pekao_sa', 'banki_spbdzielcze', 'blik', 'bnp_paribas', 'boz', 'citi_handlowy', 'credit_agricole', 'envelobank', 'etransfer_pocztowy24', 'getin_bank', 'ideabank', 'ing', 'inteligo', 'mbank_mtransfer', 'nest_przelew', 'noble_pay', 'pbac_z_ipko', 'plus_bank', 'santander_przelew24', 'tmobile_usbugi_bankowe', 'toyota_bank', 'volkswagen_bank']" + ] + """ + The customer's bank. + """ + + class ConfirmParamsPaymentMethodDataPaynow(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataPaypal(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataPix(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataPromptpay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataRadarOptions(TypedDict): + session: NotRequired["str"] + """ + A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + """ + + class ConfirmParamsPaymentMethodDataRevolutPay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataSepaDebit(TypedDict): + iban: str + """ + IBAN of the bank account. + """ + + class ConfirmParamsPaymentMethodDataSofort(TypedDict): + country: Literal["AT", "BE", "DE", "ES", "IT", "NL"] + """ + Two-letter ISO code representing the country the bank account is located in. + """ + + class ConfirmParamsPaymentMethodDataUsBankAccount(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type: individual or company. + """ + account_number: NotRequired["str"] + """ + Account number of the bank account. + """ + account_type: NotRequired["Literal['checking', 'savings']"] + """ + Account type: checkings or savings. Defaults to checking if omitted. + """ + financial_connections_account: NotRequired["str"] + """ + The ID of a Financial Connections Account to use as a payment method. + """ + routing_number: NotRequired["str"] + """ + Routing number of the bank account. + """ + + class ConfirmParamsPaymentMethodDataWechatPay(TypedDict): + pass + + class ConfirmParamsPaymentMethodDataZip(TypedDict): + pass + + class ConfirmParamsPaymentMethodOptions(TypedDict): + acss_debit: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsAcssDebit" + ] + """ + If this is a `acss_debit` SetupIntent, this sub-hash contains details about the ACSS Debit payment method options. + """ + card: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsCard" + ] + """ + Configuration for any card setup attempted on this SetupIntent. + """ + link: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsLink" + ] + """ + If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. + """ + paypal: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsPaypal" + ] + """ + If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. + """ + sepa_debit: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsSepaDebit" + ] + """ + If this is a `sepa_debit` SetupIntent, this sub-hash contains details about the SEPA Debit payment method options. + """ + us_bank_account: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsUsBankAccount" + ] + """ + If this is a `us_bank_account` SetupIntent, this sub-hash contains details about the US bank account payment method options. + """ + + class ConfirmParamsPaymentMethodOptionsAcssDebit(TypedDict): + currency: NotRequired["Literal['cad', 'usd']"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + mandate_options: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsAcssDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Bank account verification method. + """ + + class ConfirmParamsPaymentMethodOptionsAcssDebitMandateOptions(TypedDict): + custom_mandate_url: NotRequired["Literal['']|str"] + """ + A URL for custom mandate text to render during confirmation step. + The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + """ + default_for: NotRequired["List[Literal['invoice', 'subscription']]"] + """ + List of Stripe products where this mandate can be selected automatically. + """ + interval_description: NotRequired["str"] + """ + Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + """ + payment_schedule: NotRequired[ + "Literal['combined', 'interval', 'sporadic']" + ] + """ + Payment schedule for the mandate. + """ + transaction_type: NotRequired["Literal['business', 'personal']"] + """ + Transaction type of the mandate. + """ + + class ConfirmParamsPaymentMethodOptionsCard(TypedDict): + mandate_options: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsCardMandateOptions" + ] + """ + Configuration options for setting up an eMandate for cards issued in India. + """ + moto: NotRequired["bool"] + """ + When specified, this parameter signals that a card has been collected + as MOTO (Mail Order Telephone Order) and thus out of scope for SCA. This + parameter can only be provided during confirmation. + """ + network: NotRequired[ + "Literal['amex', 'cartes_bancaires', 'diners', 'discover', 'eftpos_au', 'interac', 'jcb', 'mastercard', 'unionpay', 'unknown', 'visa']" + ] + """ + Selected network to process this SetupIntent on. Depends on the available networks of the card attached to the SetupIntent. Can be only set confirm-time. + """ + request_three_d_secure: NotRequired[ + "Literal['any', 'automatic', 'challenge']" + ] + """ + We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + """ + three_d_secure: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsCardThreeDSecure" + ] + """ + If 3D Secure authentication was performed with a third-party provider, + the authentication details to use for this setup. + """ + + class ConfirmParamsPaymentMethodOptionsCardMandateOptions(TypedDict): + amount: int + """ + Amount to be charged for future payments. + """ + amount_type: Literal["fixed", "maximum"] + """ + One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + """ + currency: str + """ + Currency in which future payments will be charged. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + description: NotRequired["str"] + """ + A description of the mandate or subscription that is meant to be displayed to the customer. + """ + end_date: NotRequired["int"] + """ + End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + """ + interval: Literal["day", "month", "sporadic", "week", "year"] + """ + Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + """ + reference: str + """ + Unique identifier for the mandate or subscription. + """ + start_date: int + """ + Start date of the mandate or subscription. Start date should not be lesser than yesterday. + """ + supported_types: NotRequired["List[Literal['india']]"] + """ + Specifies the type of mandates supported. Possible values are `india`. + """ + + class ConfirmParamsPaymentMethodOptionsCardThreeDSecure(TypedDict): + ares_trans_status: NotRequired[ + "Literal['A', 'C', 'I', 'N', 'R', 'U', 'Y']" + ] + """ + The `transStatus` returned from the card Issuer's ACS in the ARes. + """ + cryptogram: NotRequired["str"] + """ + The cryptogram, also known as the "authentication value" (AAV, CAVV or + AEVV). This value is 20 bytes, base64-encoded into a 28-character string. + (Most 3D Secure providers will return the base64-encoded version, which + is what you should specify here.) + """ + electronic_commerce_indicator: NotRequired[ + "Literal['01', '02', '05', '06', '07']" + ] + """ + The Electronic Commerce Indicator (ECI) is returned by your 3D Secure + provider and indicates what degree of authentication was performed. + """ + network_options: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsCardThreeDSecureNetworkOptions" + ] + """ + Network specific 3DS fields. Network specific arguments require an + explicit card brand choice. The parameter `payment_method_options.card.network`` + must be populated accordingly + """ + requestor_challenge_indicator: NotRequired["str"] + """ + The challenge indicator (`threeDSRequestorChallengeInd`) which was requested in the + AReq sent to the card Issuer's ACS. A string containing 2 digits from 01-99. + """ + transaction_id: NotRequired["str"] + """ + For 3D Secure 1, the XID. For 3D Secure 2, the Directory Server + Transaction ID (dsTransID). + """ + version: NotRequired["Literal['1.0.2', '2.1.0', '2.2.0']"] + """ + The version of 3D Secure that was performed. + """ + + class ConfirmParamsPaymentMethodOptionsCardThreeDSecureNetworkOptions( + TypedDict, + ): + cartes_bancaires: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancaires" + ] + """ + Cartes Bancaires-specific 3DS fields. + """ + + class ConfirmParamsPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancaires( + TypedDict, + ): + cb_avalgo: Literal["0", "1", "2", "3", "4", "A"] + """ + The cryptogram calculation algorithm used by the card Issuer's ACS + to calculate the Authentication cryptogram. Also known as `cavvAlgorithm`. + messageExtension: CB-AVALGO + """ + cb_exemption: NotRequired["str"] + """ + The exemption indicator returned from Cartes Bancaires in the ARes. + message extension: CB-EXEMPTION; string (4 characters) + This is a 3 byte bitmap (low significant byte first and most significant + bit first) that has been Base64 encoded + """ + cb_score: NotRequired["int"] + """ + The risk score returned from Cartes Bancaires in the ARes. + message extension: CB-SCORE; numeric value 0-99 + """ + + class ConfirmParamsPaymentMethodOptionsLink(TypedDict): + persistent_token: NotRequired["str"] + """ + [Deprecated] This is a legacy parameter that no longer has any function. + """ + + class ConfirmParamsPaymentMethodOptionsPaypal(TypedDict): + billing_agreement_id: NotRequired["str"] + """ + The PayPal Billing Agreement ID (BAID). This is an ID generated by PayPal which represents the mandate between the merchant and the customer. + """ + + class ConfirmParamsPaymentMethodOptionsSepaDebit(TypedDict): + mandate_options: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsSepaDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + + class ConfirmParamsPaymentMethodOptionsSepaDebitMandateOptions(TypedDict): + pass + + class ConfirmParamsPaymentMethodOptionsUsBankAccount(TypedDict): + financial_connections: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsUsBankAccountFinancialConnections" + ] + """ + Additional fields for Financial Connections Session creation + """ + mandate_options: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsUsBankAccountMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + networks: NotRequired[ + "SetupIntentService.ConfirmParamsPaymentMethodOptionsUsBankAccountNetworks" + ] + """ + Additional fields for network related functions + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Bank account verification method. + """ + + class ConfirmParamsPaymentMethodOptionsUsBankAccountFinancialConnections( + TypedDict, + ): + permissions: NotRequired[ + "List[Literal['balances', 'ownership', 'payment_method', 'transactions']]" + ] + """ + The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + """ + prefetch: NotRequired["List[Literal['balances', 'transactions']]"] + """ + List of data features that you would like to retrieve upon account creation. + """ + return_url: NotRequired["str"] + """ + For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + """ + + class ConfirmParamsPaymentMethodOptionsUsBankAccountMandateOptions( + TypedDict, + ): + collection_method: NotRequired["Literal['']|Literal['paper']"] + """ + The method used to collect offline mandate customer acceptance. + """ + + class ConfirmParamsPaymentMethodOptionsUsBankAccountNetworks(TypedDict): + requested: NotRequired["List[Literal['ach', 'us_domestic_wire']]"] + """ + Triggers validations to run across the selected networks + """ + + class CreateParams(TypedDict): + attach_to_self: NotRequired["bool"] + """ + If present, the SetupIntent's payment method will be attached to the in-context Stripe Account. + + It can only be used for this Stripe Account's own money movement flows like InboundTransfer and OutboundTransfers. It cannot be set to true when setting up a PaymentMethod for a Customer, and defaults to false when attaching a PaymentMethod to a Customer. + """ + automatic_payment_methods: NotRequired[ + "SetupIntentService.CreateParamsAutomaticPaymentMethods" + ] + """ + When you enable this parameter, this SetupIntent accepts payment methods that you enable in the Dashboard and that are compatible with its other parameters. + """ + confirm: NotRequired["bool"] + """ + Set to `true` to attempt to confirm this SetupIntent immediately. This parameter defaults to `false`. If a card is the attached payment method, you can provide a `return_url` in case further authentication is necessary. + """ + customer: NotRequired["str"] + """ + ID of the Customer this SetupIntent belongs to, if one exists. + + If present, the SetupIntent's payment method will be attached to the Customer on successful setup. Payment methods attached to other Customers cannot be used with this SetupIntent. + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + flow_directions: NotRequired["List[Literal['inbound', 'outbound']]"] + """ + Indicates the directions of money movement for which this payment method is intended to be used. + + Include `inbound` if you intend to use the payment method as the origin to pull funds from. Include `outbound` if you intend to use the payment method as the destination to send funds to. You can include both if you intend to use the payment method for both purposes. + """ + mandate_data: NotRequired[ + "Literal['']|SetupIntentService.CreateParamsMandateData" + ] + """ + This hash contains details about the mandate to create. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/setup_intents/create#create_setup_intent-confirm). + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + on_behalf_of: NotRequired["str"] + """ + The Stripe account ID created for this SetupIntent. + """ + payment_method: NotRequired["str"] + """ + ID of the payment method (a PaymentMethod, Card, or saved Source object) to attach to this SetupIntent. + """ + payment_method_configuration: NotRequired["str"] + """ + The ID of the payment method configuration to use with this SetupIntent. + """ + payment_method_data: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodData" + ] + """ + When included, this hash creates a PaymentMethod that is set as the [`payment_method`](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-payment_method) + value in the SetupIntent. + """ + payment_method_options: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptions" + ] + """ + Payment method-specific configuration for this SetupIntent. + """ + payment_method_types: NotRequired["List[str]"] + """ + The list of payment method types (for example, card) that this SetupIntent can use. If you don't provide this, it defaults to ["card"]. + """ + return_url: NotRequired["str"] + """ + The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method's app or site. To redirect to a mobile application, you can alternatively supply an application URI scheme. This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/setup_intents/create#create_setup_intent-confirm). + """ + single_use: NotRequired["SetupIntentService.CreateParamsSingleUse"] + """ + If you populate this hash, this SetupIntent generates a `single_use` mandate after successful completion. + """ + usage: NotRequired["Literal['off_session', 'on_session']"] + """ + Indicates how the payment method is intended to be used in the future. If not provided, this value defaults to `off_session`. + """ + use_stripe_sdk: NotRequired["bool"] + """ + Set to `true` when confirming server-side and using Stripe.js, iOS, or Android client-side SDKs to handle the next actions. + """ + + class CreateParamsAutomaticPaymentMethods(TypedDict): + allow_redirects: NotRequired["Literal['always', 'never']"] + """ + Controls whether this SetupIntent will accept redirect-based payment methods. + + Redirect-based payment methods may require your customer to be redirected to a payment method's app or site for authentication or additional steps. To [confirm](https://stripe.com/docs/api/setup_intents/confirm) this SetupIntent, you may be required to provide a `return_url` to redirect customers back to your site after they authenticate or complete the setup. + """ + enabled: bool + """ + Whether this feature is enabled. + """ + + class CreateParamsMandateData(TypedDict): + customer_acceptance: "SetupIntentService.CreateParamsMandateDataCustomerAcceptance" + """ + This hash contains details about the customer acceptance of the Mandate. + """ + + class CreateParamsMandateDataCustomerAcceptance(TypedDict): + accepted_at: NotRequired["int"] + """ + The time at which the customer accepted the Mandate. + """ + offline: NotRequired[ + "SetupIntentService.CreateParamsMandateDataCustomerAcceptanceOffline" + ] + """ + If this is a Mandate accepted offline, this hash contains details about the offline acceptance. + """ + online: NotRequired[ + "SetupIntentService.CreateParamsMandateDataCustomerAcceptanceOnline" + ] + """ + If this is a Mandate accepted online, this hash contains details about the online acceptance. + """ + type: Literal["offline", "online"] + """ + The type of customer acceptance information included with the Mandate. One of `online` or `offline`. + """ + + class CreateParamsMandateDataCustomerAcceptanceOffline(TypedDict): + pass + + class CreateParamsMandateDataCustomerAcceptanceOnline(TypedDict): + ip_address: str + """ + The IP address from which the Mandate was accepted by the customer. + """ + user_agent: str + """ + The user agent of the browser from which the Mandate was accepted by the customer. + """ + + class CreateParamsPaymentMethodData(TypedDict): + acss_debit: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataAcssDebit" + ] + """ + If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + """ + affirm: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataAffirm" + ] + """ + If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + """ + afterpay_clearpay: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataAfterpayClearpay" + ] + """ + If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + """ + alipay: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataAlipay" + ] + """ + If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + """ + au_becs_debit: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataAuBecsDebit" + ] + """ + If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + """ + bacs_debit: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataBacsDebit" + ] + """ + If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + """ + bancontact: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataBancontact" + ] + """ + If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + """ + billing_details: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataBillingDetails" + ] + """ + Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + """ + blik: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataBlik" + ] + """ + If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + """ + boleto: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataBoleto" + ] + """ + If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + """ + cashapp: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataCashapp" + ] + """ + If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + """ + customer_balance: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataCustomerBalance" + ] + """ + If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + """ + eps: NotRequired["SetupIntentService.CreateParamsPaymentMethodDataEps"] + """ + If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + """ + fpx: NotRequired["SetupIntentService.CreateParamsPaymentMethodDataFpx"] + """ + If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + """ + giropay: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataGiropay" + ] + """ + If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + """ + grabpay: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataGrabpay" + ] + """ + If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + """ + ideal: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataIdeal" + ] + """ + If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + """ + interac_present: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataInteracPresent" + ] + """ + If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + """ + klarna: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataKlarna" + ] + """ + If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + """ + konbini: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataKonbini" + ] + """ + If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + """ + link: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataLink" + ] + """ + If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + oxxo: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataOxxo" + ] + """ + If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + """ + p24: NotRequired["SetupIntentService.CreateParamsPaymentMethodDataP24"] + """ + If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + """ + paynow: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataPaynow" + ] + """ + If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + """ + paypal: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataPaypal" + ] + """ + If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + """ + pix: NotRequired["SetupIntentService.CreateParamsPaymentMethodDataPix"] + """ + If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + """ + promptpay: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataPromptpay" + ] + """ + If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + """ + radar_options: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataRadarOptions" + ] + """ + Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + """ + revolut_pay: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataRevolutPay" + ] + """ + If this is a `Revolut Pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + """ + sepa_debit: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataSepaDebit" + ] + """ + If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + """ + sofort: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataSofort" + ] + """ + If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + """ + type: Literal[ + "acss_debit", + "affirm", + "afterpay_clearpay", + "alipay", + "au_becs_debit", + "bacs_debit", + "bancontact", + "blik", + "boleto", + "cashapp", + "customer_balance", + "eps", + "fpx", + "giropay", + "grabpay", + "ideal", + "klarna", + "konbini", + "link", + "oxxo", + "p24", + "paynow", + "paypal", + "pix", + "promptpay", + "revolut_pay", + "sepa_debit", + "sofort", + "us_bank_account", + "wechat_pay", + "zip", + ] + """ + The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + """ + us_bank_account: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataUsBankAccount" + ] + """ + If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + """ + wechat_pay: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataWechatPay" + ] + """ + If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + """ + zip: NotRequired["SetupIntentService.CreateParamsPaymentMethodDataZip"] + """ + If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + """ + + class CreateParamsPaymentMethodDataAcssDebit(TypedDict): + account_number: str + """ + Customer's bank account number. + """ + institution_number: str + """ + Institution number of the customer's bank. + """ + transit_number: str + """ + Transit number of the customer's bank. + """ + + class CreateParamsPaymentMethodDataAffirm(TypedDict): + pass + + class CreateParamsPaymentMethodDataAfterpayClearpay(TypedDict): + pass + + class CreateParamsPaymentMethodDataAlipay(TypedDict): + pass + + class CreateParamsPaymentMethodDataAuBecsDebit(TypedDict): + account_number: str + """ + The account number for the bank account. + """ + bsb_number: str + """ + Bank-State-Branch number of the bank account. + """ + + class CreateParamsPaymentMethodDataBacsDebit(TypedDict): + account_number: NotRequired["str"] + """ + Account number of the bank account that the funds will be debited from. + """ + sort_code: NotRequired["str"] + """ + Sort code of the bank account. (e.g., `10-20-30`) + """ + + class CreateParamsPaymentMethodDataBancontact(TypedDict): + pass + + class CreateParamsPaymentMethodDataBillingDetails(TypedDict): + address: NotRequired[ + "Literal['']|SetupIntentService.CreateParamsPaymentMethodDataBillingDetailsAddress" + ] + """ + Billing address. + """ + email: NotRequired["Literal['']|str"] + """ + Email address. + """ + name: NotRequired["Literal['']|str"] + """ + Full name. + """ + phone: NotRequired["Literal['']|str"] + """ + Billing phone number (including extension). + """ + + class CreateParamsPaymentMethodDataBillingDetailsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsPaymentMethodDataBlik(TypedDict): + pass + + class CreateParamsPaymentMethodDataBoleto(TypedDict): + tax_id: str + """ + The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + """ + + class CreateParamsPaymentMethodDataCashapp(TypedDict): + pass + + class CreateParamsPaymentMethodDataCustomerBalance(TypedDict): + pass + + class CreateParamsPaymentMethodDataEps(TypedDict): + bank: NotRequired[ + "Literal['arzte_und_apotheker_bank', 'austrian_anadi_bank_ag', 'bank_austria', 'bankhaus_carl_spangler', 'bankhaus_schelhammer_und_schattera_ag', 'bawag_psk_ag', 'bks_bank_ag', 'brull_kallmus_bank_ag', 'btv_vier_lander_bank', 'capital_bank_grawe_gruppe_ag', 'deutsche_bank_ag', 'dolomitenbank', 'easybank_ag', 'erste_bank_und_sparkassen', 'hypo_alpeadriabank_international_ag', 'hypo_bank_burgenland_aktiengesellschaft', 'hypo_noe_lb_fur_niederosterreich_u_wien', 'hypo_oberosterreich_salzburg_steiermark', 'hypo_tirol_bank_ag', 'hypo_vorarlberg_bank_ag', 'marchfelder_bank', 'oberbank_ag', 'raiffeisen_bankengruppe_osterreich', 'schoellerbank_ag', 'sparda_bank_wien', 'volksbank_gruppe', 'volkskreditbank_ag', 'vr_bank_braunau']" + ] + """ + The customer's bank. + """ + + class CreateParamsPaymentMethodDataFpx(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type for FPX transaction + """ + bank: Literal[ + "affin_bank", + "agrobank", + "alliance_bank", + "ambank", + "bank_islam", + "bank_muamalat", + "bank_of_china", + "bank_rakyat", + "bsn", + "cimb", + "deutsche_bank", + "hong_leong_bank", + "hsbc", + "kfh", + "maybank2e", + "maybank2u", + "ocbc", + "pb_enterprise", + "public_bank", + "rhb", + "standard_chartered", + "uob", + ] + """ + The customer's bank. + """ + + class CreateParamsPaymentMethodDataGiropay(TypedDict): + pass + + class CreateParamsPaymentMethodDataGrabpay(TypedDict): + pass + + class CreateParamsPaymentMethodDataIdeal(TypedDict): + bank: NotRequired[ + "Literal['abn_amro', 'asn_bank', 'bunq', 'handelsbanken', 'ing', 'knab', 'moneyou', 'n26', 'nn', 'rabobank', 'regiobank', 'revolut', 'sns_bank', 'triodos_bank', 'van_lanschot', 'yoursafe']" + ] + """ + The customer's bank. + """ + + class CreateParamsPaymentMethodDataInteracPresent(TypedDict): + pass + + class CreateParamsPaymentMethodDataKlarna(TypedDict): + dob: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodDataKlarnaDob" + ] + """ + Customer's date of birth + """ + + class CreateParamsPaymentMethodDataKlarnaDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class CreateParamsPaymentMethodDataKonbini(TypedDict): + pass + + class CreateParamsPaymentMethodDataLink(TypedDict): + pass + + class CreateParamsPaymentMethodDataOxxo(TypedDict): + pass + + class CreateParamsPaymentMethodDataP24(TypedDict): + bank: NotRequired[ + "Literal['alior_bank', 'bank_millennium', 'bank_nowy_bfg_sa', 'bank_pekao_sa', 'banki_spbdzielcze', 'blik', 'bnp_paribas', 'boz', 'citi_handlowy', 'credit_agricole', 'envelobank', 'etransfer_pocztowy24', 'getin_bank', 'ideabank', 'ing', 'inteligo', 'mbank_mtransfer', 'nest_przelew', 'noble_pay', 'pbac_z_ipko', 'plus_bank', 'santander_przelew24', 'tmobile_usbugi_bankowe', 'toyota_bank', 'volkswagen_bank']" + ] + """ + The customer's bank. + """ + + class CreateParamsPaymentMethodDataPaynow(TypedDict): + pass + + class CreateParamsPaymentMethodDataPaypal(TypedDict): + pass + + class CreateParamsPaymentMethodDataPix(TypedDict): + pass + + class CreateParamsPaymentMethodDataPromptpay(TypedDict): + pass + + class CreateParamsPaymentMethodDataRadarOptions(TypedDict): + session: NotRequired["str"] + """ + A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + """ + + class CreateParamsPaymentMethodDataRevolutPay(TypedDict): + pass + + class CreateParamsPaymentMethodDataSepaDebit(TypedDict): + iban: str + """ + IBAN of the bank account. + """ + + class CreateParamsPaymentMethodDataSofort(TypedDict): + country: Literal["AT", "BE", "DE", "ES", "IT", "NL"] + """ + Two-letter ISO code representing the country the bank account is located in. + """ + + class CreateParamsPaymentMethodDataUsBankAccount(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type: individual or company. + """ + account_number: NotRequired["str"] + """ + Account number of the bank account. + """ + account_type: NotRequired["Literal['checking', 'savings']"] + """ + Account type: checkings or savings. Defaults to checking if omitted. + """ + financial_connections_account: NotRequired["str"] + """ + The ID of a Financial Connections Account to use as a payment method. + """ + routing_number: NotRequired["str"] + """ + Routing number of the bank account. + """ + + class CreateParamsPaymentMethodDataWechatPay(TypedDict): + pass + + class CreateParamsPaymentMethodDataZip(TypedDict): + pass + + class CreateParamsPaymentMethodOptions(TypedDict): + acss_debit: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsAcssDebit" + ] + """ + If this is a `acss_debit` SetupIntent, this sub-hash contains details about the ACSS Debit payment method options. + """ + card: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsCard" + ] + """ + Configuration for any card setup attempted on this SetupIntent. + """ + link: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsLink" + ] + """ + If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. + """ + paypal: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsPaypal" + ] + """ + If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. + """ + sepa_debit: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsSepaDebit" + ] + """ + If this is a `sepa_debit` SetupIntent, this sub-hash contains details about the SEPA Debit payment method options. + """ + us_bank_account: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsUsBankAccount" + ] + """ + If this is a `us_bank_account` SetupIntent, this sub-hash contains details about the US bank account payment method options. + """ + + class CreateParamsPaymentMethodOptionsAcssDebit(TypedDict): + currency: NotRequired["Literal['cad', 'usd']"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + mandate_options: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsAcssDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Bank account verification method. + """ + + class CreateParamsPaymentMethodOptionsAcssDebitMandateOptions(TypedDict): + custom_mandate_url: NotRequired["Literal['']|str"] + """ + A URL for custom mandate text to render during confirmation step. + The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + """ + default_for: NotRequired["List[Literal['invoice', 'subscription']]"] + """ + List of Stripe products where this mandate can be selected automatically. + """ + interval_description: NotRequired["str"] + """ + Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + """ + payment_schedule: NotRequired[ + "Literal['combined', 'interval', 'sporadic']" + ] + """ + Payment schedule for the mandate. + """ + transaction_type: NotRequired["Literal['business', 'personal']"] + """ + Transaction type of the mandate. + """ + + class CreateParamsPaymentMethodOptionsCard(TypedDict): + mandate_options: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsCardMandateOptions" + ] + """ + Configuration options for setting up an eMandate for cards issued in India. + """ + moto: NotRequired["bool"] + """ + When specified, this parameter signals that a card has been collected + as MOTO (Mail Order Telephone Order) and thus out of scope for SCA. This + parameter can only be provided during confirmation. + """ + network: NotRequired[ + "Literal['amex', 'cartes_bancaires', 'diners', 'discover', 'eftpos_au', 'interac', 'jcb', 'mastercard', 'unionpay', 'unknown', 'visa']" + ] + """ + Selected network to process this SetupIntent on. Depends on the available networks of the card attached to the SetupIntent. Can be only set confirm-time. + """ + request_three_d_secure: NotRequired[ + "Literal['any', 'automatic', 'challenge']" + ] + """ + We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + """ + three_d_secure: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsCardThreeDSecure" + ] + """ + If 3D Secure authentication was performed with a third-party provider, + the authentication details to use for this setup. + """ + + class CreateParamsPaymentMethodOptionsCardMandateOptions(TypedDict): + amount: int + """ + Amount to be charged for future payments. + """ + amount_type: Literal["fixed", "maximum"] + """ + One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + """ + currency: str + """ + Currency in which future payments will be charged. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + description: NotRequired["str"] + """ + A description of the mandate or subscription that is meant to be displayed to the customer. + """ + end_date: NotRequired["int"] + """ + End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + """ + interval: Literal["day", "month", "sporadic", "week", "year"] + """ + Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + """ + reference: str + """ + Unique identifier for the mandate or subscription. + """ + start_date: int + """ + Start date of the mandate or subscription. Start date should not be lesser than yesterday. + """ + supported_types: NotRequired["List[Literal['india']]"] + """ + Specifies the type of mandates supported. Possible values are `india`. + """ + + class CreateParamsPaymentMethodOptionsCardThreeDSecure(TypedDict): + ares_trans_status: NotRequired[ + "Literal['A', 'C', 'I', 'N', 'R', 'U', 'Y']" + ] + """ + The `transStatus` returned from the card Issuer's ACS in the ARes. + """ + cryptogram: NotRequired["str"] + """ + The cryptogram, also known as the "authentication value" (AAV, CAVV or + AEVV). This value is 20 bytes, base64-encoded into a 28-character string. + (Most 3D Secure providers will return the base64-encoded version, which + is what you should specify here.) + """ + electronic_commerce_indicator: NotRequired[ + "Literal['01', '02', '05', '06', '07']" + ] + """ + The Electronic Commerce Indicator (ECI) is returned by your 3D Secure + provider and indicates what degree of authentication was performed. + """ + network_options: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptions" + ] + """ + Network specific 3DS fields. Network specific arguments require an + explicit card brand choice. The parameter `payment_method_options.card.network`` + must be populated accordingly + """ + requestor_challenge_indicator: NotRequired["str"] + """ + The challenge indicator (`threeDSRequestorChallengeInd`) which was requested in the + AReq sent to the card Issuer's ACS. A string containing 2 digits from 01-99. + """ + transaction_id: NotRequired["str"] + """ + For 3D Secure 1, the XID. For 3D Secure 2, the Directory Server + Transaction ID (dsTransID). + """ + version: NotRequired["Literal['1.0.2', '2.1.0', '2.2.0']"] + """ + The version of 3D Secure that was performed. + """ + + class CreateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptions( + TypedDict, + ): + cartes_bancaires: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancaires" + ] + """ + Cartes Bancaires-specific 3DS fields. + """ + + class CreateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancaires( + TypedDict, + ): + cb_avalgo: Literal["0", "1", "2", "3", "4", "A"] + """ + The cryptogram calculation algorithm used by the card Issuer's ACS + to calculate the Authentication cryptogram. Also known as `cavvAlgorithm`. + messageExtension: CB-AVALGO + """ + cb_exemption: NotRequired["str"] + """ + The exemption indicator returned from Cartes Bancaires in the ARes. + message extension: CB-EXEMPTION; string (4 characters) + This is a 3 byte bitmap (low significant byte first and most significant + bit first) that has been Base64 encoded + """ + cb_score: NotRequired["int"] + """ + The risk score returned from Cartes Bancaires in the ARes. + message extension: CB-SCORE; numeric value 0-99 + """ + + class CreateParamsPaymentMethodOptionsLink(TypedDict): + persistent_token: NotRequired["str"] + """ + [Deprecated] This is a legacy parameter that no longer has any function. + """ + + class CreateParamsPaymentMethodOptionsPaypal(TypedDict): + billing_agreement_id: NotRequired["str"] + """ + The PayPal Billing Agreement ID (BAID). This is an ID generated by PayPal which represents the mandate between the merchant and the customer. + """ + + class CreateParamsPaymentMethodOptionsSepaDebit(TypedDict): + mandate_options: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsSepaDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + + class CreateParamsPaymentMethodOptionsSepaDebitMandateOptions(TypedDict): + pass + + class CreateParamsPaymentMethodOptionsUsBankAccount(TypedDict): + financial_connections: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsUsBankAccountFinancialConnections" + ] + """ + Additional fields for Financial Connections Session creation + """ + mandate_options: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsUsBankAccountMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + networks: NotRequired[ + "SetupIntentService.CreateParamsPaymentMethodOptionsUsBankAccountNetworks" + ] + """ + Additional fields for network related functions + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Bank account verification method. + """ + + class CreateParamsPaymentMethodOptionsUsBankAccountFinancialConnections( + TypedDict, + ): + permissions: NotRequired[ + "List[Literal['balances', 'ownership', 'payment_method', 'transactions']]" + ] + """ + The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + """ + prefetch: NotRequired["List[Literal['balances', 'transactions']]"] + """ + List of data features that you would like to retrieve upon account creation. + """ + return_url: NotRequired["str"] + """ + For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + """ + + class CreateParamsPaymentMethodOptionsUsBankAccountMandateOptions( + TypedDict, + ): + collection_method: NotRequired["Literal['']|Literal['paper']"] + """ + The method used to collect offline mandate customer acceptance. + """ + + class CreateParamsPaymentMethodOptionsUsBankAccountNetworks(TypedDict): + requested: NotRequired["List[Literal['ach', 'us_domestic_wire']]"] + """ + Triggers validations to run across the selected networks + """ + + class CreateParamsSingleUse(TypedDict): + amount: int + """ + Amount the customer is granting permission to collect later. A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + + class ListParams(TypedDict): + attach_to_self: NotRequired["bool"] + """ + If present, the SetupIntent's payment method will be attached to the in-context Stripe Account. + + It can only be used for this Stripe Account's own money movement flows like InboundTransfer and OutboundTransfers. It cannot be set to true when setting up a PaymentMethod for a Customer, and defaults to false when attaching a PaymentMethod to a Customer. + """ + created: NotRequired["SetupIntentService.ListParamsCreated|int"] + """ + A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + """ + customer: NotRequired["str"] + """ + Only return SetupIntents for the customer specified by this customer ID. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + payment_method: NotRequired["str"] + """ + Only return SetupIntents that associate with the specified payment method. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + client_secret: NotRequired["str"] + """ + The client secret of the SetupIntent. We require this string if you use a publishable key to retrieve the SetupIntent. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + attach_to_self: NotRequired["bool"] + """ + If present, the SetupIntent's payment method will be attached to the in-context Stripe Account. + + It can only be used for this Stripe Account's own money movement flows like InboundTransfer and OutboundTransfers. It cannot be set to true when setting up a PaymentMethod for a Customer, and defaults to false when attaching a PaymentMethod to a Customer. + """ + customer: NotRequired["str"] + """ + ID of the Customer this SetupIntent belongs to, if one exists. + + If present, the SetupIntent's payment method will be attached to the Customer on successful setup. Payment methods attached to other Customers cannot be used with this SetupIntent. + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + flow_directions: NotRequired["List[Literal['inbound', 'outbound']]"] + """ + Indicates the directions of money movement for which this payment method is intended to be used. + + Include `inbound` if you intend to use the payment method as the origin to pull funds from. Include `outbound` if you intend to use the payment method as the destination to send funds to. You can include both if you intend to use the payment method for both purposes. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + payment_method: NotRequired["str"] + """ + ID of the payment method (a PaymentMethod, Card, or saved Source object) to attach to this SetupIntent. + """ + payment_method_configuration: NotRequired["str"] + """ + The ID of the payment method configuration to use with this SetupIntent. + """ + payment_method_data: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodData" + ] + """ + When included, this hash creates a PaymentMethod that is set as the [`payment_method`](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-payment_method) + value in the SetupIntent. + """ + payment_method_options: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptions" + ] + """ + Payment method-specific configuration for this SetupIntent. + """ + payment_method_types: NotRequired["List[str]"] + """ + The list of payment method types (for example, card) that this SetupIntent can set up. If you don't provide this array, it defaults to ["card"]. + """ + + class UpdateParamsPaymentMethodData(TypedDict): + acss_debit: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataAcssDebit" + ] + """ + If this is an `acss_debit` PaymentMethod, this hash contains details about the ACSS Debit payment method. + """ + affirm: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataAffirm" + ] + """ + If this is an `affirm` PaymentMethod, this hash contains details about the Affirm payment method. + """ + afterpay_clearpay: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataAfterpayClearpay" + ] + """ + If this is an `AfterpayClearpay` PaymentMethod, this hash contains details about the AfterpayClearpay payment method. + """ + alipay: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataAlipay" + ] + """ + If this is an `Alipay` PaymentMethod, this hash contains details about the Alipay payment method. + """ + au_becs_debit: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataAuBecsDebit" + ] + """ + If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + """ + bacs_debit: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataBacsDebit" + ] + """ + If this is a `bacs_debit` PaymentMethod, this hash contains details about the Bacs Direct Debit bank account. + """ + bancontact: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataBancontact" + ] + """ + If this is a `bancontact` PaymentMethod, this hash contains details about the Bancontact payment method. + """ + billing_details: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataBillingDetails" + ] + """ + Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + """ + blik: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataBlik" + ] + """ + If this is a `blik` PaymentMethod, this hash contains details about the BLIK payment method. + """ + boleto: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataBoleto" + ] + """ + If this is a `boleto` PaymentMethod, this hash contains details about the Boleto payment method. + """ + cashapp: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataCashapp" + ] + """ + If this is a `cashapp` PaymentMethod, this hash contains details about the Cash App Pay payment method. + """ + customer_balance: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataCustomerBalance" + ] + """ + If this is a `customer_balance` PaymentMethod, this hash contains details about the CustomerBalance payment method. + """ + eps: NotRequired["SetupIntentService.UpdateParamsPaymentMethodDataEps"] + """ + If this is an `eps` PaymentMethod, this hash contains details about the EPS payment method. + """ + fpx: NotRequired["SetupIntentService.UpdateParamsPaymentMethodDataFpx"] + """ + If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + """ + giropay: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataGiropay" + ] + """ + If this is a `giropay` PaymentMethod, this hash contains details about the Giropay payment method. + """ + grabpay: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataGrabpay" + ] + """ + If this is a `grabpay` PaymentMethod, this hash contains details about the GrabPay payment method. + """ + ideal: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataIdeal" + ] + """ + If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + """ + interac_present: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataInteracPresent" + ] + """ + If this is an `interac_present` PaymentMethod, this hash contains details about the Interac Present payment method. + """ + klarna: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataKlarna" + ] + """ + If this is a `klarna` PaymentMethod, this hash contains details about the Klarna payment method. + """ + konbini: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataKonbini" + ] + """ + If this is a `konbini` PaymentMethod, this hash contains details about the Konbini payment method. + """ + link: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataLink" + ] + """ + If this is an `Link` PaymentMethod, this hash contains details about the Link payment method. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + oxxo: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataOxxo" + ] + """ + If this is an `oxxo` PaymentMethod, this hash contains details about the OXXO payment method. + """ + p24: NotRequired["SetupIntentService.UpdateParamsPaymentMethodDataP24"] + """ + If this is a `p24` PaymentMethod, this hash contains details about the P24 payment method. + """ + paynow: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataPaynow" + ] + """ + If this is a `paynow` PaymentMethod, this hash contains details about the PayNow payment method. + """ + paypal: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataPaypal" + ] + """ + If this is a `paypal` PaymentMethod, this hash contains details about the PayPal payment method. + """ + pix: NotRequired["SetupIntentService.UpdateParamsPaymentMethodDataPix"] + """ + If this is a `pix` PaymentMethod, this hash contains details about the Pix payment method. + """ + promptpay: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataPromptpay" + ] + """ + If this is a `promptpay` PaymentMethod, this hash contains details about the PromptPay payment method. + """ + radar_options: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataRadarOptions" + ] + """ + Options to configure Radar. See [Radar Session](https://stripe.com/docs/radar/radar-session) for more information. + """ + revolut_pay: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataRevolutPay" + ] + """ + If this is a `Revolut Pay` PaymentMethod, this hash contains details about the Revolut Pay payment method. + """ + sepa_debit: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataSepaDebit" + ] + """ + If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + """ + sofort: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataSofort" + ] + """ + If this is a `sofort` PaymentMethod, this hash contains details about the SOFORT payment method. + """ + type: Literal[ + "acss_debit", + "affirm", + "afterpay_clearpay", + "alipay", + "au_becs_debit", + "bacs_debit", + "bancontact", + "blik", + "boleto", + "cashapp", + "customer_balance", + "eps", + "fpx", + "giropay", + "grabpay", + "ideal", + "klarna", + "konbini", + "link", + "oxxo", + "p24", + "paynow", + "paypal", + "pix", + "promptpay", + "revolut_pay", + "sepa_debit", + "sofort", + "us_bank_account", + "wechat_pay", + "zip", + ] + """ + The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + """ + us_bank_account: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataUsBankAccount" + ] + """ + If this is an `us_bank_account` PaymentMethod, this hash contains details about the US bank account payment method. + """ + wechat_pay: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataWechatPay" + ] + """ + If this is an `wechat_pay` PaymentMethod, this hash contains details about the wechat_pay payment method. + """ + zip: NotRequired["SetupIntentService.UpdateParamsPaymentMethodDataZip"] + """ + If this is a `zip` PaymentMethod, this hash contains details about the Zip payment method. + """ + + class UpdateParamsPaymentMethodDataAcssDebit(TypedDict): + account_number: str + """ + Customer's bank account number. + """ + institution_number: str + """ + Institution number of the customer's bank. + """ + transit_number: str + """ + Transit number of the customer's bank. + """ + + class UpdateParamsPaymentMethodDataAffirm(TypedDict): + pass + + class UpdateParamsPaymentMethodDataAfterpayClearpay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataAlipay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataAuBecsDebit(TypedDict): + account_number: str + """ + The account number for the bank account. + """ + bsb_number: str + """ + Bank-State-Branch number of the bank account. + """ + + class UpdateParamsPaymentMethodDataBacsDebit(TypedDict): + account_number: NotRequired["str"] + """ + Account number of the bank account that the funds will be debited from. + """ + sort_code: NotRequired["str"] + """ + Sort code of the bank account. (e.g., `10-20-30`) + """ + + class UpdateParamsPaymentMethodDataBancontact(TypedDict): + pass + + class UpdateParamsPaymentMethodDataBillingDetails(TypedDict): + address: NotRequired[ + "Literal['']|SetupIntentService.UpdateParamsPaymentMethodDataBillingDetailsAddress" + ] + """ + Billing address. + """ + email: NotRequired["Literal['']|str"] + """ + Email address. + """ + name: NotRequired["Literal['']|str"] + """ + Full name. + """ + phone: NotRequired["Literal['']|str"] + """ + Billing phone number (including extension). + """ + + class UpdateParamsPaymentMethodDataBillingDetailsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsPaymentMethodDataBlik(TypedDict): + pass + + class UpdateParamsPaymentMethodDataBoleto(TypedDict): + tax_id: str + """ + The tax ID of the customer (CPF for individual consumers or CNPJ for businesses consumers) + """ + + class UpdateParamsPaymentMethodDataCashapp(TypedDict): + pass + + class UpdateParamsPaymentMethodDataCustomerBalance(TypedDict): + pass + + class UpdateParamsPaymentMethodDataEps(TypedDict): + bank: NotRequired[ + "Literal['arzte_und_apotheker_bank', 'austrian_anadi_bank_ag', 'bank_austria', 'bankhaus_carl_spangler', 'bankhaus_schelhammer_und_schattera_ag', 'bawag_psk_ag', 'bks_bank_ag', 'brull_kallmus_bank_ag', 'btv_vier_lander_bank', 'capital_bank_grawe_gruppe_ag', 'deutsche_bank_ag', 'dolomitenbank', 'easybank_ag', 'erste_bank_und_sparkassen', 'hypo_alpeadriabank_international_ag', 'hypo_bank_burgenland_aktiengesellschaft', 'hypo_noe_lb_fur_niederosterreich_u_wien', 'hypo_oberosterreich_salzburg_steiermark', 'hypo_tirol_bank_ag', 'hypo_vorarlberg_bank_ag', 'marchfelder_bank', 'oberbank_ag', 'raiffeisen_bankengruppe_osterreich', 'schoellerbank_ag', 'sparda_bank_wien', 'volksbank_gruppe', 'volkskreditbank_ag', 'vr_bank_braunau']" + ] + """ + The customer's bank. + """ + + class UpdateParamsPaymentMethodDataFpx(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type for FPX transaction + """ + bank: Literal[ + "affin_bank", + "agrobank", + "alliance_bank", + "ambank", + "bank_islam", + "bank_muamalat", + "bank_of_china", + "bank_rakyat", + "bsn", + "cimb", + "deutsche_bank", + "hong_leong_bank", + "hsbc", + "kfh", + "maybank2e", + "maybank2u", + "ocbc", + "pb_enterprise", + "public_bank", + "rhb", + "standard_chartered", + "uob", + ] + """ + The customer's bank. + """ + + class UpdateParamsPaymentMethodDataGiropay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataGrabpay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataIdeal(TypedDict): + bank: NotRequired[ + "Literal['abn_amro', 'asn_bank', 'bunq', 'handelsbanken', 'ing', 'knab', 'moneyou', 'n26', 'nn', 'rabobank', 'regiobank', 'revolut', 'sns_bank', 'triodos_bank', 'van_lanschot', 'yoursafe']" + ] + """ + The customer's bank. + """ + + class UpdateParamsPaymentMethodDataInteracPresent(TypedDict): + pass + + class UpdateParamsPaymentMethodDataKlarna(TypedDict): + dob: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodDataKlarnaDob" + ] + """ + Customer's date of birth + """ + + class UpdateParamsPaymentMethodDataKlarnaDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class UpdateParamsPaymentMethodDataKonbini(TypedDict): + pass + + class UpdateParamsPaymentMethodDataLink(TypedDict): + pass + + class UpdateParamsPaymentMethodDataOxxo(TypedDict): + pass + + class UpdateParamsPaymentMethodDataP24(TypedDict): + bank: NotRequired[ + "Literal['alior_bank', 'bank_millennium', 'bank_nowy_bfg_sa', 'bank_pekao_sa', 'banki_spbdzielcze', 'blik', 'bnp_paribas', 'boz', 'citi_handlowy', 'credit_agricole', 'envelobank', 'etransfer_pocztowy24', 'getin_bank', 'ideabank', 'ing', 'inteligo', 'mbank_mtransfer', 'nest_przelew', 'noble_pay', 'pbac_z_ipko', 'plus_bank', 'santander_przelew24', 'tmobile_usbugi_bankowe', 'toyota_bank', 'volkswagen_bank']" + ] + """ + The customer's bank. + """ + + class UpdateParamsPaymentMethodDataPaynow(TypedDict): + pass + + class UpdateParamsPaymentMethodDataPaypal(TypedDict): + pass + + class UpdateParamsPaymentMethodDataPix(TypedDict): + pass + + class UpdateParamsPaymentMethodDataPromptpay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataRadarOptions(TypedDict): + session: NotRequired["str"] + """ + A [Radar Session](https://stripe.com/docs/radar/radar-session) is a snapshot of the browser metadata and device details that help Radar make more accurate predictions on your payments. + """ + + class UpdateParamsPaymentMethodDataRevolutPay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataSepaDebit(TypedDict): + iban: str + """ + IBAN of the bank account. + """ + + class UpdateParamsPaymentMethodDataSofort(TypedDict): + country: Literal["AT", "BE", "DE", "ES", "IT", "NL"] + """ + Two-letter ISO code representing the country the bank account is located in. + """ + + class UpdateParamsPaymentMethodDataUsBankAccount(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type: individual or company. + """ + account_number: NotRequired["str"] + """ + Account number of the bank account. + """ + account_type: NotRequired["Literal['checking', 'savings']"] + """ + Account type: checkings or savings. Defaults to checking if omitted. + """ + financial_connections_account: NotRequired["str"] + """ + The ID of a Financial Connections Account to use as a payment method. + """ + routing_number: NotRequired["str"] + """ + Routing number of the bank account. + """ + + class UpdateParamsPaymentMethodDataWechatPay(TypedDict): + pass + + class UpdateParamsPaymentMethodDataZip(TypedDict): + pass + + class UpdateParamsPaymentMethodOptions(TypedDict): + acss_debit: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsAcssDebit" + ] + """ + If this is a `acss_debit` SetupIntent, this sub-hash contains details about the ACSS Debit payment method options. + """ + card: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsCard" + ] + """ + Configuration for any card setup attempted on this SetupIntent. + """ + link: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsLink" + ] + """ + If this is a `link` PaymentMethod, this sub-hash contains details about the Link payment method options. + """ + paypal: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsPaypal" + ] + """ + If this is a `paypal` PaymentMethod, this sub-hash contains details about the PayPal payment method options. + """ + sepa_debit: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsSepaDebit" + ] + """ + If this is a `sepa_debit` SetupIntent, this sub-hash contains details about the SEPA Debit payment method options. + """ + us_bank_account: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsUsBankAccount" + ] + """ + If this is a `us_bank_account` SetupIntent, this sub-hash contains details about the US bank account payment method options. + """ + + class UpdateParamsPaymentMethodOptionsAcssDebit(TypedDict): + currency: NotRequired["Literal['cad', 'usd']"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + mandate_options: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsAcssDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Bank account verification method. + """ + + class UpdateParamsPaymentMethodOptionsAcssDebitMandateOptions(TypedDict): + custom_mandate_url: NotRequired["Literal['']|str"] + """ + A URL for custom mandate text to render during confirmation step. + The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + """ + default_for: NotRequired["List[Literal['invoice', 'subscription']]"] + """ + List of Stripe products where this mandate can be selected automatically. + """ + interval_description: NotRequired["str"] + """ + Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + """ + payment_schedule: NotRequired[ + "Literal['combined', 'interval', 'sporadic']" + ] + """ + Payment schedule for the mandate. + """ + transaction_type: NotRequired["Literal['business', 'personal']"] + """ + Transaction type of the mandate. + """ + + class UpdateParamsPaymentMethodOptionsCard(TypedDict): + mandate_options: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsCardMandateOptions" + ] + """ + Configuration options for setting up an eMandate for cards issued in India. + """ + moto: NotRequired["bool"] + """ + When specified, this parameter signals that a card has been collected + as MOTO (Mail Order Telephone Order) and thus out of scope for SCA. This + parameter can only be provided during confirmation. + """ + network: NotRequired[ + "Literal['amex', 'cartes_bancaires', 'diners', 'discover', 'eftpos_au', 'interac', 'jcb', 'mastercard', 'unionpay', 'unknown', 'visa']" + ] + """ + Selected network to process this SetupIntent on. Depends on the available networks of the card attached to the SetupIntent. Can be only set confirm-time. + """ + request_three_d_secure: NotRequired[ + "Literal['any', 'automatic', 'challenge']" + ] + """ + We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. If not provided, this value defaults to `automatic`. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + """ + three_d_secure: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsCardThreeDSecure" + ] + """ + If 3D Secure authentication was performed with a third-party provider, + the authentication details to use for this setup. + """ + + class UpdateParamsPaymentMethodOptionsCardMandateOptions(TypedDict): + amount: int + """ + Amount to be charged for future payments. + """ + amount_type: Literal["fixed", "maximum"] + """ + One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + """ + currency: str + """ + Currency in which future payments will be charged. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + description: NotRequired["str"] + """ + A description of the mandate or subscription that is meant to be displayed to the customer. + """ + end_date: NotRequired["int"] + """ + End date of the mandate or subscription. If not provided, the mandate will be active until canceled. If provided, end date should be after start date. + """ + interval: Literal["day", "month", "sporadic", "week", "year"] + """ + Specifies payment frequency. One of `day`, `week`, `month`, `year`, or `sporadic`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between payments. For example, `interval=month` and `interval_count=3` indicates one payment every three months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). This parameter is optional when `interval=sporadic`. + """ + reference: str + """ + Unique identifier for the mandate or subscription. + """ + start_date: int + """ + Start date of the mandate or subscription. Start date should not be lesser than yesterday. + """ + supported_types: NotRequired["List[Literal['india']]"] + """ + Specifies the type of mandates supported. Possible values are `india`. + """ + + class UpdateParamsPaymentMethodOptionsCardThreeDSecure(TypedDict): + ares_trans_status: NotRequired[ + "Literal['A', 'C', 'I', 'N', 'R', 'U', 'Y']" + ] + """ + The `transStatus` returned from the card Issuer's ACS in the ARes. + """ + cryptogram: NotRequired["str"] + """ + The cryptogram, also known as the "authentication value" (AAV, CAVV or + AEVV). This value is 20 bytes, base64-encoded into a 28-character string. + (Most 3D Secure providers will return the base64-encoded version, which + is what you should specify here.) + """ + electronic_commerce_indicator: NotRequired[ + "Literal['01', '02', '05', '06', '07']" + ] + """ + The Electronic Commerce Indicator (ECI) is returned by your 3D Secure + provider and indicates what degree of authentication was performed. + """ + network_options: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptions" + ] + """ + Network specific 3DS fields. Network specific arguments require an + explicit card brand choice. The parameter `payment_method_options.card.network`` + must be populated accordingly + """ + requestor_challenge_indicator: NotRequired["str"] + """ + The challenge indicator (`threeDSRequestorChallengeInd`) which was requested in the + AReq sent to the card Issuer's ACS. A string containing 2 digits from 01-99. + """ + transaction_id: NotRequired["str"] + """ + For 3D Secure 1, the XID. For 3D Secure 2, the Directory Server + Transaction ID (dsTransID). + """ + version: NotRequired["Literal['1.0.2', '2.1.0', '2.2.0']"] + """ + The version of 3D Secure that was performed. + """ + + class UpdateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptions( + TypedDict, + ): + cartes_bancaires: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancaires" + ] + """ + Cartes Bancaires-specific 3DS fields. + """ + + class UpdateParamsPaymentMethodOptionsCardThreeDSecureNetworkOptionsCartesBancaires( + TypedDict, + ): + cb_avalgo: Literal["0", "1", "2", "3", "4", "A"] + """ + The cryptogram calculation algorithm used by the card Issuer's ACS + to calculate the Authentication cryptogram. Also known as `cavvAlgorithm`. + messageExtension: CB-AVALGO + """ + cb_exemption: NotRequired["str"] + """ + The exemption indicator returned from Cartes Bancaires in the ARes. + message extension: CB-EXEMPTION; string (4 characters) + This is a 3 byte bitmap (low significant byte first and most significant + bit first) that has been Base64 encoded + """ + cb_score: NotRequired["int"] + """ + The risk score returned from Cartes Bancaires in the ARes. + message extension: CB-SCORE; numeric value 0-99 + """ + + class UpdateParamsPaymentMethodOptionsLink(TypedDict): + persistent_token: NotRequired["str"] + """ + [Deprecated] This is a legacy parameter that no longer has any function. + """ + + class UpdateParamsPaymentMethodOptionsPaypal(TypedDict): + billing_agreement_id: NotRequired["str"] + """ + The PayPal Billing Agreement ID (BAID). This is an ID generated by PayPal which represents the mandate between the merchant and the customer. + """ + + class UpdateParamsPaymentMethodOptionsSepaDebit(TypedDict): + mandate_options: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsSepaDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + + class UpdateParamsPaymentMethodOptionsSepaDebitMandateOptions(TypedDict): + pass + + class UpdateParamsPaymentMethodOptionsUsBankAccount(TypedDict): + financial_connections: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsUsBankAccountFinancialConnections" + ] + """ + Additional fields for Financial Connections Session creation + """ + mandate_options: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsUsBankAccountMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + networks: NotRequired[ + "SetupIntentService.UpdateParamsPaymentMethodOptionsUsBankAccountNetworks" + ] + """ + Additional fields for network related functions + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Bank account verification method. + """ + + class UpdateParamsPaymentMethodOptionsUsBankAccountFinancialConnections( + TypedDict, + ): + permissions: NotRequired[ + "List[Literal['balances', 'ownership', 'payment_method', 'transactions']]" + ] + """ + The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + """ + prefetch: NotRequired["List[Literal['balances', 'transactions']]"] + """ + List of data features that you would like to retrieve upon account creation. + """ + return_url: NotRequired["str"] + """ + For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + """ + + class UpdateParamsPaymentMethodOptionsUsBankAccountMandateOptions( + TypedDict, + ): + collection_method: NotRequired["Literal['']|Literal['paper']"] + """ + The method used to collect offline mandate customer acceptance. + """ + + class UpdateParamsPaymentMethodOptionsUsBankAccountNetworks(TypedDict): + requested: NotRequired["List[Literal['ach', 'us_domestic_wire']]"] + """ + Triggers validations to run across the selected networks + """ + + class VerifyMicrodepositsParams(TypedDict): + amounts: NotRequired["List[int]"] + """ + Two positive integers, in *cents*, equal to the values of the microdeposits sent to the bank account. + """ + descriptor_code: NotRequired["str"] + """ + A six-character code starting with SM present in the microdeposit sent to the bank account. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "SetupIntentService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[SetupIntent]: + """ + Returns a list of SetupIntents. + """ + return cast( + ListObject[SetupIntent], + self._requestor.request( + "get", + "/v1/setup_intents", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "SetupIntentService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> SetupIntent: + """ + Creates a SetupIntent object. + + After you create the SetupIntent, attach a payment method and [confirm](https://stripe.com/docs/api/setup_intents/confirm) + it to collect any required permissions to charge the payment method later. + """ + return cast( + SetupIntent, + self._requestor.request( + "post", + "/v1/setup_intents", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + intent: str, + params: "SetupIntentService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> SetupIntent: + """ + Retrieves the details of a SetupIntent that has previously been created. + + Client-side retrieval using a publishable key is allowed when the client_secret is provided in the query string. + + When retrieved with a publishable key, only a subset of properties will be returned. Please refer to the [SetupIntent](https://stripe.com/docs/api#setup_intent_object) object reference for more details. + """ + return cast( + SetupIntent, + self._requestor.request( + "get", + "/v1/setup_intents/{intent}".format( + intent=_util.sanitize_id(intent), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + intent: str, + params: "SetupIntentService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> SetupIntent: + """ + Updates a SetupIntent object. + """ + return cast( + SetupIntent, + self._requestor.request( + "post", + "/v1/setup_intents/{intent}".format( + intent=_util.sanitize_id(intent), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def cancel( + self, + intent: str, + params: "SetupIntentService.CancelParams" = {}, + options: RequestOptions = {}, + ) -> SetupIntent: + """ + You can cancel a SetupIntent object when it's in one of these statuses: requires_payment_method, requires_confirmation, or requires_action. + + After you cancel it, setup is abandoned and any operations on the SetupIntent fail with an error. + """ + return cast( + SetupIntent, + self._requestor.request( + "post", + "/v1/setup_intents/{intent}/cancel".format( + intent=_util.sanitize_id(intent), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def confirm( + self, + intent: str, + params: "SetupIntentService.ConfirmParams" = {}, + options: RequestOptions = {}, + ) -> SetupIntent: + """ + Confirm that your customer intends to set up the current or + provided payment method. For example, you would confirm a SetupIntent + when a customer hits the “Save” button on a payment method management + page on your website. + + If the selected payment method does not require any additional + steps from the customer, the SetupIntent will transition to the + succeeded status. + + Otherwise, it will transition to the requires_action status and + suggest additional actions via next_action. If setup fails, + the SetupIntent will transition to the + requires_payment_method status or the canceled status if the + confirmation limit is reached. + """ + return cast( + SetupIntent, + self._requestor.request( + "post", + "/v1/setup_intents/{intent}/confirm".format( + intent=_util.sanitize_id(intent), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def verify_microdeposits( + self, + intent: str, + params: "SetupIntentService.VerifyMicrodepositsParams" = {}, + options: RequestOptions = {}, + ) -> SetupIntent: + """ + Verifies microdeposits on a SetupIntent object. + """ + return cast( + SetupIntent, + self._requestor.request( + "post", + "/v1/setup_intents/{intent}/verify_microdeposits".format( + intent=_util.sanitize_id(intent), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_shipping_rate.py b/stripe/_shipping_rate.py index e0df70e4c..d70367f08 100644 --- a/stripe/_shipping_rate.py +++ b/stripe/_shipping_rate.py @@ -336,14 +336,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ShippingRate.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ShippingRate.CreateParams"] ) -> "ShippingRate": """ Creates a new shipping rate object. @@ -353,23 +346,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ShippingRate.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ShippingRate.ListParams"] ) -> ListObject["ShippingRate"]: """ Returns a list of your shipping rates. @@ -377,9 +360,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_shipping_rate_service.py b/stripe/_shipping_rate_service.py new file mode 100644 index 000000000..564a21f82 --- /dev/null +++ b/stripe/_shipping_rate_service.py @@ -0,0 +1,299 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._shipping_rate import ShippingRate +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ShippingRateService(StripeService): + class CreateParams(TypedDict): + delivery_estimate: NotRequired[ + "ShippingRateService.CreateParamsDeliveryEstimate" + ] + """ + The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. + """ + display_name: str + """ + The name of the shipping rate, meant to be displayable to the customer. This will appear on CheckoutSessions. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + fixed_amount: NotRequired[ + "ShippingRateService.CreateParamsFixedAmount" + ] + """ + Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + """ + tax_code: NotRequired["str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. The Shipping tax code is `txcd_92010001`. + """ + type: NotRequired["Literal['fixed_amount']"] + """ + The type of calculation to use on the shipping rate. Can only be `fixed_amount` for now. + """ + + class CreateParamsDeliveryEstimate(TypedDict): + maximum: NotRequired[ + "ShippingRateService.CreateParamsDeliveryEstimateMaximum" + ] + """ + The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. + """ + minimum: NotRequired[ + "ShippingRateService.CreateParamsDeliveryEstimateMinimum" + ] + """ + The lower bound of the estimated range. If empty, represents no lower bound. + """ + + class CreateParamsDeliveryEstimateMaximum(TypedDict): + unit: Literal["business_day", "day", "hour", "month", "week"] + """ + A unit of time. + """ + value: int + """ + Must be greater than 0. + """ + + class CreateParamsDeliveryEstimateMinimum(TypedDict): + unit: Literal["business_day", "day", "hour", "month", "week"] + """ + A unit of time. + """ + value: int + """ + Must be greater than 0. + """ + + class CreateParamsFixedAmount(TypedDict): + amount: int + """ + A non-negative integer in cents representing how much to charge. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + currency_options: NotRequired[ + "Dict[str, ShippingRateService.CreateParamsFixedAmountCurrencyOptions]" + ] + """ + Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + """ + + class CreateParamsFixedAmountCurrencyOptions(TypedDict): + amount: int + """ + A non-negative integer in cents representing how much to charge. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + """ + + class ListParams(TypedDict): + active: NotRequired["bool"] + """ + Only return shipping rates that are active or inactive. + """ + created: NotRequired["ShippingRateService.ListParamsCreated|int"] + """ + A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + """ + currency: NotRequired["str"] + """ + Only return shipping rates for the given currency. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + active: NotRequired["bool"] + """ + Whether the shipping rate can be used for new purchases. Defaults to `true`. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + fixed_amount: NotRequired[ + "ShippingRateService.UpdateParamsFixedAmount" + ] + """ + Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + """ + + class UpdateParamsFixedAmount(TypedDict): + currency_options: NotRequired[ + "Dict[str, ShippingRateService.UpdateParamsFixedAmountCurrencyOptions]" + ] + """ + Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + """ + + class UpdateParamsFixedAmountCurrencyOptions(TypedDict): + amount: NotRequired["int"] + """ + A non-negative integer in cents representing how much to charge. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + """ + + def list( + self, + params: "ShippingRateService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[ShippingRate]: + """ + Returns a list of your shipping rates. + """ + return cast( + ListObject[ShippingRate], + self._requestor.request( + "get", + "/v1/shipping_rates", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "ShippingRateService.CreateParams", + options: RequestOptions = {}, + ) -> ShippingRate: + """ + Creates a new shipping rate object. + """ + return cast( + ShippingRate, + self._requestor.request( + "post", + "/v1/shipping_rates", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + shipping_rate_token: str, + params: "ShippingRateService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> ShippingRate: + """ + Returns the shipping rate object with the given ID. + """ + return cast( + ShippingRate, + self._requestor.request( + "get", + "/v1/shipping_rates/{shipping_rate_token}".format( + shipping_rate_token=_util.sanitize_id(shipping_rate_token), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + shipping_rate_token: str, + params: "ShippingRateService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> ShippingRate: + """ + Updates an existing shipping rate object. + """ + return cast( + ShippingRate, + self._requestor.request( + "post", + "/v1/shipping_rates/{shipping_rate_token}".format( + shipping_rate_token=_util.sanitize_id(shipping_rate_token), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_sigma_service.py b/stripe/_sigma_service.py new file mode 100644 index 000000000..4e275554e --- /dev/null +++ b/stripe/_sigma_service.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.sigma._scheduled_query_run_service import ScheduledQueryRunService + + +class SigmaService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.scheduled_query_runs = ScheduledQueryRunService(self._requestor) diff --git a/stripe/_source.py b/stripe/_source.py index 7e6a16b9a..ccc5a9b3e 100644 --- a/stripe/_source.py +++ b/stripe/_source.py @@ -1112,16 +1112,7 @@ class VerifyParams(RequestOptions): wechat: Optional[Wechat] @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Source.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Source": + def create(cls, **params: Unpack["Source.CreateParams"]) -> "Source": """ Creates a new source object. """ @@ -1130,10 +1121,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -1142,12 +1129,7 @@ def create( def _cls_list_source_transactions( cls, source: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Source.ListSourceTransactionsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Source.ListSourceTransactionsParams"] ) -> ListObject["SourceTransaction"]: """ List source transactions for a given source. @@ -1159,9 +1141,6 @@ def _cls_list_source_transactions( "/v1/sources/{source}/source_transactions".format( source=_util.sanitize_id(source) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1169,13 +1148,7 @@ def _cls_list_source_transactions( @overload @staticmethod def list_source_transactions( - source: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Source.ListSourceTransactionsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + source: str, **params: Unpack["Source.ListSourceTransactionsParams"] ) -> ListObject["SourceTransaction"]: """ List source transactions for a given source. @@ -1184,11 +1157,7 @@ def list_source_transactions( @overload def list_source_transactions( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Source.ListSourceTransactionsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Source.ListSourceTransactionsParams"] ) -> ListObject["SourceTransaction"]: """ List source transactions for a given source. @@ -1197,11 +1166,7 @@ def list_source_transactions( @class_method_variant("_cls_list_source_transactions") def list_source_transactions( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Source.ListSourceTransactionsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Source.ListSourceTransactionsParams"] ) -> ListObject["SourceTransaction"]: """ List source transactions for a given source. @@ -1213,7 +1178,6 @@ def list_source_transactions( # pyright: ignore[reportGeneralTypeIssues] "/v1/sources/{source}/source_transactions".format( source=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -1246,14 +1210,7 @@ def retrieve( @classmethod def _cls_verify( - cls, - source: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Source.VerifyParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, source: str, **params: Unpack["Source.VerifyParams"] ) -> "Source": """ Verify a given source. @@ -1265,9 +1222,6 @@ def _cls_verify( "/v1/sources/{source}/verify".format( source=_util.sanitize_id(source) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1275,13 +1229,7 @@ def _cls_verify( @overload @staticmethod def verify( - source: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Source.VerifyParams" - ] # pyright: ignore[reportGeneralTypeIssues] + source: str, **params: Unpack["Source.VerifyParams"] ) -> "Source": """ Verify a given source. @@ -1289,13 +1237,7 @@ def verify( ... @overload - def verify( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Source.VerifyParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Source": + def verify(self, **params: Unpack["Source.VerifyParams"]) -> "Source": """ Verify a given source. """ @@ -1303,11 +1245,7 @@ def verify( @class_method_variant("_cls_verify") def verify( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Source.VerifyParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Source.VerifyParams"] ) -> "Source": """ Verify a given source. @@ -1319,12 +1257,11 @@ def verify( # pyright: ignore[reportGeneralTypeIssues] "/v1/sources/{source}/verify".format( source=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) - def detach(self, idempotency_key=None, **params) -> "Source": + def detach(self, **params) -> "Source": token = self.id if hasattr(self, "customer") and self.customer: @@ -1333,9 +1270,8 @@ def detach(self, idempotency_key=None, **params) -> "Source": base = Customer.class_url() owner_extn = quote_plus(customer) url = "%s/%s/sources/%s" % (base, owner_extn, extn) - headers = _util.populate_headers(idempotency_key) - self.refresh_from(self.request("delete", url, params, headers)) + self._request_and_refresh("delete", url, params) return cast("Source", self) else: diff --git a/stripe/_source_service.py b/stripe/_source_service.py new file mode 100644 index 000000000..20975352f --- /dev/null +++ b/stripe/_source_service.py @@ -0,0 +1,650 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._account import Account +from stripe._bank_account import BankAccount +from stripe._card import Card +from stripe._request_options import RequestOptions +from stripe._source import Source +from stripe._source_transaction_service import SourceTransactionService +from stripe._stripe_service import StripeService +from typing import Dict, List, Union, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class SourceService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.transactions = SourceTransactionService(self._requestor) + + class CreateParams(TypedDict): + amount: NotRequired["int"] + """ + Amount associated with the source. This is the amount for which the source will be chargeable once ready. Required for `single_use` sources. Not supported for `receiver` type sources, where charge amount may not be specified until funds land. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) associated with the source. This is the currency for which the source will be chargeable once ready. + """ + customer: NotRequired["str"] + """ + The `Customer` to whom the original source is attached to. Must be set when the original source is not a `Source` (e.g., `Card`). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + flow: NotRequired[ + "Literal['code_verification', 'none', 'receiver', 'redirect']" + ] + """ + The authentication `flow` of the source to create. `flow` is one of `redirect`, `receiver`, `code_verification`, `none`. It is generally inferred unless a type supports multiple flows. + """ + mandate: NotRequired["SourceService.CreateParamsMandate"] + """ + Information about a mandate possibility attached to a source object (generally for bank debits) as well as its acceptance status. + """ + metadata: NotRequired["Dict[str, str]"] + original_source: NotRequired["str"] + """ + The source to share. + """ + owner: NotRequired["SourceService.CreateParamsOwner"] + """ + Information about the owner of the payment instrument that may be used or required by particular source types. + """ + receiver: NotRequired["SourceService.CreateParamsReceiver"] + """ + Optional parameters for the receiver flow. Can be set only if the source is a receiver (`flow` is `receiver`). + """ + redirect: NotRequired["SourceService.CreateParamsRedirect"] + """ + Parameters required for the redirect flow. Required if the source is authenticated by a redirect (`flow` is `redirect`). + """ + source_order: NotRequired["SourceService.CreateParamsSourceOrder"] + """ + Information about the items and shipping associated with the source. Required for transactional credit (for example Klarna) sources before you can charge it. + """ + statement_descriptor: NotRequired["str"] + """ + An arbitrary string to be displayed on your customer's statement. As an example, if your website is `RunClub` and the item you're charging for is a race ticket, you may want to specify a `statement_descriptor` of `RunClub 5K race ticket.` While many payment types will display this information, some may not display it at all. + """ + token: NotRequired["str"] + """ + An optional token used to create the source. When passed, token properties will override source parameters. + """ + type: NotRequired["str"] + """ + The `type` of the source to create. Required unless `customer` and `original_source` are specified (see the [Cloning card Sources](https://stripe.com/docs/sources/connect#cloning-card-sources) guide) + """ + usage: NotRequired["Literal['reusable', 'single_use']"] + + class CreateParamsMandate(TypedDict): + acceptance: NotRequired["SourceService.CreateParamsMandateAcceptance"] + """ + The parameters required to notify Stripe of a mandate acceptance or refusal by the customer. + """ + amount: NotRequired["Literal['']|int"] + """ + The amount specified by the mandate. (Leave null for a mandate covering all amounts) + """ + currency: NotRequired["str"] + """ + The currency specified by the mandate. (Must match `currency` of the source) + """ + interval: NotRequired["Literal['one_time', 'scheduled', 'variable']"] + """ + The interval of debits permitted by the mandate. Either `one_time` (just permitting a single debit), `scheduled` (with debits on an agreed schedule or for clearly-defined events), or `variable`(for debits with any frequency) + """ + notification_method: NotRequired[ + "Literal['deprecated_none', 'email', 'manual', 'none', 'stripe_email']" + ] + """ + The method Stripe should use to notify the customer of upcoming debit instructions and/or mandate confirmation as required by the underlying debit network. Either `email` (an email is sent directly to the customer), `manual` (a `source.mandate_notification` event is sent to your webhooks endpoint and you should handle the notification) or `none` (the underlying debit network does not require any notification). + """ + + class CreateParamsMandateAcceptance(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp (in seconds) when the mandate was accepted or refused by the customer. + """ + ip: NotRequired["str"] + """ + The IP address from which the mandate was accepted or refused by the customer. + """ + offline: NotRequired[ + "SourceService.CreateParamsMandateAcceptanceOffline" + ] + """ + The parameters required to store a mandate accepted offline. Should only be set if `mandate[type]` is `offline` + """ + online: NotRequired[ + "SourceService.CreateParamsMandateAcceptanceOnline" + ] + """ + The parameters required to store a mandate accepted online. Should only be set if `mandate[type]` is `online` + """ + status: Literal["accepted", "pending", "refused", "revoked"] + """ + The status of the mandate acceptance. Either `accepted` (the mandate was accepted) or `refused` (the mandate was refused). + """ + type: NotRequired["Literal['offline', 'online']"] + """ + The type of acceptance information included with the mandate. Either `online` or `offline` + """ + user_agent: NotRequired["str"] + """ + The user agent of the browser from which the mandate was accepted or refused by the customer. + """ + + class CreateParamsMandateAcceptanceOffline(TypedDict): + contact_email: str + """ + An email to contact you with if a copy of the mandate is requested, required if `type` is `offline`. + """ + + class CreateParamsMandateAcceptanceOnline(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp (in seconds) when the mandate was accepted or refused by the customer. + """ + ip: NotRequired["str"] + """ + The IP address from which the mandate was accepted or refused by the customer. + """ + user_agent: NotRequired["str"] + """ + The user agent of the browser from which the mandate was accepted or refused by the customer. + """ + + class CreateParamsOwner(TypedDict): + address: NotRequired["SourceService.CreateParamsOwnerAddress"] + """ + Owner's address. + """ + email: NotRequired["str"] + """ + Owner's email address. + """ + name: NotRequired["str"] + """ + Owner's full name. + """ + phone: NotRequired["str"] + """ + Owner's phone number. + """ + + class CreateParamsOwnerAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsReceiver(TypedDict): + refund_attributes_method: NotRequired[ + "Literal['email', 'manual', 'none']" + ] + """ + The method Stripe should use to request information needed to process a refund or mispayment. Either `email` (an email is sent directly to the customer) or `manual` (a `source.refund_attributes_required` event is sent to your webhooks endpoint). Refer to each payment method's documentation to learn which refund attributes may be required. + """ + + class CreateParamsRedirect(TypedDict): + return_url: str + """ + The URL you provide to redirect the customer back to you after they authenticated their payment. It can use your application URI scheme in the context of a mobile application. + """ + + class CreateParamsSourceOrder(TypedDict): + items: NotRequired["List[SourceService.CreateParamsSourceOrderItem]"] + """ + List of items constituting the order. + """ + shipping: NotRequired["SourceService.CreateParamsSourceOrderShipping"] + """ + Shipping address for the order. Required if any of the SKUs are for products that have `shippable` set to true. + """ + + class CreateParamsSourceOrderItem(TypedDict): + amount: NotRequired["int"] + currency: NotRequired["str"] + description: NotRequired["str"] + parent: NotRequired["str"] + """ + The ID of the SKU being ordered. + """ + quantity: NotRequired["int"] + """ + The quantity of this order item. When type is `sku`, this is the number of instances of the SKU to be ordered. + """ + type: NotRequired["Literal['discount', 'shipping', 'sku', 'tax']"] + + class CreateParamsSourceOrderShipping(TypedDict): + address: "SourceService.CreateParamsSourceOrderShippingAddress" + """ + Shipping address. + """ + carrier: NotRequired["str"] + """ + The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. + """ + name: NotRequired["str"] + """ + Recipient name. + """ + phone: NotRequired["str"] + """ + Recipient phone (including extension). + """ + tracking_number: NotRequired["str"] + """ + The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. + """ + + class CreateParamsSourceOrderShippingAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: str + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class DetachParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class RetrieveParams(TypedDict): + client_secret: NotRequired["str"] + """ + The client secret of the source. Required if a publishable key is used to retrieve the source. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + amount: NotRequired["int"] + """ + Amount associated with the source. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + mandate: NotRequired["SourceService.UpdateParamsMandate"] + """ + Information about a mandate possibility attached to a source object (generally for bank debits) as well as its acceptance status. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + owner: NotRequired["SourceService.UpdateParamsOwner"] + """ + Information about the owner of the payment instrument that may be used or required by particular source types. + """ + source_order: NotRequired["SourceService.UpdateParamsSourceOrder"] + """ + Information about the items and shipping associated with the source. Required for transactional credit (for example Klarna) sources before you can charge it. + """ + + class UpdateParamsMandate(TypedDict): + acceptance: NotRequired["SourceService.UpdateParamsMandateAcceptance"] + """ + The parameters required to notify Stripe of a mandate acceptance or refusal by the customer. + """ + amount: NotRequired["Literal['']|int"] + """ + The amount specified by the mandate. (Leave null for a mandate covering all amounts) + """ + currency: NotRequired["str"] + """ + The currency specified by the mandate. (Must match `currency` of the source) + """ + interval: NotRequired["Literal['one_time', 'scheduled', 'variable']"] + """ + The interval of debits permitted by the mandate. Either `one_time` (just permitting a single debit), `scheduled` (with debits on an agreed schedule or for clearly-defined events), or `variable`(for debits with any frequency) + """ + notification_method: NotRequired[ + "Literal['deprecated_none', 'email', 'manual', 'none', 'stripe_email']" + ] + """ + The method Stripe should use to notify the customer of upcoming debit instructions and/or mandate confirmation as required by the underlying debit network. Either `email` (an email is sent directly to the customer), `manual` (a `source.mandate_notification` event is sent to your webhooks endpoint and you should handle the notification) or `none` (the underlying debit network does not require any notification). + """ + + class UpdateParamsMandateAcceptance(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp (in seconds) when the mandate was accepted or refused by the customer. + """ + ip: NotRequired["str"] + """ + The IP address from which the mandate was accepted or refused by the customer. + """ + offline: NotRequired[ + "SourceService.UpdateParamsMandateAcceptanceOffline" + ] + """ + The parameters required to store a mandate accepted offline. Should only be set if `mandate[type]` is `offline` + """ + online: NotRequired[ + "SourceService.UpdateParamsMandateAcceptanceOnline" + ] + """ + The parameters required to store a mandate accepted online. Should only be set if `mandate[type]` is `online` + """ + status: Literal["accepted", "pending", "refused", "revoked"] + """ + The status of the mandate acceptance. Either `accepted` (the mandate was accepted) or `refused` (the mandate was refused). + """ + type: NotRequired["Literal['offline', 'online']"] + """ + The type of acceptance information included with the mandate. Either `online` or `offline` + """ + user_agent: NotRequired["str"] + """ + The user agent of the browser from which the mandate was accepted or refused by the customer. + """ + + class UpdateParamsMandateAcceptanceOffline(TypedDict): + contact_email: str + """ + An email to contact you with if a copy of the mandate is requested, required if `type` is `offline`. + """ + + class UpdateParamsMandateAcceptanceOnline(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp (in seconds) when the mandate was accepted or refused by the customer. + """ + ip: NotRequired["str"] + """ + The IP address from which the mandate was accepted or refused by the customer. + """ + user_agent: NotRequired["str"] + """ + The user agent of the browser from which the mandate was accepted or refused by the customer. + """ + + class UpdateParamsOwner(TypedDict): + address: NotRequired["SourceService.UpdateParamsOwnerAddress"] + """ + Owner's address. + """ + email: NotRequired["str"] + """ + Owner's email address. + """ + name: NotRequired["str"] + """ + Owner's full name. + """ + phone: NotRequired["str"] + """ + Owner's phone number. + """ + + class UpdateParamsOwnerAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsSourceOrder(TypedDict): + items: NotRequired["List[SourceService.UpdateParamsSourceOrderItem]"] + """ + List of items constituting the order. + """ + shipping: NotRequired["SourceService.UpdateParamsSourceOrderShipping"] + """ + Shipping address for the order. Required if any of the SKUs are for products that have `shippable` set to true. + """ + + class UpdateParamsSourceOrderItem(TypedDict): + amount: NotRequired["int"] + currency: NotRequired["str"] + description: NotRequired["str"] + parent: NotRequired["str"] + """ + The ID of the SKU being ordered. + """ + quantity: NotRequired["int"] + """ + The quantity of this order item. When type is `sku`, this is the number of instances of the SKU to be ordered. + """ + type: NotRequired["Literal['discount', 'shipping', 'sku', 'tax']"] + + class UpdateParamsSourceOrderShipping(TypedDict): + address: "SourceService.UpdateParamsSourceOrderShippingAddress" + """ + Shipping address. + """ + carrier: NotRequired["str"] + """ + The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. + """ + name: NotRequired["str"] + """ + Recipient name. + """ + phone: NotRequired["str"] + """ + Recipient phone (including extension). + """ + tracking_number: NotRequired["str"] + """ + The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. + """ + + class UpdateParamsSourceOrderShippingAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: str + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class VerifyParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + values: List[str] + """ + The values needed to verify the source. + """ + + def detach( + self, + customer: str, + id: str, + params: "SourceService.DetachParams" = {}, + options: RequestOptions = {}, + ) -> Union[Account, BankAccount, Card, Source]: + """ + Delete a specified source for a given customer. + """ + return cast( + Union[Account, BankAccount, Card, Source], + self._requestor.request( + "delete", + "/v1/customers/{customer}/sources/{id}".format( + customer=_util.sanitize_id(customer), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + source: str, + params: "SourceService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Source: + """ + Retrieves an existing source object. Supply the unique source ID from a source creation request and Stripe will return the corresponding up-to-date source object information. + """ + return cast( + Source, + self._requestor.request( + "get", + "/v1/sources/{source}".format( + source=_util.sanitize_id(source) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + source: str, + params: "SourceService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Source: + """ + Updates the specified source by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + + This request accepts the metadata and owner as arguments. It is also possible to update type specific information for selected payment methods. Please refer to our [payment method guides](https://stripe.com/docs/sources) for more detail. + """ + return cast( + Source, + self._requestor.request( + "post", + "/v1/sources/{source}".format( + source=_util.sanitize_id(source) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "SourceService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Source: + """ + Creates a new source object. + """ + return cast( + Source, + self._requestor.request( + "post", + "/v1/sources", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def verify( + self, + source: str, + params: "SourceService.VerifyParams", + options: RequestOptions = {}, + ) -> Source: + """ + Verify a given source. + """ + return cast( + Source, + self._requestor.request( + "post", + "/v1/sources/{source}/verify".format( + source=_util.sanitize_id(source), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_source_transaction_service.py b/stripe/_source_transaction_service.py new file mode 100644 index 000000000..1d7feb0e9 --- /dev/null +++ b/stripe/_source_transaction_service.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._source_transaction import SourceTransaction +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class SourceTransactionService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + def list( + self, + source: str, + params: "SourceTransactionService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[SourceTransaction]: + """ + List source transactions for a given source. + """ + return cast( + ListObject[SourceTransaction], + self._requestor.request( + "get", + "/v1/sources/{source}/source_transactions".format( + source=_util.sanitize_id(source), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_stripe_client.py b/stripe/_stripe_client.py new file mode 100644 index 000000000..7def5bcd8 --- /dev/null +++ b/stripe/_stripe_client.py @@ -0,0 +1,253 @@ +# -*- coding: utf-8 -*- + +import json +from collections import OrderedDict + +from stripe import ( + DEFAULT_API_BASE, + DEFAULT_CONNECT_API_BASE, + DEFAULT_UPLOAD_API_BASE, +) + +from stripe._error import AuthenticationError +from stripe._api_requestor import _APIRequestor +from stripe._requestor_options import RequestorOptions, BaseAddresses +from stripe._client_options import _ClientOptions +from stripe._http_client import HTTPClient, new_default_http_client +from stripe._api_version import _ApiVersion +from stripe._webhook import Webhook, WebhookSignature +from stripe._event import Event + +from typing import Optional, Union, cast + +# Non-generated services +from stripe._oauth_service import OAuthService + +# services: The beginning of the section generated from our OpenAPI spec +from stripe._account_service import AccountService +from stripe._account_link_service import AccountLinkService +from stripe._account_session_service import AccountSessionService +from stripe._apple_pay_domain_service import ApplePayDomainService +from stripe._application_fee_service import ApplicationFeeService +from stripe._apps_service import AppsService +from stripe._balance_service import BalanceService +from stripe._balance_transaction_service import BalanceTransactionService +from stripe._billing_portal_service import BillingPortalService +from stripe._charge_service import ChargeService +from stripe._checkout_service import CheckoutService +from stripe._climate_service import ClimateService +from stripe._country_spec_service import CountrySpecService +from stripe._coupon_service import CouponService +from stripe._credit_note_service import CreditNoteService +from stripe._customer_service import CustomerService +from stripe._test_helpers_service import TestHelpersService +from stripe._customer_session_service import CustomerSessionService +from stripe._dispute_service import DisputeService +from stripe._ephemeral_key_service import EphemeralKeyService +from stripe._event_service import EventService +from stripe._exchange_rate_service import ExchangeRateService +from stripe._file_service import FileService +from stripe._file_link_service import FileLinkService +from stripe._financial_connections_service import FinancialConnectionsService +from stripe._identity_service import IdentityService +from stripe._invoice_service import InvoiceService +from stripe._invoice_item_service import InvoiceItemService +from stripe._issuing_service import IssuingService +from stripe._mandate_service import MandateService +from stripe._payment_intent_service import PaymentIntentService +from stripe._payment_link_service import PaymentLinkService +from stripe._payment_method_service import PaymentMethodService +from stripe._payment_method_configuration_service import ( + PaymentMethodConfigurationService, +) +from stripe._payment_method_domain_service import PaymentMethodDomainService +from stripe._payout_service import PayoutService +from stripe._plan_service import PlanService +from stripe._price_service import PriceService +from stripe._product_service import ProductService +from stripe._promotion_code_service import PromotionCodeService +from stripe._quote_service import QuoteService +from stripe._radar_service import RadarService +from stripe._refund_service import RefundService +from stripe._reporting_service import ReportingService +from stripe._review_service import ReviewService +from stripe._sigma_service import SigmaService +from stripe._setup_attempt_service import SetupAttemptService +from stripe._setup_intent_service import SetupIntentService +from stripe._shipping_rate_service import ShippingRateService +from stripe._source_service import SourceService +from stripe._subscription_service import SubscriptionService +from stripe._subscription_item_service import SubscriptionItemService +from stripe._subscription_schedule_service import SubscriptionScheduleService +from stripe._tax_service import TaxService +from stripe._tax_code_service import TaxCodeService +from stripe._tax_rate_service import TaxRateService +from stripe._terminal_service import TerminalService +from stripe._token_service import TokenService +from stripe._topup_service import TopupService +from stripe._transfer_service import TransferService +from stripe._treasury_service import TreasuryService +from stripe._webhook_endpoint_service import WebhookEndpointService + +# services: The end of the section generated from our OpenAPI spec + + +class StripeClient(object): + def __init__( + self, + api_key: str, + *, + stripe_account: Optional[str] = None, + stripe_version: Optional[str] = None, + base_addresses: BaseAddresses = {}, + client_id: Optional[str] = None, + verify_ssl_certs: bool = True, + proxy: Optional[str] = None, + max_network_retries: Optional[int] = None, + http_client: Optional[HTTPClient] = None, + ): + # The types forbid this, but let's give users without types a friendly error. + if api_key is None: # pyright: ignore[reportUnnecessaryComparison] + raise AuthenticationError( + "No API key provided. (HINT: set your API key using " + '"client = stripe.StripeClient()"). You can ' + "generate API keys from the Stripe web interface. " + "See https://stripe.com/api for details, or email " + "support@stripe.com if you have any questions." + ) + + if http_client and (proxy or verify_ssl_certs is not True): + raise ValueError( + "You cannot specify `proxy` or `verify_ssl_certs` when passing " + "in a custom `http_client`. Please set these values on your " + "custom `http_client` instead." + ) + + # Default to stripe.DEFAULT_API_BASE, stripe.DEFAULT_CONNECT_API_BASE, + # and stripe.DEFAULT_UPLOAD_API_BASE if not set in base_addresses. + base_addresses = { + "api": DEFAULT_API_BASE, + "connect": DEFAULT_CONNECT_API_BASE, + "files": DEFAULT_UPLOAD_API_BASE, + **base_addresses, + } + + requestor_options = RequestorOptions( + api_key=api_key, + stripe_account=stripe_account, + stripe_version=stripe_version or _ApiVersion.CURRENT, + base_addresses=base_addresses, + max_network_retries=max_network_retries, + ) + + if http_client is None: + http_client = new_default_http_client( + proxy=proxy, verify_ssl_certs=verify_ssl_certs + ) + + self._requestor = _APIRequestor( + options=requestor_options, + client=http_client, + ) + + self._options = _ClientOptions( + client_id=client_id, + proxy=proxy, + verify_ssl_certs=verify_ssl_certs, + ) + + self.oauth = OAuthService(self._requestor, self._options) + + # top-level services: The beginning of the section generated from our OpenAPI spec + self.accounts = AccountService(self._requestor) + self.account_links = AccountLinkService(self._requestor) + self.account_sessions = AccountSessionService(self._requestor) + self.apple_pay_domains = ApplePayDomainService(self._requestor) + self.application_fees = ApplicationFeeService(self._requestor) + self.apps = AppsService(self._requestor) + self.balance = BalanceService(self._requestor) + self.balance_transactions = BalanceTransactionService(self._requestor) + self.billing_portal = BillingPortalService(self._requestor) + self.charges = ChargeService(self._requestor) + self.checkout = CheckoutService(self._requestor) + self.climate = ClimateService(self._requestor) + self.country_specs = CountrySpecService(self._requestor) + self.coupons = CouponService(self._requestor) + self.credit_notes = CreditNoteService(self._requestor) + self.customers = CustomerService(self._requestor) + self.test_helpers = TestHelpersService(self._requestor) + self.customer_sessions = CustomerSessionService(self._requestor) + self.disputes = DisputeService(self._requestor) + self.ephemeral_keys = EphemeralKeyService(self._requestor) + self.events = EventService(self._requestor) + self.exchange_rates = ExchangeRateService(self._requestor) + self.files = FileService(self._requestor) + self.file_links = FileLinkService(self._requestor) + self.financial_connections = FinancialConnectionsService( + self._requestor + ) + self.identity = IdentityService(self._requestor) + self.invoices = InvoiceService(self._requestor) + self.invoice_items = InvoiceItemService(self._requestor) + self.issuing = IssuingService(self._requestor) + self.mandates = MandateService(self._requestor) + self.payment_intents = PaymentIntentService(self._requestor) + self.payment_links = PaymentLinkService(self._requestor) + self.payment_methods = PaymentMethodService(self._requestor) + self.payment_method_configurations = PaymentMethodConfigurationService( + self._requestor, + ) + self.payment_method_domains = PaymentMethodDomainService( + self._requestor + ) + self.payouts = PayoutService(self._requestor) + self.plans = PlanService(self._requestor) + self.prices = PriceService(self._requestor) + self.products = ProductService(self._requestor) + self.promotion_codes = PromotionCodeService(self._requestor) + self.quotes = QuoteService(self._requestor) + self.radar = RadarService(self._requestor) + self.refunds = RefundService(self._requestor) + self.reporting = ReportingService(self._requestor) + self.reviews = ReviewService(self._requestor) + self.sigma = SigmaService(self._requestor) + self.setup_attempts = SetupAttemptService(self._requestor) + self.setup_intents = SetupIntentService(self._requestor) + self.shipping_rates = ShippingRateService(self._requestor) + self.sources = SourceService(self._requestor) + self.subscriptions = SubscriptionService(self._requestor) + self.subscription_items = SubscriptionItemService(self._requestor) + self.subscription_schedules = SubscriptionScheduleService( + self._requestor + ) + self.tax = TaxService(self._requestor) + self.tax_codes = TaxCodeService(self._requestor) + self.tax_rates = TaxRateService(self._requestor) + self.terminal = TerminalService(self._requestor) + self.tokens = TokenService(self._requestor) + self.topups = TopupService(self._requestor) + self.transfers = TransferService(self._requestor) + self.treasury = TreasuryService(self._requestor) + self.webhook_endpoints = WebhookEndpointService(self._requestor) + # top-level services: The end of the section generated from our OpenAPI spec + + def construct_event( + self, + payload: Union[bytes, str], + sig_header: str, + secret: str, + tolerance: int = Webhook.DEFAULT_TOLERANCE, + ) -> Event: + if hasattr(payload, "decode"): + payload = cast(bytes, payload).decode("utf-8") + + WebhookSignature.verify_header(payload, sig_header, secret, tolerance) + + data = json.loads(payload, object_pairs_hook=OrderedDict) + event = Event._construct_from( + values=data, + requestor=self._requestor, + api_mode="V1", + ) + + return event diff --git a/stripe/_stripe_object.py b/stripe/_stripe_object.py index 4382a15b3..74b07a3cf 100644 --- a/stripe/_stripe_object.py +++ b/stripe/_stripe_object.py @@ -19,11 +19,16 @@ # Used to break circular imports import stripe # noqa: IMP101 -from stripe._encode import _encode_datetime # pyright: ignore from stripe import _util from stripe._stripe_response import StripeResponse, StripeStreamResponse -import warnings +from stripe._encode import _encode_datetime # pyright: ignore +from stripe._request_options import extract_options_from_dict +from stripe._api_mode import ApiMode +from stripe._base_address import BaseAddress + +if TYPE_CHECKING: + from stripe import _APIRequestor # pyright: ignore[reportPrivateUsage] @overload @@ -79,18 +84,8 @@ def default(self, o: Any) -> Any: return _encode_datetime(o) return super(StripeObject._ReprJSONEncoder, self).default(o) - @_util.deprecated( - "For internal stripe-python use only. The public interface will be removed in a future version" - ) - class ReprJSONEncoder(_ReprJSONEncoder): - pass - - _retrieve_params: Dict[str, Any] - _previous: Optional[Dict[str, Any]] - - api_key: Optional[str] - stripe_version: Optional[str] - stripe_account: Optional[str] + _retrieve_params: Mapping[str, Any] + _previous: Optional[Mapping[str, Any]] def __init__( self, @@ -99,6 +94,8 @@ def __init__( stripe_version: Optional[str] = None, stripe_account: Optional[str] = None, last_response: Optional[StripeResponse] = None, + *, + _requestor: Optional["_APIRequestor"] = None, # TODO: is a more specific type possible here? **params: Any ): @@ -111,13 +108,31 @@ def __init__( self._retrieve_params = params self._previous = None - object.__setattr__(self, "api_key", api_key) - object.__setattr__(self, "stripe_version", stripe_version) - object.__setattr__(self, "stripe_account", stripe_account) + self._requestor = ( + stripe._APIRequestor._global_with_options( # pyright: ignore[reportPrivateUsage] + api_key=api_key, + stripe_version=stripe_version, + stripe_account=stripe_account, + ) + if _requestor is None + else _requestor + ) if id: self["id"] = id + @property + def api_key(self): + return self._requestor.api_key + + @property + def stripe_account(self): + return self._requestor.stripe_account + + @property + def stripe_version(self): + return self._requestor.stripe_version + @property def last_response(self) -> Optional[StripeResponse]: return self._last_response @@ -135,6 +150,10 @@ def update( # pyright: ignore if not TYPE_CHECKING: def __setattr__(self, k, v): + if k in {"api_key", "stripe_account", "stripe_version"}: + self._requestor = self._requestor._replace_options({k: v}) + return None + if k[0] == "_" or k in self.__dict__: return super(StripeObject, self).__setattr__(k, v) @@ -229,20 +248,39 @@ def construct_from( stripe_version: Optional[str] = None, stripe_account: Optional[str] = None, last_response: Optional[StripeResponse] = None, + *, + api_mode: ApiMode = "V1", + ) -> Self: + return cls._construct_from( + values=values, + requestor=stripe._APIRequestor._global_with_options( # pyright: ignore[reportPrivateUsage] + api_key=key, + stripe_version=stripe_version, + stripe_account=stripe_account, + ), + api_mode=api_mode, + last_response=last_response, + ) + + @classmethod + def _construct_from( + cls, + *, + values: Dict[str, Any], + last_response: Optional[StripeResponse] = None, + requestor: "_APIRequestor", + api_mode: ApiMode, ) -> Self: instance = cls( values.get("id"), - api_key=key, - stripe_version=stripe_version, - stripe_account=stripe_account, last_response=last_response, + _requestor=requestor, ) - instance.refresh_from( - values, - api_key=key, - stripe_version=stripe_version, - stripe_account=stripe_account, + instance._refresh_from( + values=values, last_response=last_response, + requestor=requestor, + api_mode=api_mode, ) return instance @@ -254,14 +292,33 @@ def refresh_from( stripe_version: Optional[str] = None, stripe_account: Optional[str] = None, last_response: Optional[StripeResponse] = None, + *, + api_mode: ApiMode = "V1", ) -> None: - self.api_key = api_key or getattr(values, "api_key", None) - self.stripe_version = stripe_version or getattr( - values, "stripe_version", None - ) - self.stripe_account = stripe_account or getattr( - values, "stripe_account", None + self._refresh_from( + values=values, + partial=partial, + last_response=last_response, + requestor=self._requestor._replace_options( # pyright: ignore[reportPrivateUsage] + { + "api_key": api_key, + "stripe_version": stripe_version, + "stripe_account": stripe_account, + } + ), + api_mode=api_mode, ) + + def _refresh_from( + self, + *, + values: Dict[str, Any], + partial: Optional[bool] = False, + last_response: Optional[StripeResponse] = None, + requestor: Optional["_APIRequestor"] = None, + api_mode: ApiMode, + ) -> None: + self._requestor = requestor or self._requestor self._last_response = last_response or getattr( values, "_last_response", None ) @@ -288,13 +345,12 @@ def refresh_from( if v is None else cast( StripeObject, - _util.convert_to_stripe_object( - v, - api_key, - stripe_version, - stripe_account, - None, - inner_class, + _util._convert_to_stripe_object( # pyright: ignore[reportPrivateUsage] + resp=v, + params=None, + klass_=inner_class, + requestor=self._requestor, + api_mode=api_mode, ), ) for k, v in v.items() @@ -302,35 +358,37 @@ def refresh_from( else: obj = cast( Union[StripeObject, List[StripeObject]], - _util.convert_to_stripe_object( - v, - api_key, - stripe_version, - stripe_account, - None, - inner_class, + _util._convert_to_stripe_object( # pyright: ignore[reportPrivateUsage] + resp=v, + params=None, + klass_=inner_class, + requestor=self._requestor, + api_mode=api_mode, ), ) super(StripeObject, self).__setitem__(k, obj) self._previous = values - @classmethod @_util.deprecated( "This will be removed in a future version of stripe-python." ) - def api_base(cls) -> Optional[str]: - return None - def request( self, method: Literal["get", "post", "delete"], url: str, params: Optional[Dict[str, Any]] = None, - headers: Optional[Dict[str, str]] = None, + *, + base_address: BaseAddress = "api", + api_mode: ApiMode = "V1", ) -> "StripeObject": return StripeObject._request( - self, method, url, headers=headers, params=params + self, + method, + url, + params=params, + base_address=base_address, + api_mode=api_mode, ) # The `method_` and `url_` arguments are suffixed with an underscore to @@ -339,77 +397,48 @@ def _request( self, method_: Literal["get", "post", "delete"], url_: str, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - headers: Optional[Dict[str, str]] = None, params: Optional[Mapping[str, Any]] = None, _usage: Optional[List[str]] = None, + *, + base_address: BaseAddress, + api_mode: ApiMode, ) -> "StripeObject": - params = None if params is None else dict(params) - api_key = _util.read_special_variable(params, "api_key", api_key) - idempotency_key = _util.read_special_variable( - params, "idempotency_key", idempotency_key - ) - stripe_version = _util.read_special_variable( - params, "stripe_version", stripe_version - ) - stripe_account = _util.read_special_variable( - params, "stripe_account", stripe_account - ) - headers = _util.read_special_variable(params, "headers", headers) - - stripe_account = stripe_account or self.stripe_account - stripe_version = stripe_version or self.stripe_version - api_key = api_key or self.api_key - params = params or self._retrieve_params - api_base = None - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - api_base = self.api_base() # pyright: ignore[reportDeprecated] - - requestor = stripe.APIRequestor( - key=api_key, - api_base=api_base, - api_version=stripe_version, - account=stripe_account, - ) - - if idempotency_key is not None: - headers = {} if headers is None else headers.copy() - headers.update(_util.populate_headers(idempotency_key)) + if params is None: + params = self._retrieve_params - response, api_key = requestor.request( - method_, url_, params, headers, _usage=_usage - ) + request_options, request_params = extract_options_from_dict(params) - return _util.convert_to_stripe_object( - response, api_key, stripe_version, stripe_account, params + return self._requestor.request( + method_, + url_, + params=request_params, + options=request_options, + base_address=base_address, + api_mode=api_mode, + _usage=_usage, ) - def request_stream( + def _request_stream( self, method: str, url: str, params: Optional[Mapping[str, Any]] = None, - headers: Optional[Mapping[str, str]] = None, + *, + base_address: BaseAddress = "api", + api_mode: ApiMode = "V1", ) -> StripeStreamResponse: if params is None: params = self._retrieve_params - api_base = None - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - api_base = self.api_base() # pyright: ignore[reportDeprecated] - requestor = stripe.APIRequestor( - key=self.api_key, - api_base=api_base, - api_version=self.stripe_version, - account=self.stripe_account, - ) - response, _ = requestor.request_stream(method, url, params, headers) - return response + request_options, request_params = extract_options_from_dict(params) + return self._requestor.request_stream( + method, + url, + params=request_params, + options=request_options, + base_address=base_address, + api_mode=api_mode, + ) def __repr__(self) -> str: ident_parts = [type(self).__name__] @@ -473,7 +502,9 @@ def to_dict_recursive(self) -> Dict[str, Any]: def stripe_id(self) -> Optional[str]: return getattr(self, "id") - def serialize(self, previous: Optional[Dict[str, Any]]) -> Dict[str, Any]: + def serialize( + self, previous: Optional[Mapping[str, Any]] + ) -> Dict[str, Any]: params: Dict[str, Any] = {} unsaved_keys = self._unsaved_values or set() previous = previous or self._previous or {} diff --git a/stripe/_stripe_service.py b/stripe/_stripe_service.py new file mode 100644 index 000000000..e069070a7 --- /dev/null +++ b/stripe/_stripe_service.py @@ -0,0 +1,8 @@ +from stripe._api_requestor import _APIRequestor + + +class StripeService(object): + _requestor: _APIRequestor + + def __init__(self, requestor): + self._requestor = requestor diff --git a/stripe/_subscription.py b/stripe/_subscription.py index f304ba22d..5ca8cd0ed 100644 --- a/stripe/_subscription.py +++ b/stripe/_subscription.py @@ -1970,12 +1970,7 @@ class SearchParams(RequestOptions): def _cls_cancel( cls, subscription_exposed_id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Subscription.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Subscription.CancelParams"] ) -> "Subscription": """ Cancels a customer's subscription immediately. The customer will not be charged again for the subscription. @@ -1993,9 +1988,6 @@ def _cls_cancel( subscription_exposed_id ) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2004,12 +1996,7 @@ def _cls_cancel( @staticmethod def cancel( subscription_exposed_id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Subscription.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Subscription.CancelParams"] ) -> "Subscription": """ Cancels a customer's subscription immediately. The customer will not be charged again for the subscription. @@ -2022,11 +2009,7 @@ def cancel( @overload def cancel( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Subscription.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Subscription.CancelParams"] ) -> "Subscription": """ Cancels a customer's subscription immediately. The customer will not be charged again for the subscription. @@ -2039,11 +2022,7 @@ def cancel( @class_method_variant("_cls_cancel") def cancel( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Subscription.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Subscription.CancelParams"] ) -> "Subscription": """ Cancels a customer's subscription immediately. The customer will not be charged again for the subscription. @@ -2059,21 +2038,13 @@ def cancel( # pyright: ignore[reportGeneralTypeIssues] "/v1/subscriptions/{subscription_exposed_id}".format( subscription_exposed_id=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Subscription.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Subscription.CreateParams"] ) -> "Subscription": """ Creates a new subscription on an existing customer. Each customer can have up to 500 active or scheduled subscriptions. @@ -2089,10 +2060,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -2101,12 +2068,7 @@ def create( def _cls_delete_discount( cls, subscription_exposed_id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Subscription.DeleteDiscountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Subscription.DeleteDiscountParams"] ) -> "Discount": """ Removes the currently applied discount on a subscription. @@ -2120,9 +2082,6 @@ def _cls_delete_discount( subscription_exposed_id ) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2131,12 +2090,7 @@ def _cls_delete_discount( @staticmethod def delete_discount( subscription_exposed_id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Subscription.DeleteDiscountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Subscription.DeleteDiscountParams"] ) -> "Discount": """ Removes the currently applied discount on a subscription. @@ -2145,11 +2099,7 @@ def delete_discount( @overload def delete_discount( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Subscription.DeleteDiscountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Subscription.DeleteDiscountParams"] ) -> "Discount": """ Removes the currently applied discount on a subscription. @@ -2158,11 +2108,7 @@ def delete_discount( @class_method_variant("_cls_delete_discount") def delete_discount( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Subscription.DeleteDiscountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Subscription.DeleteDiscountParams"] ) -> "Discount": """ Removes the currently applied discount on a subscription. @@ -2174,20 +2120,13 @@ def delete_discount( # pyright: ignore[reportGeneralTypeIssues] "/v1/subscriptions/{subscription_exposed_id}/discount".format( subscription_exposed_id=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Subscription.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Subscription.ListParams"] ) -> ListObject["Subscription"]: """ By default, returns a list of subscriptions that have not been canceled. In order to list canceled subscriptions, specify status=canceled. @@ -2195,9 +2134,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -2244,14 +2180,7 @@ def modify( @classmethod def _cls_resume( - cls, - subscription: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Subscription.ResumeParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, subscription: str, **params: Unpack["Subscription.ResumeParams"] ) -> "Subscription": """ Initiates resumption of a paused subscription, optionally resetting the billing cycle anchor and creating prorations. If a resumption invoice is generated, it must be paid or marked uncollectible before the subscription will be unpaused. If payment succeeds the subscription will become active, and if payment fails the subscription will be past_due. The resumption invoice will void automatically if not paid by the expiration date. @@ -2263,9 +2192,6 @@ def _cls_resume( "/v1/subscriptions/{subscription}/resume".format( subscription=_util.sanitize_id(subscription) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -2273,13 +2199,7 @@ def _cls_resume( @overload @staticmethod def resume( - subscription: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Subscription.ResumeParams" - ] # pyright: ignore[reportGeneralTypeIssues] + subscription: str, **params: Unpack["Subscription.ResumeParams"] ) -> "Subscription": """ Initiates resumption of a paused subscription, optionally resetting the billing cycle anchor and creating prorations. If a resumption invoice is generated, it must be paid or marked uncollectible before the subscription will be unpaused. If payment succeeds the subscription will become active, and if payment fails the subscription will be past_due. The resumption invoice will void automatically if not paid by the expiration date. @@ -2288,11 +2208,7 @@ def resume( @overload def resume( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Subscription.ResumeParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Subscription.ResumeParams"] ) -> "Subscription": """ Initiates resumption of a paused subscription, optionally resetting the billing cycle anchor and creating prorations. If a resumption invoice is generated, it must be paid or marked uncollectible before the subscription will be unpaused. If payment succeeds the subscription will become active, and if payment fails the subscription will be past_due. The resumption invoice will void automatically if not paid by the expiration date. @@ -2301,11 +2217,7 @@ def resume( @class_method_variant("_cls_resume") def resume( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Subscription.ResumeParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Subscription.ResumeParams"] ) -> "Subscription": """ Initiates resumption of a paused subscription, optionally resetting the billing cycle anchor and creating prorations. If a resumption invoice is generated, it must be paid or marked uncollectible before the subscription will be unpaused. If payment succeeds the subscription will become active, and if payment fails the subscription will be past_due. The resumption invoice will void automatically if not paid by the expiration date. @@ -2317,7 +2229,6 @@ def resume( # pyright: ignore[reportGeneralTypeIssues] "/v1/subscriptions/{subscription}/resume".format( subscription=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/_subscription_item.py b/stripe/_subscription_item.py index e35854bd2..e5ed7b97b 100644 --- a/stripe/_subscription_item.py +++ b/stripe/_subscription_item.py @@ -400,14 +400,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SubscriptionItem.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["SubscriptionItem.CreateParams"] ) -> "SubscriptionItem": """ Adds a new item to an existing subscription. No existing items will be changed or replaced. @@ -417,10 +410,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -472,13 +461,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SubscriptionItem.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["SubscriptionItem.ListParams"] ) -> ListObject["SubscriptionItem"]: """ Returns a list of your subscription items for a given subscription. @@ -486,9 +469,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -528,12 +508,7 @@ def retrieve( def create_usage_record( cls, subscription_item: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SubscriptionItem.CreateUsageRecordParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["SubscriptionItem.CreateUsageRecordParams"] ) -> "UsageRecord": """ Creates a usage record for a specified subscription item and date, and fills it with a quantity. @@ -551,9 +526,6 @@ def create_usage_record( "/v1/subscription_items/{subscription_item}/usage_records".format( subscription_item=_util.sanitize_id(subscription_item) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -562,12 +534,7 @@ def create_usage_record( def list_usage_record_summaries( cls, subscription_item: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SubscriptionItem.ListUsageRecordSummariesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["SubscriptionItem.ListUsageRecordSummariesParams"] ) -> ListObject["UsageRecordSummary"]: """ For the specified subscription item, returns a list of summary objects. Each object in the list provides usage information that's been summarized from multiple usage records and over a subscription billing period (e.g., 15 usage records in the month of September). @@ -581,9 +548,6 @@ def list_usage_record_summaries( "/v1/subscription_items/{subscription_item}/usage_record_summaries".format( subscription_item=_util.sanitize_id(subscription_item) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) diff --git a/stripe/_subscription_item_service.py b/stripe/_subscription_item_service.py new file mode 100644 index 000000000..658ef686b --- /dev/null +++ b/stripe/_subscription_item_service.py @@ -0,0 +1,397 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe._subscription_item import SubscriptionItem +from stripe._subscription_item_usage_record_service import ( + SubscriptionItemUsageRecordService, +) +from stripe._subscription_item_usage_record_summary_service import ( + SubscriptionItemUsageRecordSummaryService, +) +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class SubscriptionItemService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.usage_records = SubscriptionItemUsageRecordService( + self._requestor + ) + self.usage_record_summaries = ( + SubscriptionItemUsageRecordSummaryService( + self._requestor, + ) + ) + + class CreateParams(TypedDict): + billing_thresholds: NotRequired[ + "Literal['']|SubscriptionItemService.CreateParamsBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + payment_behavior: NotRequired[ + "Literal['allow_incomplete', 'default_incomplete', 'error_if_incomplete', 'pending_if_incomplete']" + ] + """ + Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. For example, SCA regulation may require 3DS authentication to complete payment. See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. This is the default behavior. + + Use `default_incomplete` to transition the subscription to `status=past_due` when payment is required and await explicit confirmation of the invoice's payment intent. This allows simpler management of scenarios where additional user actions are needed to pay a subscription's invoice. Such as failed payments, [SCA regulation](https://stripe.com/docs/billing/migration/strong-customer-authentication), or collecting a mandate for a bank debit payment method. + + Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). + + Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's invoice cannot be paid. For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not update the subscription and returns an error instead. This was the default behavior for API versions prior to 2019-03-14. See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + """ + plan: NotRequired["str"] + """ + The identifier of the plan to add to the subscription. + """ + price: NotRequired["str"] + """ + The ID of the price object. + """ + price_data: NotRequired[ + "SubscriptionItemService.CreateParamsPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + """ + proration_date: NotRequired["int"] + """ + If set, the proration will be calculated as though the subscription was updated at the given time. This can be used to apply the same proration that was previewed with the [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. + """ + quantity: NotRequired["int"] + """ + The quantity you'd like to apply to the subscription item you're creating. + """ + subscription: str + """ + The identifier of the subscription to modify. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + """ + + class CreateParamsBillingThresholds(TypedDict): + usage_gte: int + """ + Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + """ + + class CreateParamsPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + recurring: "SubscriptionItemService.CreateParamsPriceDataRecurring" + """ + The recurring components of a price such as `interval` and `interval_count`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class CreateParamsPriceDataRecurring(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + + class DeleteParams(TypedDict): + clear_usage: NotRequired["bool"] + """ + Delete all usage for the given subscription item. Allowed only when the current plan's `usage_type` is `metered`. + """ + proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + """ + proration_date: NotRequired["int"] + """ + If set, the proration will be calculated as though the subscription was updated at the given time. This can be used to apply the same proration that was previewed with the [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. + """ + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + subscription: str + """ + The ID of the subscription whose items will be retrieved. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + billing_thresholds: NotRequired[ + "Literal['']|SubscriptionItemService.UpdateParamsBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + off_session: NotRequired["bool"] + """ + Indicates if a customer is on or off-session while an invoice payment is attempted. + """ + payment_behavior: NotRequired[ + "Literal['allow_incomplete', 'default_incomplete', 'error_if_incomplete', 'pending_if_incomplete']" + ] + """ + Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. For example, SCA regulation may require 3DS authentication to complete payment. See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. This is the default behavior. + + Use `default_incomplete` to transition the subscription to `status=past_due` when payment is required and await explicit confirmation of the invoice's payment intent. This allows simpler management of scenarios where additional user actions are needed to pay a subscription's invoice. Such as failed payments, [SCA regulation](https://stripe.com/docs/billing/migration/strong-customer-authentication), or collecting a mandate for a bank debit payment method. + + Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). + + Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's invoice cannot be paid. For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not update the subscription and returns an error instead. This was the default behavior for API versions prior to 2019-03-14. See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + """ + plan: NotRequired["str"] + """ + The identifier of the new plan for this subscription item. + """ + price: NotRequired["str"] + """ + The ID of the price object. When changing a subscription item's price, `quantity` is set to 1 unless a `quantity` parameter is provided. + """ + price_data: NotRequired[ + "SubscriptionItemService.UpdateParamsPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + """ + proration_date: NotRequired["int"] + """ + If set, the proration will be calculated as though the subscription was updated at the given time. This can be used to apply the same proration that was previewed with the [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. + """ + quantity: NotRequired["int"] + """ + The quantity you'd like to apply to the subscription item you're creating. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + """ + + class UpdateParamsBillingThresholds(TypedDict): + usage_gte: int + """ + Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + """ + + class UpdateParamsPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + recurring: "SubscriptionItemService.UpdateParamsPriceDataRecurring" + """ + The recurring components of a price such as `interval` and `interval_count`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class UpdateParamsPriceDataRecurring(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + + def delete( + self, + item: str, + params: "SubscriptionItemService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> SubscriptionItem: + """ + Deletes an item from the subscription. Removing a subscription item from a subscription will not cancel the subscription. + """ + return cast( + SubscriptionItem, + self._requestor.request( + "delete", + "/v1/subscription_items/{item}".format( + item=_util.sanitize_id(item), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + item: str, + params: "SubscriptionItemService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> SubscriptionItem: + """ + Retrieves the subscription item with the given ID. + """ + return cast( + SubscriptionItem, + self._requestor.request( + "get", + "/v1/subscription_items/{item}".format( + item=_util.sanitize_id(item), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + item: str, + params: "SubscriptionItemService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> SubscriptionItem: + """ + Updates the plan or quantity of an item on a current subscription. + """ + return cast( + SubscriptionItem, + self._requestor.request( + "post", + "/v1/subscription_items/{item}".format( + item=_util.sanitize_id(item), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "SubscriptionItemService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[SubscriptionItem]: + """ + Returns a list of your subscription items for a given subscription. + """ + return cast( + ListObject[SubscriptionItem], + self._requestor.request( + "get", + "/v1/subscription_items", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "SubscriptionItemService.CreateParams", + options: RequestOptions = {}, + ) -> SubscriptionItem: + """ + Adds a new item to an existing subscription. No existing items will be changed or replaced. + """ + return cast( + SubscriptionItem, + self._requestor.request( + "post", + "/v1/subscription_items", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_subscription_item_usage_record_service.py b/stripe/_subscription_item_usage_record_service.py new file mode 100644 index 000000000..3be9526a7 --- /dev/null +++ b/stripe/_subscription_item_usage_record_service.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe._usage_record import UsageRecord +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class SubscriptionItemUsageRecordService(StripeService): + class CreateParams(TypedDict): + action: NotRequired["Literal['increment', 'set']"] + """ + Valid values are `increment` (default) or `set`. When using `increment` the specified `quantity` will be added to the usage at the specified timestamp. The `set` action will overwrite the usage quantity at that timestamp. If the subscription has [billing thresholds](https://stripe.com/docs/api/subscriptions/object#subscription_object-billing_thresholds), `increment` is the only allowed value. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + quantity: int + """ + The usage quantity for the specified timestamp. + """ + timestamp: NotRequired["Literal['now']|int"] + """ + The timestamp for the usage event. This timestamp must be within the current billing period of the subscription of the provided `subscription_item`, and must not be in the future. When passing `"now"`, Stripe records usage for the current time. Default is `"now"` if a value is not provided. + """ + + def create( + self, + subscription_item: str, + params: "SubscriptionItemUsageRecordService.CreateParams", + options: RequestOptions = {}, + ) -> UsageRecord: + """ + Creates a usage record for a specified subscription item and date, and fills it with a quantity. + + Usage records provide quantity information that Stripe uses to track how much a customer is using your service. With usage information and the pricing model set up by the [metered billing](https://stripe.com/docs/billing/subscriptions/metered-billing) plan, Stripe helps you send accurate invoices to your customers. + + The default calculation for usage is to add up all the quantity values of the usage records within a billing period. You can change this default behavior with the billing plan's aggregate_usage [parameter](https://stripe.com/docs/api/plans/create#create_plan-aggregate_usage). When there is more than one usage record with the same timestamp, Stripe adds the quantity values together. In most cases, this is the desired resolution, however, you can change this behavior with the action parameter. + + The default pricing model for metered billing is [per-unit pricing. For finer granularity, you can configure metered billing to have a tiered pricing](https://stripe.com/docs/api/plans/object#plan_object-billing_scheme) model. + """ + return cast( + UsageRecord, + self._requestor.request( + "post", + "/v1/subscription_items/{subscription_item}/usage_records".format( + subscription_item=_util.sanitize_id(subscription_item), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_subscription_item_usage_record_summary_service.py b/stripe/_subscription_item_usage_record_summary_service.py new file mode 100644 index 000000000..48412782c --- /dev/null +++ b/stripe/_subscription_item_usage_record_summary_service.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe._usage_record_summary import UsageRecordSummary +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class SubscriptionItemUsageRecordSummaryService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + def list( + self, + subscription_item: str, + params: "SubscriptionItemUsageRecordSummaryService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[UsageRecordSummary]: + """ + For the specified subscription item, returns a list of summary objects. Each object in the list provides usage information that's been summarized from multiple usage records and over a subscription billing period (e.g., 15 usage records in the month of September). + + The list is sorted in reverse-chronological order (newest first). The first list item represents the most current usage period that hasn't ended yet. Since new usage records can still be added, the returned summary information for the subscription item's ID should be seen as unstable until the subscription billing period ends. + """ + return cast( + ListObject[UsageRecordSummary], + self._requestor.request( + "get", + "/v1/subscription_items/{subscription_item}/usage_record_summaries".format( + subscription_item=_util.sanitize_id(subscription_item), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_subscription_schedule.py b/stripe/_subscription_schedule.py index eaea01557..b0fc2d178 100644 --- a/stripe/_subscription_schedule.py +++ b/stripe/_subscription_schedule.py @@ -1472,12 +1472,7 @@ class RetrieveParams(RequestOptions): def _cls_cancel( cls, schedule: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SubscriptionSchedule.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["SubscriptionSchedule.CancelParams"] ) -> "SubscriptionSchedule": """ Cancels a subscription schedule and its associated subscription immediately (if the subscription schedule has an active subscription). A subscription schedule can only be canceled if its status is not_started or active. @@ -1489,9 +1484,6 @@ def _cls_cancel( "/v1/subscription_schedules/{schedule}/cancel".format( schedule=_util.sanitize_id(schedule) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1499,13 +1491,7 @@ def _cls_cancel( @overload @staticmethod def cancel( - schedule: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SubscriptionSchedule.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + schedule: str, **params: Unpack["SubscriptionSchedule.CancelParams"] ) -> "SubscriptionSchedule": """ Cancels a subscription schedule and its associated subscription immediately (if the subscription schedule has an active subscription). A subscription schedule can only be canceled if its status is not_started or active. @@ -1514,11 +1500,7 @@ def cancel( @overload def cancel( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "SubscriptionSchedule.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["SubscriptionSchedule.CancelParams"] ) -> "SubscriptionSchedule": """ Cancels a subscription schedule and its associated subscription immediately (if the subscription schedule has an active subscription). A subscription schedule can only be canceled if its status is not_started or active. @@ -1527,11 +1509,7 @@ def cancel( @class_method_variant("_cls_cancel") def cancel( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "SubscriptionSchedule.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["SubscriptionSchedule.CancelParams"] ) -> "SubscriptionSchedule": """ Cancels a subscription schedule and its associated subscription immediately (if the subscription schedule has an active subscription). A subscription schedule can only be canceled if its status is not_started or active. @@ -1543,21 +1521,13 @@ def cancel( # pyright: ignore[reportGeneralTypeIssues] "/v1/subscription_schedules/{schedule}/cancel".format( schedule=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SubscriptionSchedule.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["SubscriptionSchedule.CreateParams"] ) -> "SubscriptionSchedule": """ Creates a new subscription schedule object. Each customer can have up to 500 active or scheduled subscriptions. @@ -1567,23 +1537,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SubscriptionSchedule.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["SubscriptionSchedule.ListParams"] ) -> ListObject["SubscriptionSchedule"]: """ Retrieves the list of your subscription schedules. @@ -1591,9 +1551,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -1622,12 +1579,7 @@ def modify( def _cls_release( cls, schedule: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SubscriptionSchedule.ReleaseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["SubscriptionSchedule.ReleaseParams"] ) -> "SubscriptionSchedule": """ Releases the subscription schedule immediately, which will stop scheduling of its phases, but leave any existing subscription in place. A schedule can only be released if its status is not_started or active. If the subscription schedule is currently associated with a subscription, releasing it will remove its subscription property and set the subscription's ID to the released_subscription property. @@ -1639,9 +1591,6 @@ def _cls_release( "/v1/subscription_schedules/{schedule}/release".format( schedule=_util.sanitize_id(schedule) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1649,13 +1598,7 @@ def _cls_release( @overload @staticmethod def release( - schedule: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "SubscriptionSchedule.ReleaseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + schedule: str, **params: Unpack["SubscriptionSchedule.ReleaseParams"] ) -> "SubscriptionSchedule": """ Releases the subscription schedule immediately, which will stop scheduling of its phases, but leave any existing subscription in place. A schedule can only be released if its status is not_started or active. If the subscription schedule is currently associated with a subscription, releasing it will remove its subscription property and set the subscription's ID to the released_subscription property. @@ -1664,11 +1607,7 @@ def release( @overload def release( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "SubscriptionSchedule.ReleaseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["SubscriptionSchedule.ReleaseParams"] ) -> "SubscriptionSchedule": """ Releases the subscription schedule immediately, which will stop scheduling of its phases, but leave any existing subscription in place. A schedule can only be released if its status is not_started or active. If the subscription schedule is currently associated with a subscription, releasing it will remove its subscription property and set the subscription's ID to the released_subscription property. @@ -1677,11 +1616,7 @@ def release( @class_method_variant("_cls_release") def release( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "SubscriptionSchedule.ReleaseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["SubscriptionSchedule.ReleaseParams"] ) -> "SubscriptionSchedule": """ Releases the subscription schedule immediately, which will stop scheduling of its phases, but leave any existing subscription in place. A schedule can only be released if its status is not_started or active. If the subscription schedule is currently associated with a subscription, releasing it will remove its subscription property and set the subscription's ID to the released_subscription property. @@ -1693,7 +1628,6 @@ def release( # pyright: ignore[reportGeneralTypeIssues] "/v1/subscription_schedules/{schedule}/release".format( schedule=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/_subscription_schedule_service.py b/stripe/_subscription_schedule_service.py new file mode 100644 index 000000000..72abf3dd5 --- /dev/null +++ b/stripe/_subscription_schedule_service.py @@ -0,0 +1,1185 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe._subscription_schedule import SubscriptionSchedule +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class SubscriptionScheduleService(StripeService): + class CancelParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice_now: NotRequired["bool"] + """ + If the subscription schedule is `active`, indicates if a final invoice will be generated that contains any un-invoiced metered usage and new/pending proration invoice items. Defaults to `true`. + """ + prorate: NotRequired["bool"] + """ + If the subscription schedule is `active`, indicates if the cancellation should be prorated. Defaults to `true`. + """ + + class CreateParams(TypedDict): + customer: NotRequired["str"] + """ + The identifier of the customer to create the subscription schedule for. + """ + default_settings: NotRequired[ + "SubscriptionScheduleService.CreateParamsDefaultSettings" + ] + """ + Object representing the subscription schedule's default settings. + """ + end_behavior: NotRequired[ + "Literal['cancel', 'none', 'release', 'renew']" + ] + """ + Behavior of the subscription schedule and underlying subscription when it ends. Possible values are `release` or `cancel` with the default being `release`. `release` will end the subscription schedule and keep the underlying subscription running. `cancel` will end the subscription schedule and cancel the underlying subscription. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + from_subscription: NotRequired["str"] + """ + Migrate an existing subscription to be managed by a subscription schedule. If this parameter is set, a subscription schedule will be created using the subscription's item(s), set to auto-renew using the subscription's interval. When using this parameter, other parameters (such as phase values) cannot be set. To create a subscription schedule with other modifications, we recommend making two separate API calls. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + phases: NotRequired[ + "List[SubscriptionScheduleService.CreateParamsPhase]" + ] + """ + List representing phases of the subscription schedule. Each phase can be customized to have different durations, plans, and coupons. If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. + """ + start_date: NotRequired["int|Literal['now']"] + """ + When the subscription schedule starts. We recommend using `now` so that it starts the subscription immediately. You can also use a Unix timestamp to backdate the subscription so that it starts on a past date, or set a future date for the subscription to start on. + """ + + class CreateParamsDefaultSettings(TypedDict): + application_fee_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + """ + automatic_tax: NotRequired[ + "SubscriptionScheduleService.CreateParamsDefaultSettingsAutomaticTax" + ] + """ + Default settings for automatic tax computation. + """ + billing_cycle_anchor: NotRequired[ + "Literal['automatic', 'phase_start']" + ] + """ + Can be set to `phase_start` to set the anchor to the start of the phase or `automatic` to automatically change it if needed. Cannot be set to `phase_start` if this phase specifies a trial. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + """ + billing_thresholds: NotRequired[ + "Literal['']|SubscriptionScheduleService.CreateParamsDefaultSettingsBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + """ + collection_method: NotRequired[ + "Literal['charge_automatically', 'send_invoice']" + ] + """ + Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically` on creation. + """ + default_payment_method: NotRequired["str"] + """ + ID of the default payment method for the subscription schedule. It must belong to the customer associated with the subscription schedule. If not set, invoices will use the default payment method in the customer's invoice settings. + """ + description: NotRequired["Literal['']|str"] + """ + Subscription description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + """ + invoice_settings: NotRequired[ + "SubscriptionScheduleService.CreateParamsDefaultSettingsInvoiceSettings" + ] + """ + All invoices will be billed using the specified settings. + """ + on_behalf_of: NotRequired["Literal['']|str"] + """ + The account on behalf of which to charge, for each of the associated subscription's invoices. + """ + transfer_data: NotRequired[ + "Literal['']|SubscriptionScheduleService.CreateParamsDefaultSettingsTransferData" + ] + """ + The data with which to automatically create a Transfer for each of the associated subscription's invoices. + """ + + class CreateParamsDefaultSettingsAutomaticTax(TypedDict): + enabled: bool + """ + Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + """ + liability: NotRequired[ + "SubscriptionScheduleService.CreateParamsDefaultSettingsAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class CreateParamsDefaultSettingsAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsDefaultSettingsBillingThresholds(TypedDict): + amount_gte: NotRequired["int"] + """ + Monetary threshold that triggers the subscription to advance to a new billing period + """ + reset_billing_cycle_anchor: NotRequired["bool"] + """ + Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + """ + + class CreateParamsDefaultSettingsInvoiceSettings(TypedDict): + days_until_due: NotRequired["int"] + """ + Number of days within which a customer must pay invoices generated by this subscription schedule. This value will be `null` for subscription schedules where `collection_method=charge_automatically`. + """ + issuer: NotRequired[ + "SubscriptionScheduleService.CreateParamsDefaultSettingsInvoiceSettingsIssuer" + ] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + + class CreateParamsDefaultSettingsInvoiceSettingsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsDefaultSettingsTransferData(TypedDict): + amount_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + """ + destination: str + """ + ID of an existing, connected Stripe account. + """ + + class CreateParamsPhase(TypedDict): + add_invoice_items: NotRequired[ + "List[SubscriptionScheduleService.CreateParamsPhaseAddInvoiceItem]" + ] + """ + A list of prices and quantities that will generate invoice items appended to the next invoice for this phase. You may pass up to 20 items. + """ + application_fee_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + """ + automatic_tax: NotRequired[ + "SubscriptionScheduleService.CreateParamsPhaseAutomaticTax" + ] + """ + Automatic tax settings for this phase. + """ + billing_cycle_anchor: NotRequired[ + "Literal['automatic', 'phase_start']" + ] + """ + Can be set to `phase_start` to set the anchor to the start of the phase or `automatic` to automatically change it if needed. Cannot be set to `phase_start` if this phase specifies a trial. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + """ + billing_thresholds: NotRequired[ + "Literal['']|SubscriptionScheduleService.CreateParamsPhaseBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + """ + collection_method: NotRequired[ + "Literal['charge_automatically', 'send_invoice']" + ] + """ + Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically` on creation. + """ + coupon: NotRequired["str"] + """ + The identifier of the coupon to apply to this phase of the subscription schedule. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + default_payment_method: NotRequired["str"] + """ + ID of the default payment method for the subscription schedule. It must belong to the customer associated with the subscription schedule. If not set, invoices will use the default payment method in the customer's invoice settings. + """ + default_tax_rates: NotRequired["Literal['']|List[str]"] + """ + A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will set the Subscription's [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates), which means they will be the Invoice's [`default_tax_rates`](https://stripe.com/docs/api/invoices/create#create_invoice-default_tax_rates) for any Invoices issued by the Subscription during this Phase. + """ + description: NotRequired["Literal['']|str"] + """ + Subscription description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + """ + end_date: NotRequired["int"] + """ + The date at which this phase of the subscription schedule ends. If set, `iterations` must not be set. + """ + invoice_settings: NotRequired[ + "SubscriptionScheduleService.CreateParamsPhaseInvoiceSettings" + ] + """ + All invoices will be billed using the specified settings. + """ + items: List["SubscriptionScheduleService.CreateParamsPhaseItem"] + """ + List of configuration items, each with an attached price, to apply during this phase of the subscription schedule. + """ + iterations: NotRequired["int"] + """ + Integer representing the multiplier applied to the price interval. For example, `iterations=2` applied to a price with `interval=month` and `interval_count=3` results in a phase of duration `2 * 3 months = 6 months`. If set, `end_date` must not be set. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to a phase. Metadata on a schedule's phase will update the underlying subscription's `metadata` when the phase is entered, adding new keys and replacing existing keys in the subscription's `metadata`. Individual keys in the subscription's `metadata` can be unset by posting an empty value to them in the phase's `metadata`. To unset all keys in the subscription's `metadata`, update the subscription directly or unset every key individually from the phase's `metadata`. + """ + on_behalf_of: NotRequired["str"] + """ + The account on behalf of which to charge, for each of the associated subscription's invoices. + """ + proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Whether the subscription schedule will create [prorations](https://stripe.com/docs/billing/subscriptions/prorations) when transitioning to this phase. The default value is `create_prorations`. This setting controls prorations when a phase is started asynchronously and it is persisted as a field on the phase. It's different from the request-level [proration_behavior](https://stripe.com/docs/api/subscription_schedules/update#update_subscription_schedule-proration_behavior) parameter which controls what happens if the update request affects the billing configuration of the current phase. + """ + transfer_data: NotRequired[ + "SubscriptionScheduleService.CreateParamsPhaseTransferData" + ] + """ + The data with which to automatically create a Transfer for each of the associated subscription's invoices. + """ + trial: NotRequired["bool"] + """ + If set to true the entire phase is counted as a trial and the customer will not be charged for any fees. + """ + trial_end: NotRequired["int"] + """ + Sets the phase to trialing from the start date to this date. Must be before the phase end date, can not be combined with `trial` + """ + + class CreateParamsPhaseAddInvoiceItem(TypedDict): + price: NotRequired["str"] + """ + The ID of the price object. + """ + price_data: NotRequired[ + "SubscriptionScheduleService.CreateParamsPhaseAddInvoiceItemPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Quantity for this item. Defaults to 1. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates which apply to the item. When set, the `default_tax_rates` do not apply to this item. + """ + + class CreateParamsPhaseAddInvoiceItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class CreateParamsPhaseAutomaticTax(TypedDict): + enabled: bool + """ + Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + """ + liability: NotRequired[ + "SubscriptionScheduleService.CreateParamsPhaseAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class CreateParamsPhaseAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsPhaseBillingThresholds(TypedDict): + amount_gte: NotRequired["int"] + """ + Monetary threshold that triggers the subscription to advance to a new billing period + """ + reset_billing_cycle_anchor: NotRequired["bool"] + """ + Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + """ + + class CreateParamsPhaseInvoiceSettings(TypedDict): + days_until_due: NotRequired["int"] + """ + Number of days within which a customer must pay invoices generated by this subscription schedule. This value will be `null` for subscription schedules where `billing=charge_automatically`. + """ + issuer: NotRequired[ + "SubscriptionScheduleService.CreateParamsPhaseInvoiceSettingsIssuer" + ] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + + class CreateParamsPhaseInvoiceSettingsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsPhaseItem(TypedDict): + billing_thresholds: NotRequired[ + "Literal['']|SubscriptionScheduleService.CreateParamsPhaseItemBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to a configuration item. Metadata on a configuration item will update the underlying subscription item's `metadata` when the phase is entered, adding new keys and replacing existing keys. Individual keys in the subscription item's `metadata` can be unset by posting an empty value to them in the configuration item's `metadata`. To unset all keys in the subscription item's `metadata`, update the subscription item directly or unset every key individually from the configuration item's `metadata`. + """ + plan: NotRequired["str"] + """ + The plan ID to subscribe to. You may specify the same ID in `plan` and `price`. + """ + price: NotRequired["str"] + """ + The ID of the price object. + """ + price_data: NotRequired[ + "SubscriptionScheduleService.CreateParamsPhaseItemPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Quantity for the given price. Can be set only if the price's `usage_type` is `licensed` and not `metered`. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + """ + + class CreateParamsPhaseItemBillingThresholds(TypedDict): + usage_gte: int + """ + Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + """ + + class CreateParamsPhaseItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + recurring: "SubscriptionScheduleService.CreateParamsPhaseItemPriceDataRecurring" + """ + The recurring components of a price such as `interval` and `interval_count`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class CreateParamsPhaseItemPriceDataRecurring(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + + class CreateParamsPhaseTransferData(TypedDict): + amount_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + """ + destination: str + """ + ID of an existing, connected Stripe account. + """ + + class ListParams(TypedDict): + canceled_at: NotRequired[ + "SubscriptionScheduleService.ListParamsCanceledAt|int" + ] + """ + Only return subscription schedules that were created canceled the given date interval. + """ + completed_at: NotRequired[ + "SubscriptionScheduleService.ListParamsCompletedAt|int" + ] + """ + Only return subscription schedules that completed during the given date interval. + """ + created: NotRequired[ + "SubscriptionScheduleService.ListParamsCreated|int" + ] + """ + Only return subscription schedules that were created during the given date interval. + """ + customer: NotRequired["str"] + """ + Only return subscription schedules for the given customer. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + released_at: NotRequired[ + "SubscriptionScheduleService.ListParamsReleasedAt|int" + ] + """ + Only return subscription schedules that were released during the given date interval. + """ + scheduled: NotRequired["bool"] + """ + Only return subscription schedules that have not started yet. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCanceledAt(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ListParamsCompletedAt(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ListParamsReleasedAt(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ReleaseParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + preserve_cancel_date: NotRequired["bool"] + """ + Keep any cancellation on the subscription that the schedule has set + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + default_settings: NotRequired[ + "SubscriptionScheduleService.UpdateParamsDefaultSettings" + ] + """ + Object representing the subscription schedule's default settings. + """ + end_behavior: NotRequired[ + "Literal['cancel', 'none', 'release', 'renew']" + ] + """ + Behavior of the subscription schedule and underlying subscription when it ends. Possible values are `release` or `cancel` with the default being `release`. `release` will end the subscription schedule and keep the underlying subscription running. `cancel` will end the subscription schedule and cancel the underlying subscription. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + phases: NotRequired[ + "List[SubscriptionScheduleService.UpdateParamsPhase]" + ] + """ + List representing phases of the subscription schedule. Each phase can be customized to have different durations, plans, and coupons. If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. Note that past phases can be omitted. + """ + proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + If the update changes the current phase, indicates whether the changes should be prorated. The default value is `create_prorations`. + """ + + class UpdateParamsDefaultSettings(TypedDict): + application_fee_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + """ + automatic_tax: NotRequired[ + "SubscriptionScheduleService.UpdateParamsDefaultSettingsAutomaticTax" + ] + """ + Default settings for automatic tax computation. + """ + billing_cycle_anchor: NotRequired[ + "Literal['automatic', 'phase_start']" + ] + """ + Can be set to `phase_start` to set the anchor to the start of the phase or `automatic` to automatically change it if needed. Cannot be set to `phase_start` if this phase specifies a trial. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + """ + billing_thresholds: NotRequired[ + "Literal['']|SubscriptionScheduleService.UpdateParamsDefaultSettingsBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + """ + collection_method: NotRequired[ + "Literal['charge_automatically', 'send_invoice']" + ] + """ + Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically` on creation. + """ + default_payment_method: NotRequired["str"] + """ + ID of the default payment method for the subscription schedule. It must belong to the customer associated with the subscription schedule. If not set, invoices will use the default payment method in the customer's invoice settings. + """ + description: NotRequired["Literal['']|str"] + """ + Subscription description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + """ + invoice_settings: NotRequired[ + "SubscriptionScheduleService.UpdateParamsDefaultSettingsInvoiceSettings" + ] + """ + All invoices will be billed using the specified settings. + """ + on_behalf_of: NotRequired["Literal['']|str"] + """ + The account on behalf of which to charge, for each of the associated subscription's invoices. + """ + transfer_data: NotRequired[ + "Literal['']|SubscriptionScheduleService.UpdateParamsDefaultSettingsTransferData" + ] + """ + The data with which to automatically create a Transfer for each of the associated subscription's invoices. + """ + + class UpdateParamsDefaultSettingsAutomaticTax(TypedDict): + enabled: bool + """ + Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + """ + liability: NotRequired[ + "SubscriptionScheduleService.UpdateParamsDefaultSettingsAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class UpdateParamsDefaultSettingsAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpdateParamsDefaultSettingsBillingThresholds(TypedDict): + amount_gte: NotRequired["int"] + """ + Monetary threshold that triggers the subscription to advance to a new billing period + """ + reset_billing_cycle_anchor: NotRequired["bool"] + """ + Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + """ + + class UpdateParamsDefaultSettingsInvoiceSettings(TypedDict): + days_until_due: NotRequired["int"] + """ + Number of days within which a customer must pay invoices generated by this subscription schedule. This value will be `null` for subscription schedules where `collection_method=charge_automatically`. + """ + issuer: NotRequired[ + "SubscriptionScheduleService.UpdateParamsDefaultSettingsInvoiceSettingsIssuer" + ] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + + class UpdateParamsDefaultSettingsInvoiceSettingsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpdateParamsDefaultSettingsTransferData(TypedDict): + amount_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + """ + destination: str + """ + ID of an existing, connected Stripe account. + """ + + class UpdateParamsPhase(TypedDict): + add_invoice_items: NotRequired[ + "List[SubscriptionScheduleService.UpdateParamsPhaseAddInvoiceItem]" + ] + """ + A list of prices and quantities that will generate invoice items appended to the next invoice for this phase. You may pass up to 20 items. + """ + application_fee_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + """ + automatic_tax: NotRequired[ + "SubscriptionScheduleService.UpdateParamsPhaseAutomaticTax" + ] + """ + Automatic tax settings for this phase. + """ + billing_cycle_anchor: NotRequired[ + "Literal['automatic', 'phase_start']" + ] + """ + Can be set to `phase_start` to set the anchor to the start of the phase or `automatic` to automatically change it if needed. Cannot be set to `phase_start` if this phase specifies a trial. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + """ + billing_thresholds: NotRequired[ + "Literal['']|SubscriptionScheduleService.UpdateParamsPhaseBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + """ + collection_method: NotRequired[ + "Literal['charge_automatically', 'send_invoice']" + ] + """ + Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically` on creation. + """ + coupon: NotRequired["str"] + """ + The identifier of the coupon to apply to this phase of the subscription schedule. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + default_payment_method: NotRequired["str"] + """ + ID of the default payment method for the subscription schedule. It must belong to the customer associated with the subscription schedule. If not set, invoices will use the default payment method in the customer's invoice settings. + """ + default_tax_rates: NotRequired["Literal['']|List[str]"] + """ + A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will set the Subscription's [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates), which means they will be the Invoice's [`default_tax_rates`](https://stripe.com/docs/api/invoices/create#create_invoice-default_tax_rates) for any Invoices issued by the Subscription during this Phase. + """ + description: NotRequired["Literal['']|str"] + """ + Subscription description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + """ + end_date: NotRequired["int|Literal['now']"] + """ + The date at which this phase of the subscription schedule ends. If set, `iterations` must not be set. + """ + invoice_settings: NotRequired[ + "SubscriptionScheduleService.UpdateParamsPhaseInvoiceSettings" + ] + """ + All invoices will be billed using the specified settings. + """ + items: List["SubscriptionScheduleService.UpdateParamsPhaseItem"] + """ + List of configuration items, each with an attached price, to apply during this phase of the subscription schedule. + """ + iterations: NotRequired["int"] + """ + Integer representing the multiplier applied to the price interval. For example, `iterations=2` applied to a price with `interval=month` and `interval_count=3` results in a phase of duration `2 * 3 months = 6 months`. If set, `end_date` must not be set. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to a phase. Metadata on a schedule's phase will update the underlying subscription's `metadata` when the phase is entered, adding new keys and replacing existing keys in the subscription's `metadata`. Individual keys in the subscription's `metadata` can be unset by posting an empty value to them in the phase's `metadata`. To unset all keys in the subscription's `metadata`, update the subscription directly or unset every key individually from the phase's `metadata`. + """ + on_behalf_of: NotRequired["str"] + """ + The account on behalf of which to charge, for each of the associated subscription's invoices. + """ + proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Whether the subscription schedule will create [prorations](https://stripe.com/docs/billing/subscriptions/prorations) when transitioning to this phase. The default value is `create_prorations`. This setting controls prorations when a phase is started asynchronously and it is persisted as a field on the phase. It's different from the request-level [proration_behavior](https://stripe.com/docs/api/subscription_schedules/update#update_subscription_schedule-proration_behavior) parameter which controls what happens if the update request affects the billing configuration of the current phase. + """ + start_date: NotRequired["int|Literal['now']"] + """ + The date at which this phase of the subscription schedule starts or `now`. Must be set on the first phase. + """ + transfer_data: NotRequired[ + "SubscriptionScheduleService.UpdateParamsPhaseTransferData" + ] + """ + The data with which to automatically create a Transfer for each of the associated subscription's invoices. + """ + trial: NotRequired["bool"] + """ + If set to true the entire phase is counted as a trial and the customer will not be charged for any fees. + """ + trial_end: NotRequired["int|Literal['now']"] + """ + Sets the phase to trialing from the start date to this date. Must be before the phase end date, can not be combined with `trial` + """ + + class UpdateParamsPhaseAddInvoiceItem(TypedDict): + price: NotRequired["str"] + """ + The ID of the price object. + """ + price_data: NotRequired[ + "SubscriptionScheduleService.UpdateParamsPhaseAddInvoiceItemPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Quantity for this item. Defaults to 1. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates which apply to the item. When set, the `default_tax_rates` do not apply to this item. + """ + + class UpdateParamsPhaseAddInvoiceItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class UpdateParamsPhaseAutomaticTax(TypedDict): + enabled: bool + """ + Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + """ + liability: NotRequired[ + "SubscriptionScheduleService.UpdateParamsPhaseAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class UpdateParamsPhaseAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpdateParamsPhaseBillingThresholds(TypedDict): + amount_gte: NotRequired["int"] + """ + Monetary threshold that triggers the subscription to advance to a new billing period + """ + reset_billing_cycle_anchor: NotRequired["bool"] + """ + Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + """ + + class UpdateParamsPhaseInvoiceSettings(TypedDict): + days_until_due: NotRequired["int"] + """ + Number of days within which a customer must pay invoices generated by this subscription schedule. This value will be `null` for subscription schedules where `billing=charge_automatically`. + """ + issuer: NotRequired[ + "SubscriptionScheduleService.UpdateParamsPhaseInvoiceSettingsIssuer" + ] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + + class UpdateParamsPhaseInvoiceSettingsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpdateParamsPhaseItem(TypedDict): + billing_thresholds: NotRequired[ + "Literal['']|SubscriptionScheduleService.UpdateParamsPhaseItemBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to a configuration item. Metadata on a configuration item will update the underlying subscription item's `metadata` when the phase is entered, adding new keys and replacing existing keys. Individual keys in the subscription item's `metadata` can be unset by posting an empty value to them in the configuration item's `metadata`. To unset all keys in the subscription item's `metadata`, update the subscription item directly or unset every key individually from the configuration item's `metadata`. + """ + plan: NotRequired["str"] + """ + The plan ID to subscribe to. You may specify the same ID in `plan` and `price`. + """ + price: NotRequired["str"] + """ + The ID of the price object. + """ + price_data: NotRequired[ + "SubscriptionScheduleService.UpdateParamsPhaseItemPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Quantity for the given price. Can be set only if the price's `usage_type` is `licensed` and not `metered`. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + """ + + class UpdateParamsPhaseItemBillingThresholds(TypedDict): + usage_gte: int + """ + Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + """ + + class UpdateParamsPhaseItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + recurring: "SubscriptionScheduleService.UpdateParamsPhaseItemPriceDataRecurring" + """ + The recurring components of a price such as `interval` and `interval_count`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class UpdateParamsPhaseItemPriceDataRecurring(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + + class UpdateParamsPhaseTransferData(TypedDict): + amount_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + """ + destination: str + """ + ID of an existing, connected Stripe account. + """ + + def list( + self, + params: "SubscriptionScheduleService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[SubscriptionSchedule]: + """ + Retrieves the list of your subscription schedules. + """ + return cast( + ListObject[SubscriptionSchedule], + self._requestor.request( + "get", + "/v1/subscription_schedules", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "SubscriptionScheduleService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> SubscriptionSchedule: + """ + Creates a new subscription schedule object. Each customer can have up to 500 active or scheduled subscriptions. + """ + return cast( + SubscriptionSchedule, + self._requestor.request( + "post", + "/v1/subscription_schedules", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + schedule: str, + params: "SubscriptionScheduleService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> SubscriptionSchedule: + """ + Retrieves the details of an existing subscription schedule. You only need to supply the unique subscription schedule identifier that was returned upon subscription schedule creation. + """ + return cast( + SubscriptionSchedule, + self._requestor.request( + "get", + "/v1/subscription_schedules/{schedule}".format( + schedule=_util.sanitize_id(schedule), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + schedule: str, + params: "SubscriptionScheduleService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> SubscriptionSchedule: + """ + Updates an existing subscription schedule. + """ + return cast( + SubscriptionSchedule, + self._requestor.request( + "post", + "/v1/subscription_schedules/{schedule}".format( + schedule=_util.sanitize_id(schedule), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def cancel( + self, + schedule: str, + params: "SubscriptionScheduleService.CancelParams" = {}, + options: RequestOptions = {}, + ) -> SubscriptionSchedule: + """ + Cancels a subscription schedule and its associated subscription immediately (if the subscription schedule has an active subscription). A subscription schedule can only be canceled if its status is not_started or active. + """ + return cast( + SubscriptionSchedule, + self._requestor.request( + "post", + "/v1/subscription_schedules/{schedule}/cancel".format( + schedule=_util.sanitize_id(schedule), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def release( + self, + schedule: str, + params: "SubscriptionScheduleService.ReleaseParams" = {}, + options: RequestOptions = {}, + ) -> SubscriptionSchedule: + """ + Releases the subscription schedule immediately, which will stop scheduling of its phases, but leave any existing subscription in place. A schedule can only be released if its status is not_started or active. If the subscription schedule is currently associated with a subscription, releasing it will remove its subscription property and set the subscription's ID to the released_subscription property. + """ + return cast( + SubscriptionSchedule, + self._requestor.request( + "post", + "/v1/subscription_schedules/{schedule}/release".format( + schedule=_util.sanitize_id(schedule), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_subscription_service.py b/stripe/_subscription_service.py new file mode 100644 index 000000000..3373f3988 --- /dev/null +++ b/stripe/_subscription_service.py @@ -0,0 +1,1607 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._discount import Discount +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._search_result_object import SearchResultObject +from stripe._stripe_service import StripeService +from stripe._subscription import Subscription +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class SubscriptionService(StripeService): + class CancelParams(TypedDict): + cancellation_details: NotRequired[ + "SubscriptionService.CancelParamsCancellationDetails" + ] + """ + Details about why this subscription was cancelled + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice_now: NotRequired["bool"] + """ + Will generate a final invoice that invoices for any un-invoiced metered usage and new/pending proration invoice items. + """ + prorate: NotRequired["bool"] + """ + Will generate a proration invoice item that credits remaining unused time until the subscription period end. + """ + + class CancelParamsCancellationDetails(TypedDict): + comment: NotRequired["Literal['']|str"] + """ + Additional comments about why the user canceled the subscription, if the subscription was canceled explicitly by the user. + """ + feedback: NotRequired[ + "Literal['']|Literal['customer_service', 'low_quality', 'missing_features', 'other', 'switched_service', 'too_complex', 'too_expensive', 'unused']" + ] + """ + The customer submitted reason for why they canceled, if the subscription was canceled explicitly by the user. + """ + + class CreateParams(TypedDict): + add_invoice_items: NotRequired[ + "List[SubscriptionService.CreateParamsAddInvoiceItem]" + ] + """ + A list of prices and quantities that will generate invoice items appended to the next invoice for this subscription. You may pass up to 20 items. + """ + application_fee_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + """ + automatic_tax: NotRequired[ + "SubscriptionService.CreateParamsAutomaticTax" + ] + """ + Automatic tax settings for this subscription. We recommend you only include this parameter when the existing value is being changed. + """ + backdate_start_date: NotRequired["int"] + """ + For new subscriptions, a past timestamp to backdate the subscription's start date to. If set, the first invoice will contain a proration for the timespan between the start date and the current time. Can be combined with trials and the billing cycle anchor. + """ + billing_cycle_anchor: NotRequired["int"] + """ + A future timestamp in UTC format to anchor the subscription's [billing cycle](https://stripe.com/docs/subscriptions/billing-cycle). The anchor is the reference point that aligns future billing cycle dates. It sets the day of week for `week` intervals, the day of month for `month` and `year` intervals, and the month of year for `year` intervals. + """ + billing_cycle_anchor_config: NotRequired[ + "SubscriptionService.CreateParamsBillingCycleAnchorConfig" + ] + """ + Mutually exclusive with billing_cycle_anchor and only valid with monthly and yearly price intervals. When provided, the billing_cycle_anchor is set to the next occurence of the day_of_month at the hour, minute, and second UTC. + """ + billing_thresholds: NotRequired[ + "Literal['']|SubscriptionService.CreateParamsBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + """ + cancel_at: NotRequired["int"] + """ + A timestamp at which the subscription should cancel. If set to a date before the current period ends, this will cause a proration if prorations have been enabled using `proration_behavior`. If set during a future period, this will always cause a proration for that period. + """ + cancel_at_period_end: NotRequired["bool"] + """ + Boolean indicating whether this subscription should cancel at the end of the current period. + """ + collection_method: NotRequired[ + "Literal['charge_automatically', 'send_invoice']" + ] + """ + Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically`. + """ + coupon: NotRequired["str"] + """ + The ID of the coupon to apply to this subscription. A coupon applied to a subscription will only affect invoices created for that particular subscription. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + customer: str + """ + The identifier of the customer to subscribe. + """ + days_until_due: NotRequired["int"] + """ + Number of days a customer has to pay invoices generated by this subscription. Valid only for subscriptions where `collection_method` is set to `send_invoice`. + """ + default_payment_method: NotRequired["str"] + """ + ID of the default payment method for the subscription. It must belong to the customer associated with the subscription. This takes precedence over `default_source`. If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + """ + default_source: NotRequired["str"] + """ + ID of the default payment source for the subscription. It must belong to the customer associated with the subscription and be in a chargeable state. If `default_payment_method` is also set, `default_payment_method` will take precedence. If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + """ + default_tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates that will apply to any subscription item that does not have `tax_rates` set. Invoices created will have their `default_tax_rates` populated from the subscription. + """ + description: NotRequired["str"] + """ + The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice_settings: NotRequired[ + "SubscriptionService.CreateParamsInvoiceSettings" + ] + """ + All invoices will be billed using the specified settings. + """ + items: NotRequired["List[SubscriptionService.CreateParamsItem]"] + """ + A list of up to 20 subscription items, each with an attached price. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + off_session: NotRequired["bool"] + """ + Indicates if a customer is on or off-session while an invoice payment is attempted. + """ + on_behalf_of: NotRequired["Literal['']|str"] + """ + The account on behalf of which to charge, for each of the subscription's invoices. + """ + payment_behavior: NotRequired[ + "Literal['allow_incomplete', 'default_incomplete', 'error_if_incomplete', 'pending_if_incomplete']" + ] + """ + Only applies to subscriptions with `collection_method=charge_automatically`. + + Use `allow_incomplete` to create subscriptions with `status=incomplete` if the first invoice cannot be paid. Creating subscriptions with this status allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. For example, SCA regulation may require 3DS authentication to complete payment. See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. This is the default behavior. + + Use `default_incomplete` to create Subscriptions with `status=incomplete` when the first invoice requires payment, otherwise start as active. Subscriptions transition to `status=active` when successfully confirming the payment intent on the first invoice. This allows simpler management of scenarios where additional user actions are needed to pay a subscription's invoice. Such as failed payments, [SCA regulation](https://stripe.com/docs/billing/migration/strong-customer-authentication), or collecting a mandate for a bank debit payment method. If the payment intent is not confirmed within 23 hours subscriptions transition to `status=incomplete_expired`, which is a terminal state. + + Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's first invoice cannot be paid. For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not create a subscription and returns an error instead. This was the default behavior for API versions prior to 2019-03-14. See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + + `pending_if_incomplete` is only used with updates and cannot be passed when creating a subscription. + + Subscriptions with `collection_method=send_invoice` are automatically activated regardless of the first invoice status. + """ + payment_settings: NotRequired[ + "SubscriptionService.CreateParamsPaymentSettings" + ] + """ + Payment settings to pass to invoices created by the subscription. + """ + pending_invoice_item_interval: NotRequired[ + "Literal['']|SubscriptionService.CreateParamsPendingInvoiceItemInterval" + ] + """ + Specifies an interval for how often to bill for any pending invoice items. It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. + """ + promotion_code: NotRequired["str"] + """ + The API ID of a promotion code to apply to this subscription. A promotion code applied to a subscription will only affect invoices created for that particular subscription. + """ + proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) resulting from the `billing_cycle_anchor`. If no value is passed, the default is `create_prorations`. + """ + transfer_data: NotRequired[ + "SubscriptionService.CreateParamsTransferData" + ] + """ + If specified, the funds from the subscription's invoices will be transferred to the destination and the ID of the resulting transfers will be found on the resulting charges. + """ + trial_end: NotRequired["Literal['now']|int"] + """ + Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. If set, trial_end will override the default trial period of the plan the customer is being subscribed to. The special value `now` can be provided to end the customer's trial immediately. Can be at most two years from `billing_cycle_anchor`. See [Using trial periods on subscriptions](https://stripe.com/docs/billing/subscriptions/trials) to learn more. + """ + trial_from_plan: NotRequired["bool"] + """ + Indicates if a plan's `trial_period_days` should be applied to the subscription. Setting `trial_end` per subscription is preferred, and this defaults to `false`. Setting this flag to `true` together with `trial_end` is not allowed. See [Using trial periods on subscriptions](https://stripe.com/docs/billing/subscriptions/trials) to learn more. + """ + trial_period_days: NotRequired["int"] + """ + Integer representing the number of trial period days before the customer is charged for the first time. This will always overwrite any trials that might apply via a subscribed plan. See [Using trial periods on subscriptions](https://stripe.com/docs/billing/subscriptions/trials) to learn more. + """ + trial_settings: NotRequired[ + "SubscriptionService.CreateParamsTrialSettings" + ] + """ + Settings related to subscription trials. + """ + + class CreateParamsAddInvoiceItem(TypedDict): + price: NotRequired["str"] + """ + The ID of the price object. + """ + price_data: NotRequired[ + "SubscriptionService.CreateParamsAddInvoiceItemPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Quantity for this item. Defaults to 1. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates which apply to the item. When set, the `default_tax_rates` do not apply to this item. + """ + + class CreateParamsAddInvoiceItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class CreateParamsAutomaticTax(TypedDict): + enabled: bool + """ + Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + """ + liability: NotRequired[ + "SubscriptionService.CreateParamsAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class CreateParamsAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsBillingCycleAnchorConfig(TypedDict): + day_of_month: int + """ + The day of the month the billing_cycle_anchor should be. Ranges from 1 to 31. + """ + hour: NotRequired["int"] + """ + The hour of the day the billing_cycle_anchor should be. Ranges from 0 to 23. + """ + minute: NotRequired["int"] + """ + The minute of the hour the billing_cycle_anchor should be. Ranges from 0 to 59. + """ + month: NotRequired["int"] + """ + The month to start full cycle billing periods. Ranges from 1 to 12. + """ + second: NotRequired["int"] + """ + The second of the minute the billing_cycle_anchor should be. Ranges from 0 to 59. + """ + + class CreateParamsBillingThresholds(TypedDict): + amount_gte: NotRequired["int"] + """ + Monetary threshold that triggers the subscription to advance to a new billing period + """ + reset_billing_cycle_anchor: NotRequired["bool"] + """ + Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + """ + + class CreateParamsInvoiceSettings(TypedDict): + issuer: NotRequired[ + "SubscriptionService.CreateParamsInvoiceSettingsIssuer" + ] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + + class CreateParamsInvoiceSettingsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsItem(TypedDict): + billing_thresholds: NotRequired[ + "Literal['']|SubscriptionService.CreateParamsItemBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + plan: NotRequired["str"] + """ + Plan ID for this item, as a string. + """ + price: NotRequired["str"] + """ + The ID of the price object. + """ + price_data: NotRequired[ + "SubscriptionService.CreateParamsItemPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Quantity for this item. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + """ + + class CreateParamsItemBillingThresholds(TypedDict): + usage_gte: int + """ + Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + """ + + class CreateParamsItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + recurring: "SubscriptionService.CreateParamsItemPriceDataRecurring" + """ + The recurring components of a price such as `interval` and `interval_count`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class CreateParamsItemPriceDataRecurring(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + + class CreateParamsPaymentSettings(TypedDict): + payment_method_options: NotRequired[ + "SubscriptionService.CreateParamsPaymentSettingsPaymentMethodOptions" + ] + """ + Payment-method-specific configuration to provide to invoices created by the subscription. + """ + payment_method_types: NotRequired[ + "Literal['']|List[Literal['ach_credit_transfer', 'ach_debit', 'acss_debit', 'au_becs_debit', 'bacs_debit', 'bancontact', 'boleto', 'card', 'cashapp', 'customer_balance', 'eps', 'fpx', 'giropay', 'grabpay', 'ideal', 'konbini', 'link', 'p24', 'paynow', 'paypal', 'promptpay', 'sepa_credit_transfer', 'sepa_debit', 'sofort', 'us_bank_account', 'wechat_pay']]" + ] + """ + The list of payment method types (e.g. card) to provide to the invoice's PaymentIntent. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). + """ + save_default_payment_method: NotRequired[ + "Literal['off', 'on_subscription']" + ] + """ + Either `off`, or `on_subscription`. With `on_subscription` Stripe updates `subscription.default_payment_method` when a subscription payment succeeds. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptions(TypedDict): + acss_debit: NotRequired[ + "Literal['']|SubscriptionService.CreateParamsPaymentSettingsPaymentMethodOptionsAcssDebit" + ] + """ + This sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. + """ + bancontact: NotRequired[ + "Literal['']|SubscriptionService.CreateParamsPaymentSettingsPaymentMethodOptionsBancontact" + ] + """ + This sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. + """ + card: NotRequired[ + "Literal['']|SubscriptionService.CreateParamsPaymentSettingsPaymentMethodOptionsCard" + ] + """ + This sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. + """ + customer_balance: NotRequired[ + "Literal['']|SubscriptionService.CreateParamsPaymentSettingsPaymentMethodOptionsCustomerBalance" + ] + """ + This sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. + """ + konbini: NotRequired[ + "Literal['']|SubscriptionService.CreateParamsPaymentSettingsPaymentMethodOptionsKonbini" + ] + """ + This sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. + """ + us_bank_account: NotRequired[ + "Literal['']|SubscriptionService.CreateParamsPaymentSettingsPaymentMethodOptionsUsBankAccount" + ] + """ + This sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsAcssDebit(TypedDict): + mandate_options: NotRequired[ + "SubscriptionService.CreateParamsPaymentSettingsPaymentMethodOptionsAcssDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Verification method for the intent + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsAcssDebitMandateOptions( + TypedDict, + ): + transaction_type: NotRequired["Literal['business', 'personal']"] + """ + Transaction type of the mandate. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsBancontact(TypedDict): + preferred_language: NotRequired["Literal['de', 'en', 'fr', 'nl']"] + """ + Preferred language of the Bancontact authorization page that the customer is redirected to. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsCard(TypedDict): + mandate_options: NotRequired[ + "SubscriptionService.CreateParamsPaymentSettingsPaymentMethodOptionsCardMandateOptions" + ] + """ + Configuration options for setting up an eMandate for cards issued in India. + """ + network: NotRequired[ + "Literal['amex', 'cartes_bancaires', 'diners', 'discover', 'eftpos_au', 'interac', 'jcb', 'mastercard', 'unionpay', 'unknown', 'visa']" + ] + """ + Selected network to process this Subscription on. Depends on the available networks of the card attached to the Subscription. Can be only set confirm-time. + """ + request_three_d_secure: NotRequired[ + "Literal['any', 'automatic', 'challenge']" + ] + """ + We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsCardMandateOptions( + TypedDict, + ): + amount: NotRequired["int"] + """ + Amount to be charged for future payments. + """ + amount_type: NotRequired["Literal['fixed', 'maximum']"] + """ + One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + """ + description: NotRequired["str"] + """ + A description of the mandate or subscription that is meant to be displayed to the customer. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsCustomerBalance( + TypedDict, + ): + bank_transfer: NotRequired[ + "SubscriptionService.CreateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer" + ] + """ + Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + """ + funding_type: NotRequired["str"] + """ + The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer( + TypedDict, + ): + eu_bank_transfer: NotRequired[ + "SubscriptionService.CreateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer" + ] + """ + Configuration for eu_bank_transfer funding type. + """ + type: NotRequired["str"] + """ + The bank transfer type that can be used for funding. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer( + TypedDict, + ): + country: str + """ + The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsKonbini(TypedDict): + pass + + class CreateParamsPaymentSettingsPaymentMethodOptionsUsBankAccount( + TypedDict, + ): + financial_connections: NotRequired[ + "SubscriptionService.CreateParamsPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnections" + ] + """ + Additional fields for Financial Connections Session creation + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Verification method for the intent + """ + + class CreateParamsPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnections( + TypedDict, + ): + permissions: NotRequired[ + "List[Literal['balances', 'ownership', 'payment_method', 'transactions']]" + ] + """ + The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + """ + prefetch: NotRequired["List[Literal['balances', 'transactions']]"] + """ + List of data features that you would like to retrieve upon account creation. + """ + + class CreateParamsPendingInvoiceItemInterval(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies invoicing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between invoices. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). + """ + + class CreateParamsTransferData(TypedDict): + amount_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + """ + destination: str + """ + ID of an existing, connected Stripe account. + """ + + class CreateParamsTrialSettings(TypedDict): + end_behavior: "SubscriptionService.CreateParamsTrialSettingsEndBehavior" + """ + Defines how the subscription should behave when the user's free trial ends. + """ + + class CreateParamsTrialSettingsEndBehavior(TypedDict): + missing_payment_method: Literal["cancel", "create_invoice", "pause"] + """ + Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + """ + + class DeleteDiscountParams(TypedDict): + pass + + class ListParams(TypedDict): + automatic_tax: NotRequired[ + "SubscriptionService.ListParamsAutomaticTax" + ] + """ + Filter subscriptions by their automatic tax settings. + """ + collection_method: NotRequired[ + "Literal['charge_automatically', 'send_invoice']" + ] + """ + The collection method of the subscriptions to retrieve. Either `charge_automatically` or `send_invoice`. + """ + created: NotRequired["SubscriptionService.ListParamsCreated|int"] + current_period_end: NotRequired[ + "SubscriptionService.ListParamsCurrentPeriodEnd|int" + ] + current_period_start: NotRequired[ + "SubscriptionService.ListParamsCurrentPeriodStart|int" + ] + customer: NotRequired["str"] + """ + The ID of the customer whose subscriptions will be retrieved. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + plan: NotRequired["str"] + """ + The ID of the plan whose subscriptions will be retrieved. + """ + price: NotRequired["str"] + """ + Filter for subscriptions that contain this recurring price ID. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired[ + "Literal['active', 'all', 'canceled', 'ended', 'incomplete', 'incomplete_expired', 'past_due', 'paused', 'trialing', 'unpaid']" + ] + """ + The status of the subscriptions to retrieve. Passing in a value of `canceled` will return all canceled subscriptions, including those belonging to deleted customers. Pass `ended` to find subscriptions that are canceled and subscriptions that are expired due to [incomplete payment](https://stripe.com/docs/billing/subscriptions/overview#subscription-statuses). Passing in a value of `all` will return subscriptions of all statuses. If no value is supplied, all subscriptions that have not been canceled are returned. + """ + test_clock: NotRequired["str"] + """ + Filter for subscriptions that are associated with the specified test clock. The response will not include subscriptions with test clocks if this and the customer parameter is not set. + """ + + class ListParamsAutomaticTax(TypedDict): + enabled: bool + """ + Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ListParamsCurrentPeriodEnd(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ListParamsCurrentPeriodStart(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ResumeParams(TypedDict): + billing_cycle_anchor: NotRequired["Literal['now', 'unchanged']"] + """ + Either `now` or `unchanged`. Setting the value to `now` resets the subscription's billing cycle anchor to the current time (in UTC). Setting the value to `unchanged` advances the subscription's billing cycle anchor to the period that surrounds the current time. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + """ + proration_date: NotRequired["int"] + """ + If set, the proration will be calculated as though the subscription was resumed at the given time. This can be used to apply exactly the same proration that was previewed with [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class SearchParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + page: NotRequired["str"] + """ + A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + """ + query: str + """ + The search query string. See [search query language](https://stripe.com/docs/search#search-query-language) and the list of supported [query fields for subscriptions](https://stripe.com/docs/search#query-fields-for-subscriptions). + """ + + class UpdateParams(TypedDict): + add_invoice_items: NotRequired[ + "List[SubscriptionService.UpdateParamsAddInvoiceItem]" + ] + """ + A list of prices and quantities that will generate invoice items appended to the next invoice for this subscription. You may pass up to 20 items. + """ + application_fee_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + """ + automatic_tax: NotRequired[ + "SubscriptionService.UpdateParamsAutomaticTax" + ] + """ + Automatic tax settings for this subscription. We recommend you only include this parameter when the existing value is being changed. + """ + billing_cycle_anchor: NotRequired["Literal['now', 'unchanged']"] + """ + Either `now` or `unchanged`. Setting the value to `now` resets the subscription's billing cycle anchor to the current time (in UTC). For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + """ + billing_thresholds: NotRequired[ + "Literal['']|SubscriptionService.UpdateParamsBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds. + """ + cancel_at: NotRequired["Literal['']|int"] + """ + A timestamp at which the subscription should cancel. If set to a date before the current period ends, this will cause a proration if prorations have been enabled using `proration_behavior`. If set during a future period, this will always cause a proration for that period. + """ + cancel_at_period_end: NotRequired["bool"] + """ + Boolean indicating whether this subscription should cancel at the end of the current period. + """ + cancellation_details: NotRequired[ + "SubscriptionService.UpdateParamsCancellationDetails" + ] + """ + Details about why this subscription was cancelled + """ + collection_method: NotRequired[ + "Literal['charge_automatically', 'send_invoice']" + ] + """ + Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`. Defaults to `charge_automatically`. + """ + coupon: NotRequired["str"] + """ + The ID of the coupon to apply to this subscription. A coupon applied to a subscription will only affect invoices created for that particular subscription. + """ + days_until_due: NotRequired["int"] + """ + Number of days a customer has to pay invoices generated by this subscription. Valid only for subscriptions where `collection_method` is set to `send_invoice`. + """ + default_payment_method: NotRequired["str"] + """ + ID of the default payment method for the subscription. It must belong to the customer associated with the subscription. This takes precedence over `default_source`. If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + """ + default_source: NotRequired["Literal['']|str"] + """ + ID of the default payment source for the subscription. It must belong to the customer associated with the subscription and be in a chargeable state. If `default_payment_method` is also set, `default_payment_method` will take precedence. If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + """ + default_tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates that will apply to any subscription item that does not have `tax_rates` set. Invoices created will have their `default_tax_rates` populated from the subscription. Pass an empty string to remove previously-defined tax rates. + """ + description: NotRequired["Literal['']|str"] + """ + The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + invoice_settings: NotRequired[ + "SubscriptionService.UpdateParamsInvoiceSettings" + ] + """ + All invoices will be billed using the specified settings. + """ + items: NotRequired["List[SubscriptionService.UpdateParamsItem]"] + """ + A list of up to 20 subscription items, each with an attached price. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + off_session: NotRequired["bool"] + """ + Indicates if a customer is on or off-session while an invoice payment is attempted. + """ + on_behalf_of: NotRequired["Literal['']|str"] + """ + The account on behalf of which to charge, for each of the subscription's invoices. + """ + pause_collection: NotRequired[ + "Literal['']|SubscriptionService.UpdateParamsPauseCollection" + ] + """ + If specified, payment collection for this subscription will be paused. + """ + payment_behavior: NotRequired[ + "Literal['allow_incomplete', 'default_incomplete', 'error_if_incomplete', 'pending_if_incomplete']" + ] + """ + Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. For example, SCA regulation may require 3DS authentication to complete payment. See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. This is the default behavior. + + Use `default_incomplete` to transition the subscription to `status=past_due` when payment is required and await explicit confirmation of the invoice's payment intent. This allows simpler management of scenarios where additional user actions are needed to pay a subscription's invoice. Such as failed payments, [SCA regulation](https://stripe.com/docs/billing/migration/strong-customer-authentication), or collecting a mandate for a bank debit payment method. + + Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). + + Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's invoice cannot be paid. For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not update the subscription and returns an error instead. This was the default behavior for API versions prior to 2019-03-14. See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + """ + payment_settings: NotRequired[ + "SubscriptionService.UpdateParamsPaymentSettings" + ] + """ + Payment settings to pass to invoices created by the subscription. + """ + pending_invoice_item_interval: NotRequired[ + "Literal['']|SubscriptionService.UpdateParamsPendingInvoiceItemInterval" + ] + """ + Specifies an interval for how often to bill for any pending invoice items. It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. + """ + promotion_code: NotRequired["str"] + """ + The promotion code to apply to this subscription. A promotion code applied to a subscription will only affect invoices created for that particular subscription. + """ + proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. The default value is `create_prorations`. + """ + proration_date: NotRequired["int"] + """ + If set, the proration will be calculated as though the subscription was updated at the given time. This can be used to apply exactly the same proration that was previewed with [upcoming invoice](https://stripe.com/docs/api#upcoming_invoice) endpoint. It can also be used to implement custom proration logic, such as prorating by day instead of by second, by providing the time that you wish to use for proration calculations. + """ + transfer_data: NotRequired[ + "Literal['']|SubscriptionService.UpdateParamsTransferData" + ] + """ + If specified, the funds from the subscription's invoices will be transferred to the destination and the ID of the resulting transfers will be found on the resulting charges. This will be unset if you POST an empty value. + """ + trial_end: NotRequired["Literal['now']|int"] + """ + Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. This will always overwrite any trials that might apply via a subscribed plan. If set, trial_end will override the default trial period of the plan the customer is being subscribed to. The special value `now` can be provided to end the customer's trial immediately. Can be at most two years from `billing_cycle_anchor`. + """ + trial_from_plan: NotRequired["bool"] + """ + Indicates if a plan's `trial_period_days` should be applied to the subscription. Setting `trial_end` per subscription is preferred, and this defaults to `false`. Setting this flag to `true` together with `trial_end` is not allowed. See [Using trial periods on subscriptions](https://stripe.com/docs/billing/subscriptions/trials) to learn more. + """ + trial_settings: NotRequired[ + "SubscriptionService.UpdateParamsTrialSettings" + ] + """ + Settings related to subscription trials. + """ + + class UpdateParamsAddInvoiceItem(TypedDict): + price: NotRequired["str"] + """ + The ID of the price object. + """ + price_data: NotRequired[ + "SubscriptionService.UpdateParamsAddInvoiceItemPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Quantity for this item. Defaults to 1. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + The tax rates which apply to the item. When set, the `default_tax_rates` do not apply to this item. + """ + + class UpdateParamsAddInvoiceItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class UpdateParamsAutomaticTax(TypedDict): + enabled: bool + """ + Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription. + """ + liability: NotRequired[ + "SubscriptionService.UpdateParamsAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class UpdateParamsAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpdateParamsBillingThresholds(TypedDict): + amount_gte: NotRequired["int"] + """ + Monetary threshold that triggers the subscription to advance to a new billing period + """ + reset_billing_cycle_anchor: NotRequired["bool"] + """ + Indicates if the `billing_cycle_anchor` should be reset when a threshold is reached. If true, `billing_cycle_anchor` will be updated to the date/time the threshold was last reached; otherwise, the value will remain unchanged. + """ + + class UpdateParamsCancellationDetails(TypedDict): + comment: NotRequired["Literal['']|str"] + """ + Additional comments about why the user canceled the subscription, if the subscription was canceled explicitly by the user. + """ + feedback: NotRequired[ + "Literal['']|Literal['customer_service', 'low_quality', 'missing_features', 'other', 'switched_service', 'too_complex', 'too_expensive', 'unused']" + ] + """ + The customer submitted reason for why they canceled, if the subscription was canceled explicitly by the user. + """ + + class UpdateParamsInvoiceSettings(TypedDict): + issuer: NotRequired[ + "SubscriptionService.UpdateParamsInvoiceSettingsIssuer" + ] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + + class UpdateParamsInvoiceSettingsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class UpdateParamsItem(TypedDict): + billing_thresholds: NotRequired[ + "Literal['']|SubscriptionService.UpdateParamsItemBillingThresholds" + ] + """ + Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. When updating, pass an empty string to remove previously-defined thresholds. + """ + clear_usage: NotRequired["bool"] + """ + Delete all usage for a given subscription item. Allowed only when `deleted` is set to `true` and the current plan's `usage_type` is `metered`. + """ + deleted: NotRequired["bool"] + """ + A flag that, if set to `true`, will delete the specified item. + """ + id: NotRequired["str"] + """ + Subscription item to update. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + plan: NotRequired["str"] + """ + Plan ID for this item, as a string. + """ + price: NotRequired["str"] + """ + The ID of the price object. When changing a subscription item's price, `quantity` is set to 1 unless a `quantity` parameter is provided. + """ + price_data: NotRequired[ + "SubscriptionService.UpdateParamsItemPriceData" + ] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. + """ + quantity: NotRequired["int"] + """ + Quantity for this item. + """ + tax_rates: NotRequired["Literal['']|List[str]"] + """ + A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. When updating, pass an empty string to remove previously-defined tax rates. + """ + + class UpdateParamsItemBillingThresholds(TypedDict): + usage_gte: int + """ + Number of units that meets the billing threshold to advance the subscription to a new billing period (e.g., it takes 10 $5 units to meet a $50 [monetary threshold](https://stripe.com/docs/api/subscriptions/update#update_subscription-billing_thresholds-amount_gte)) + """ + + class UpdateParamsItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: str + """ + The ID of the product that this price will belong to. + """ + recurring: "SubscriptionService.UpdateParamsItemPriceDataRecurring" + """ + The recurring components of a price such as `interval` and `interval_count`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) (or 0 for a free price) representing how much to charge. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class UpdateParamsItemPriceDataRecurring(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + + class UpdateParamsPauseCollection(TypedDict): + behavior: Literal["keep_as_draft", "mark_uncollectible", "void"] + """ + The payment collection behavior for this subscription while paused. One of `keep_as_draft`, `mark_uncollectible`, or `void`. + """ + resumes_at: NotRequired["int"] + """ + The time after which the subscription will resume collecting payments. + """ + + class UpdateParamsPaymentSettings(TypedDict): + payment_method_options: NotRequired[ + "SubscriptionService.UpdateParamsPaymentSettingsPaymentMethodOptions" + ] + """ + Payment-method-specific configuration to provide to invoices created by the subscription. + """ + payment_method_types: NotRequired[ + "Literal['']|List[Literal['ach_credit_transfer', 'ach_debit', 'acss_debit', 'au_becs_debit', 'bacs_debit', 'bancontact', 'boleto', 'card', 'cashapp', 'customer_balance', 'eps', 'fpx', 'giropay', 'grabpay', 'ideal', 'konbini', 'link', 'p24', 'paynow', 'paypal', 'promptpay', 'sepa_credit_transfer', 'sepa_debit', 'sofort', 'us_bank_account', 'wechat_pay']]" + ] + """ + The list of payment method types (e.g. card) to provide to the invoice's PaymentIntent. If not set, Stripe attempts to automatically determine the types to use by looking at the invoice's default payment method, the subscription's default payment method, the customer's default payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). + """ + save_default_payment_method: NotRequired[ + "Literal['off', 'on_subscription']" + ] + """ + Either `off`, or `on_subscription`. With `on_subscription` Stripe updates `subscription.default_payment_method` when a subscription payment succeeds. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptions(TypedDict): + acss_debit: NotRequired[ + "Literal['']|SubscriptionService.UpdateParamsPaymentSettingsPaymentMethodOptionsAcssDebit" + ] + """ + This sub-hash contains details about the Canadian pre-authorized debit payment method options to pass to the invoice's PaymentIntent. + """ + bancontact: NotRequired[ + "Literal['']|SubscriptionService.UpdateParamsPaymentSettingsPaymentMethodOptionsBancontact" + ] + """ + This sub-hash contains details about the Bancontact payment method options to pass to the invoice's PaymentIntent. + """ + card: NotRequired[ + "Literal['']|SubscriptionService.UpdateParamsPaymentSettingsPaymentMethodOptionsCard" + ] + """ + This sub-hash contains details about the Card payment method options to pass to the invoice's PaymentIntent. + """ + customer_balance: NotRequired[ + "Literal['']|SubscriptionService.UpdateParamsPaymentSettingsPaymentMethodOptionsCustomerBalance" + ] + """ + This sub-hash contains details about the Bank transfer payment method options to pass to the invoice's PaymentIntent. + """ + konbini: NotRequired[ + "Literal['']|SubscriptionService.UpdateParamsPaymentSettingsPaymentMethodOptionsKonbini" + ] + """ + This sub-hash contains details about the Konbini payment method options to pass to the invoice's PaymentIntent. + """ + us_bank_account: NotRequired[ + "Literal['']|SubscriptionService.UpdateParamsPaymentSettingsPaymentMethodOptionsUsBankAccount" + ] + """ + This sub-hash contains details about the ACH direct debit payment method options to pass to the invoice's PaymentIntent. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsAcssDebit(TypedDict): + mandate_options: NotRequired[ + "SubscriptionService.UpdateParamsPaymentSettingsPaymentMethodOptionsAcssDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Verification method for the intent + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsAcssDebitMandateOptions( + TypedDict, + ): + transaction_type: NotRequired["Literal['business', 'personal']"] + """ + Transaction type of the mandate. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsBancontact(TypedDict): + preferred_language: NotRequired["Literal['de', 'en', 'fr', 'nl']"] + """ + Preferred language of the Bancontact authorization page that the customer is redirected to. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsCard(TypedDict): + mandate_options: NotRequired[ + "SubscriptionService.UpdateParamsPaymentSettingsPaymentMethodOptionsCardMandateOptions" + ] + """ + Configuration options for setting up an eMandate for cards issued in India. + """ + network: NotRequired[ + "Literal['amex', 'cartes_bancaires', 'diners', 'discover', 'eftpos_au', 'interac', 'jcb', 'mastercard', 'unionpay', 'unknown', 'visa']" + ] + """ + Selected network to process this Subscription on. Depends on the available networks of the card attached to the Subscription. Can be only set confirm-time. + """ + request_three_d_secure: NotRequired[ + "Literal['any', 'automatic', 'challenge']" + ] + """ + We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsCardMandateOptions( + TypedDict, + ): + amount: NotRequired["int"] + """ + Amount to be charged for future payments. + """ + amount_type: NotRequired["Literal['fixed', 'maximum']"] + """ + One of `fixed` or `maximum`. If `fixed`, the `amount` param refers to the exact amount to be charged in future payments. If `maximum`, the amount charged can be up to the value passed for the `amount` param. + """ + description: NotRequired["str"] + """ + A description of the mandate or subscription that is meant to be displayed to the customer. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsCustomerBalance( + TypedDict, + ): + bank_transfer: NotRequired[ + "SubscriptionService.UpdateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer" + ] + """ + Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + """ + funding_type: NotRequired["str"] + """ + The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransfer( + TypedDict, + ): + eu_bank_transfer: NotRequired[ + "SubscriptionService.UpdateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer" + ] + """ + Configuration for eu_bank_transfer funding type. + """ + type: NotRequired["str"] + """ + The bank transfer type that can be used for funding. Permitted values include: `eu_bank_transfer`, `gb_bank_transfer`, `jp_bank_transfer`, `mx_bank_transfer`, or `us_bank_transfer`. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer( + TypedDict, + ): + country: str + """ + The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsKonbini(TypedDict): + pass + + class UpdateParamsPaymentSettingsPaymentMethodOptionsUsBankAccount( + TypedDict, + ): + financial_connections: NotRequired[ + "SubscriptionService.UpdateParamsPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnections" + ] + """ + Additional fields for Financial Connections Session creation + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Verification method for the intent + """ + + class UpdateParamsPaymentSettingsPaymentMethodOptionsUsBankAccountFinancialConnections( + TypedDict, + ): + permissions: NotRequired[ + "List[Literal['balances', 'ownership', 'payment_method', 'transactions']]" + ] + """ + The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + """ + prefetch: NotRequired["List[Literal['balances', 'transactions']]"] + """ + List of data features that you would like to retrieve upon account creation. + """ + + class UpdateParamsPendingInvoiceItemInterval(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies invoicing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between invoices. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). + """ + + class UpdateParamsTransferData(TypedDict): + amount_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + """ + destination: str + """ + ID of an existing, connected Stripe account. + """ + + class UpdateParamsTrialSettings(TypedDict): + end_behavior: "SubscriptionService.UpdateParamsTrialSettingsEndBehavior" + """ + Defines how the subscription should behave when the user's free trial ends. + """ + + class UpdateParamsTrialSettingsEndBehavior(TypedDict): + missing_payment_method: Literal["cancel", "create_invoice", "pause"] + """ + Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + """ + + def cancel( + self, + subscription_exposed_id: str, + params: "SubscriptionService.CancelParams" = {}, + options: RequestOptions = {}, + ) -> Subscription: + """ + Cancels a customer's subscription immediately. The customer will not be charged again for the subscription. + + Note, however, that any pending invoice items that you've created will still be charged for at the end of the period, unless manually [deleted](https://stripe.com/docs/api#delete_invoiceitem). If you've set the subscription to cancel at the end of the period, any pending prorations will also be left in place and collected at the end of the period. But if the subscription is set to cancel immediately, pending prorations will be removed. + + By default, upon subscription cancellation, Stripe will stop automatic collection of all finalized invoices for the customer. This is intended to prevent unexpected payment attempts after the customer has canceled a subscription. However, you can resume automatic collection of the invoices manually after subscription cancellation to have us proceed. Or, you could check for unpaid invoices before allowing the customer to cancel the subscription at all. + """ + return cast( + Subscription, + self._requestor.request( + "delete", + "/v1/subscriptions/{subscription_exposed_id}".format( + subscription_exposed_id=_util.sanitize_id( + subscription_exposed_id + ), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + subscription_exposed_id: str, + params: "SubscriptionService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Subscription: + """ + Retrieves the subscription with the given ID. + """ + return cast( + Subscription, + self._requestor.request( + "get", + "/v1/subscriptions/{subscription_exposed_id}".format( + subscription_exposed_id=_util.sanitize_id( + subscription_exposed_id + ), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + subscription_exposed_id: str, + params: "SubscriptionService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Subscription: + """ + Updates an existing subscription to match the specified parameters. + When changing prices or quantities, we optionally prorate the price we charge next month to make up for any price changes. + To preview how the proration is calculated, use the [upcoming invoice](https://stripe.com/docs/api/invoices/upcoming) endpoint. + + By default, we prorate subscription changes. For example, if a customer signs up on May 1 for a 100 price, they'll be billed 100 immediately. If on May 15 they switch to a 200 price, then on June 1 they'll be billed 250 (200 for a renewal of her subscription, plus a 50 prorating adjustment for half of the previous month's 100 difference). Similarly, a downgrade generates a credit that is applied to the next invoice. We also prorate when you make quantity changes. + + Switching prices does not normally change the billing date or generate an immediate charge unless: + + + The billing interval is changed (for example, from monthly to yearly). + The subscription moves from free to paid, or paid to free. + A trial starts or ends. + + + In these cases, we apply a credit for the unused time on the previous price, immediately charge the customer using the new price, and reset the billing date. + + If you want to charge for an upgrade immediately, pass proration_behavior as always_invoice to create prorations, automatically invoice the customer for those proration adjustments, and attempt to collect payment. If you pass create_prorations, the prorations are created but not automatically invoiced. If you want to bill the customer for the prorations before the subscription's renewal date, you need to manually [invoice the customer](https://stripe.com/docs/api/invoices/create). + + If you don't want to prorate, set the proration_behavior option to none. With this option, the customer is billed 100 on May 1 and 200 on June 1. Similarly, if you set proration_behavior to none when switching between different billing intervals (for example, from monthly to yearly), we don't generate any credits for the old subscription's unused time. We still reset the billing date and bill immediately for the new subscription. + + Updating the quantity on a subscription many times in an hour may result in [rate limiting. If you need to bill for a frequently changing quantity, consider integrating usage-based billing](https://stripe.com/docs/rate-limits) instead. + """ + return cast( + Subscription, + self._requestor.request( + "post", + "/v1/subscriptions/{subscription_exposed_id}".format( + subscription_exposed_id=_util.sanitize_id( + subscription_exposed_id + ), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def delete_discount( + self, + subscription_exposed_id: str, + params: "SubscriptionService.DeleteDiscountParams" = {}, + options: RequestOptions = {}, + ) -> Discount: + """ + Removes the currently applied discount on a subscription. + """ + return cast( + Discount, + self._requestor.request( + "delete", + "/v1/subscriptions/{subscription_exposed_id}/discount".format( + subscription_exposed_id=_util.sanitize_id( + subscription_exposed_id + ), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "SubscriptionService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Subscription]: + """ + By default, returns a list of subscriptions that have not been canceled. In order to list canceled subscriptions, specify status=canceled. + """ + return cast( + ListObject[Subscription], + self._requestor.request( + "get", + "/v1/subscriptions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "SubscriptionService.CreateParams", + options: RequestOptions = {}, + ) -> Subscription: + """ + Creates a new subscription on an existing customer. Each customer can have up to 500 active or scheduled subscriptions. + + When you create a subscription with collection_method=charge_automatically, the first invoice is finalized as part of the request. + The payment_behavior parameter determines the exact behavior of the initial payment. + + To start subscriptions where the first invoice always begins in a draft status, use [subscription schedules](https://stripe.com/docs/billing/subscriptions/subscription-schedules#managing) instead. + Schedules provide the flexibility to model more complex billing configurations that change over time. + """ + return cast( + Subscription, + self._requestor.request( + "post", + "/v1/subscriptions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def search( + self, + params: "SubscriptionService.SearchParams", + options: RequestOptions = {}, + ) -> SearchResultObject[Subscription]: + """ + Search for subscriptions you've previously created using Stripe's [Search Query Language](https://stripe.com/docs/search#search-query-language). + Don't use search in read-after-write flows where strict consistency is necessary. Under normal operating + conditions, data is searchable in less than a minute. Occasionally, propagation of new or updated data can be up + to an hour behind during outages. Search functionality is not available to merchants in India. + """ + return cast( + SearchResultObject[Subscription], + self._requestor.request( + "get", + "/v1/subscriptions/search", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def resume( + self, + subscription: str, + params: "SubscriptionService.ResumeParams" = {}, + options: RequestOptions = {}, + ) -> Subscription: + """ + Initiates resumption of a paused subscription, optionally resetting the billing cycle anchor and creating prorations. If a resumption invoice is generated, it must be paid or marked uncollectible before the subscription will be unpaused. If payment succeeds the subscription will become active, and if payment fails the subscription will be past_due. The resumption invoice will void automatically if not paid by the expiration date. + """ + return cast( + Subscription, + self._requestor.request( + "post", + "/v1/subscriptions/{subscription}/resume".format( + subscription=_util.sanitize_id(subscription), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_tax_code.py b/stripe/_tax_code.py index dca87c853..42b142c72 100644 --- a/stripe/_tax_code.py +++ b/stripe/_tax_code.py @@ -3,7 +3,7 @@ from stripe._list_object import ListObject from stripe._listable_api_resource import ListableAPIResource from stripe._request_options import RequestOptions -from typing import ClassVar, List, Optional +from typing import ClassVar, List from typing_extensions import Literal, NotRequired, Unpack @@ -57,13 +57,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "TaxCode.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["TaxCode.ListParams"] ) -> ListObject["TaxCode"]: """ A list of [all tax codes available](https://stripe.com/docs/tax/tax-categories) to add to Products in order to allow specific tax calculations. @@ -71,9 +65,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_tax_code_service.py b/stripe/_tax_code_service.py new file mode 100644 index 000000000..a766dbfae --- /dev/null +++ b/stripe/_tax_code_service.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe._tax_code import TaxCode +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class TaxCodeService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "TaxCodeService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[TaxCode]: + """ + A list of [all tax codes available](https://stripe.com/docs/tax/tax-categories) to add to Products in order to allow specific tax calculations. + """ + return cast( + ListObject[TaxCode], + self._requestor.request( + "get", + "/v1/tax_codes", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + id: str, + params: "TaxCodeService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> TaxCode: + """ + Retrieves the details of an existing tax code. Supply the unique tax code ID and Stripe will return the corresponding tax code information. + """ + return cast( + TaxCode, + self._requestor.request( + "get", + "/v1/tax_codes/{id}".format(id=_util.sanitize_id(id)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_tax_id.py b/stripe/_tax_id.py index bee80e64e..bf8dcbcc8 100644 --- a/stripe/_tax_id.py +++ b/stripe/_tax_id.py @@ -154,7 +154,7 @@ def instance_url(self): return "%s/%s/tax_ids/%s" % (base, cust_extn, extn) @classmethod - def retrieve(cls, id, api_key=None, **params): + def retrieve(cls, id, **params): raise NotImplementedError( "Can't retrieve a tax id without a customer ID. Use customer.retrieve_tax_id('tax_id')" ) diff --git a/stripe/_tax_rate.py b/stripe/_tax_rate.py index 1a7334c2e..6e5e20d04 100644 --- a/stripe/_tax_rate.py +++ b/stripe/_tax_rate.py @@ -245,16 +245,7 @@ class RetrieveParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "TaxRate.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "TaxRate": + def create(cls, **params: Unpack["TaxRate.CreateParams"]) -> "TaxRate": """ Creates a new tax rate. """ @@ -263,23 +254,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "TaxRate.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["TaxRate.ListParams"] ) -> ListObject["TaxRate"]: """ Returns a list of your tax rates. Tax rates are returned sorted by creation date, with the most recently created tax rates appearing first. @@ -287,9 +268,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_tax_rate_service.py b/stripe/_tax_rate_service.py new file mode 100644 index 000000000..14c5d795d --- /dev/null +++ b/stripe/_tax_rate_service.py @@ -0,0 +1,239 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe._tax_rate import TaxRate +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class TaxRateService(StripeService): + class CreateParams(TypedDict): + active: NotRequired["bool"] + """ + Flag determining whether the tax rate is active or inactive (archived). Inactive tax rates cannot be used with new applications or Checkout Sessions, but will still work for subscriptions and invoices that already have it set. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the tax rate for your internal use only. It will not be visible to your customers. + """ + display_name: str + """ + The display name of the tax rate, which will be shown to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + inclusive: bool + """ + This specifies if the tax rate is inclusive or exclusive. + """ + jurisdiction: NotRequired["str"] + """ + The jurisdiction for the tax rate. You can use this label field for tax reporting purposes. It also appears on your customer's invoice. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + percentage: float + """ + This represents the tax rate percent out of 100. + """ + state: NotRequired["str"] + """ + [ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2:US), without country prefix. For example, "NY" for New York, United States. + """ + tax_type: NotRequired[ + "Literal['amusement_tax', 'communications_tax', 'gst', 'hst', 'igst', 'jct', 'lease_tax', 'pst', 'qst', 'rst', 'sales_tax', 'service_tax', 'vat']" + ] + """ + The high-level tax type, such as `vat` or `sales_tax`. + """ + + class ListParams(TypedDict): + active: NotRequired["bool"] + """ + Optional flag to filter by tax rates that are either active or inactive (archived). + """ + created: NotRequired["TaxRateService.ListParamsCreated|int"] + """ + Optional range for filtering created date. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + inclusive: NotRequired["bool"] + """ + Optional flag to filter by tax rates that are inclusive (or those that are not inclusive). + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + active: NotRequired["bool"] + """ + Flag determining whether the tax rate is active or inactive (archived). Inactive tax rates cannot be used with new applications or Checkout Sessions, but will still work for subscriptions and invoices that already have it set. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the tax rate for your internal use only. It will not be visible to your customers. + """ + display_name: NotRequired["str"] + """ + The display name of the tax rate, which will be shown to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + jurisdiction: NotRequired["str"] + """ + The jurisdiction for the tax rate. You can use this label field for tax reporting purposes. It also appears on your customer's invoice. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + state: NotRequired["str"] + """ + [ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2:US), without country prefix. For example, "NY" for New York, United States. + """ + tax_type: NotRequired[ + "Literal['amusement_tax', 'communications_tax', 'gst', 'hst', 'igst', 'jct', 'lease_tax', 'pst', 'qst', 'rst', 'sales_tax', 'service_tax', 'vat']" + ] + """ + The high-level tax type, such as `vat` or `sales_tax`. + """ + + def list( + self, + params: "TaxRateService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[TaxRate]: + """ + Returns a list of your tax rates. Tax rates are returned sorted by creation date, with the most recently created tax rates appearing first. + """ + return cast( + ListObject[TaxRate], + self._requestor.request( + "get", + "/v1/tax_rates", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "TaxRateService.CreateParams", + options: RequestOptions = {}, + ) -> TaxRate: + """ + Creates a new tax rate. + """ + return cast( + TaxRate, + self._requestor.request( + "post", + "/v1/tax_rates", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + tax_rate: str, + params: "TaxRateService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> TaxRate: + """ + Retrieves a tax rate with the given ID + """ + return cast( + TaxRate, + self._requestor.request( + "get", + "/v1/tax_rates/{tax_rate}".format( + tax_rate=_util.sanitize_id(tax_rate), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + tax_rate: str, + params: "TaxRateService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> TaxRate: + """ + Updates an existing tax rate. + """ + return cast( + TaxRate, + self._requestor.request( + "post", + "/v1/tax_rates/{tax_rate}".format( + tax_rate=_util.sanitize_id(tax_rate), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_tax_service.py b/stripe/_tax_service.py new file mode 100644 index 000000000..05b45e4fd --- /dev/null +++ b/stripe/_tax_service.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.tax._calculation_service import CalculationService +from stripe.tax._registration_service import RegistrationService +from stripe.tax._settings_service import SettingsService +from stripe.tax._transaction_service import TransactionService + + +class TaxService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.calculations = CalculationService(self._requestor) + self.registrations = RegistrationService(self._requestor) + self.settings = SettingsService(self._requestor) + self.transactions = TransactionService(self._requestor) diff --git a/stripe/_terminal_service.py b/stripe/_terminal_service.py new file mode 100644 index 000000000..a7dc46543 --- /dev/null +++ b/stripe/_terminal_service.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.terminal._configuration_service import ConfigurationService +from stripe.terminal._connection_token_service import ConnectionTokenService +from stripe.terminal._location_service import LocationService +from stripe.terminal._reader_service import ReaderService + + +class TerminalService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.configurations = ConfigurationService(self._requestor) + self.connection_tokens = ConnectionTokenService(self._requestor) + self.locations = LocationService(self._requestor) + self.readers = ReaderService(self._requestor) diff --git a/stripe/_test_helpers_service.py b/stripe/_test_helpers_service.py new file mode 100644 index 000000000..b21181768 --- /dev/null +++ b/stripe/_test_helpers_service.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.test_helpers._customer_service import CustomerService +from stripe.test_helpers._issuing_service import IssuingService +from stripe.test_helpers._refund_service import RefundService +from stripe.test_helpers._terminal_service import TerminalService +from stripe.test_helpers._test_clock_service import TestClockService +from stripe.test_helpers._treasury_service import TreasuryService + + +class TestHelpersService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.customers = CustomerService(self._requestor) + self.issuing = IssuingService(self._requestor) + self.refunds = RefundService(self._requestor) + self.terminal = TerminalService(self._requestor) + self.test_clocks = TestClockService(self._requestor) + self.treasury = TreasuryService(self._requestor) diff --git a/stripe/_token.py b/stripe/_token.py index e1ae30087..f44317428 100644 --- a/stripe/_token.py +++ b/stripe/_token.py @@ -1068,16 +1068,7 @@ class RetrieveParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Token.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Token": + def create(cls, **params: Unpack["Token.CreateParams"]) -> "Token": """ Creates a single-use token that represents a bank account's details. You can use this token with any API method in place of a bank account dictionary. You can only use this token once. To do so, attach it to a [Custom account](https://stripe.com/docs/api#accounts). @@ -1087,10 +1078,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) diff --git a/stripe/_token_service.py b/stripe/_token_service.py new file mode 100644 index 000000000..1712402a2 --- /dev/null +++ b/stripe/_token_service.py @@ -0,0 +1,1044 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe._token import Token +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class TokenService(StripeService): + class CreateParams(TypedDict): + account: NotRequired["TokenService.CreateParamsAccount"] + """ + Information for the account this token represents. + """ + bank_account: NotRequired["TokenService.CreateParamsBankAccount"] + """ + The bank account this token will represent. + """ + card: NotRequired["TokenService.CreateParamsCard|str"] + """ + The card this token will represent. If you also pass in a customer, the card must be the ID of a card belonging to the customer. Otherwise, if you do not pass in a customer, this is a dictionary containing a user's credit card details, with the options described below. + """ + customer: NotRequired["str"] + """ + Create a token for the customer, which is owned by the application's account. You can only use this with an [OAuth access token](https://stripe.com/docs/connect/standard-accounts) or [Stripe-Account header](https://stripe.com/docs/connect/authentication). Learn more about [cloning saved payment methods](https://stripe.com/docs/connect/cloning-saved-payment-methods). + """ + cvc_update: NotRequired["TokenService.CreateParamsCvcUpdate"] + """ + The updated CVC value this token represents. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + person: NotRequired["TokenService.CreateParamsPerson"] + """ + Information for the person this token represents. + """ + pii: NotRequired["TokenService.CreateParamsPii"] + """ + The PII this token represents. + """ + + class CreateParamsAccount(TypedDict): + business_type: NotRequired[ + "Literal['company', 'government_entity', 'individual', 'non_profit']" + ] + """ + The business type. + """ + company: NotRequired["TokenService.CreateParamsAccountCompany"] + """ + Information about the company or business. + """ + individual: NotRequired["TokenService.CreateParamsAccountIndividual"] + """ + Information about the person represented by the account. + """ + tos_shown_and_accepted: NotRequired["bool"] + """ + Whether the user described by the data in the token has been shown [the Stripe Connected Account Agreement](https://stripe.com/docs/connect/account-tokens#stripe-connected-account-agreement). When creating an account token to create a new Connect account, this value must be `true`. + """ + + class CreateParamsAccountCompany(TypedDict): + address: NotRequired["TokenService.CreateParamsAccountCompanyAddress"] + """ + The company's primary address. + """ + address_kana: NotRequired[ + "TokenService.CreateParamsAccountCompanyAddressKana" + ] + """ + The Kana variation of the company's primary address (Japan only). + """ + address_kanji: NotRequired[ + "TokenService.CreateParamsAccountCompanyAddressKanji" + ] + """ + The Kanji variation of the company's primary address (Japan only). + """ + directors_provided: NotRequired["bool"] + """ + Whether the company's directors have been provided. Set this Boolean to `true` after creating all the company's directors with [the Persons API](https://stripe.com/docs/api/persons) for accounts with a `relationship.director` requirement. This value is not automatically set to `true` after creating directors, so it needs to be updated to indicate all directors have been provided. + """ + executives_provided: NotRequired["bool"] + """ + Whether the company's executives have been provided. Set this Boolean to `true` after creating all the company's executives with [the Persons API](https://stripe.com/docs/api/persons) for accounts with a `relationship.executive` requirement. + """ + export_license_id: NotRequired["str"] + """ + The export license ID number of the company, also referred as Import Export Code (India only). + """ + export_purpose_code: NotRequired["str"] + """ + The purpose code to use for export transactions (India only). + """ + name: NotRequired["str"] + """ + The company's legal name. + """ + name_kana: NotRequired["str"] + """ + The Kana variation of the company's legal name (Japan only). + """ + name_kanji: NotRequired["str"] + """ + The Kanji variation of the company's legal name (Japan only). + """ + owners_provided: NotRequired["bool"] + """ + Whether the company's owners have been provided. Set this Boolean to `true` after creating all the company's owners with [the Persons API](https://stripe.com/docs/api/persons) for accounts with a `relationship.owner` requirement. + """ + ownership_declaration: NotRequired[ + "TokenService.CreateParamsAccountCompanyOwnershipDeclaration" + ] + """ + This hash is used to attest that the beneficial owner information provided to Stripe is both current and correct. + """ + ownership_declaration_shown_and_signed: NotRequired["bool"] + """ + Whether the user described by the data in the token has been shown the Ownership Declaration and indicated that it is correct. + """ + phone: NotRequired["str"] + """ + The company's phone number (used for verification). + """ + registration_number: NotRequired["str"] + """ + The identification number given to a company when it is registered or incorporated, if distinct from the identification number used for filing taxes. (Examples are the CIN for companies and LLP IN for partnerships in India, and the Company Registration Number in Hong Kong). + """ + structure: NotRequired[ + "Literal['']|Literal['free_zone_establishment', 'free_zone_llc', 'government_instrumentality', 'governmental_unit', 'incorporated_non_profit', 'incorporated_partnership', 'limited_liability_partnership', 'llc', 'multi_member_llc', 'private_company', 'private_corporation', 'private_partnership', 'public_company', 'public_corporation', 'public_partnership', 'registered_charity', 'single_member_llc', 'sole_establishment', 'sole_proprietorship', 'tax_exempt_government_instrumentality', 'unincorporated_association', 'unincorporated_non_profit', 'unincorporated_partnership']" + ] + """ + The category identifying the legal structure of the company or legal entity. See [Business structure](https://stripe.com/docs/connect/identity-verification#business-structure) for more details. Pass an empty string to unset this value. + """ + tax_id: NotRequired["str"] + """ + The business ID number of the company, as appropriate for the company's country. (Examples are an Employer ID Number in the U.S., a Business Number in Canada, or a Company Number in the UK.) + """ + tax_id_registrar: NotRequired["str"] + """ + The jurisdiction in which the `tax_id` is registered (Germany-based companies only). + """ + vat_id: NotRequired["str"] + """ + The VAT number of the company. + """ + verification: NotRequired[ + "TokenService.CreateParamsAccountCompanyVerification" + ] + """ + Information on the verification state of the company. + """ + + class CreateParamsAccountCompanyAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsAccountCompanyAddressKana(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class CreateParamsAccountCompanyAddressKanji(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class CreateParamsAccountCompanyOwnershipDeclaration(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the beneficial owner attestation was made. + """ + ip: NotRequired["str"] + """ + The IP address from which the beneficial owner attestation was made. + """ + user_agent: NotRequired["str"] + """ + The user agent of the browser from which the beneficial owner attestation was made. + """ + + class CreateParamsAccountCompanyVerification(TypedDict): + document: NotRequired[ + "TokenService.CreateParamsAccountCompanyVerificationDocument" + ] + """ + A document verifying the business. + """ + + class CreateParamsAccountCompanyVerificationDocument(TypedDict): + back: NotRequired["str"] + """ + The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class CreateParamsAccountIndividual(TypedDict): + address: NotRequired[ + "TokenService.CreateParamsAccountIndividualAddress" + ] + """ + The individual's primary address. + """ + address_kana: NotRequired[ + "TokenService.CreateParamsAccountIndividualAddressKana" + ] + """ + The Kana variation of the the individual's primary address (Japan only). + """ + address_kanji: NotRequired[ + "TokenService.CreateParamsAccountIndividualAddressKanji" + ] + """ + The Kanji variation of the the individual's primary address (Japan only). + """ + dob: NotRequired[ + "Literal['']|TokenService.CreateParamsAccountIndividualDob" + ] + """ + The individual's date of birth. + """ + email: NotRequired["str"] + """ + The individual's email address. + """ + first_name: NotRequired["str"] + """ + The individual's first name. + """ + first_name_kana: NotRequired["str"] + """ + The Kana variation of the the individual's first name (Japan only). + """ + first_name_kanji: NotRequired["str"] + """ + The Kanji variation of the individual's first name (Japan only). + """ + full_name_aliases: NotRequired["Literal['']|List[str]"] + """ + A list of alternate names or aliases that the individual is known by. + """ + gender: NotRequired["str"] + """ + The individual's gender (International regulations require either "male" or "female"). + """ + id_number: NotRequired["str"] + """ + The government-issued ID number of the individual, as appropriate for the representative's country. (Examples are a Social Security Number in the U.S., or a Social Insurance Number in Canada). Instead of the number itself, you can also provide a [PII token created with Stripe.js](https://stripe.com/docs/js/tokens/create_token?type=pii). + """ + id_number_secondary: NotRequired["str"] + """ + The government-issued secondary ID number of the individual, as appropriate for the representative's country, will be used for enhanced verification checks. In Thailand, this would be the laser code found on the back of an ID card. Instead of the number itself, you can also provide a [PII token created with Stripe.js](https://stripe.com/docs/js/tokens/create_token?type=pii). + """ + last_name: NotRequired["str"] + """ + The individual's last name. + """ + last_name_kana: NotRequired["str"] + """ + The Kana variation of the individual's last name (Japan only). + """ + last_name_kanji: NotRequired["str"] + """ + The Kanji variation of the individual's last name (Japan only). + """ + maiden_name: NotRequired["str"] + """ + The individual's maiden name. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + phone: NotRequired["str"] + """ + The individual's phone number. + """ + political_exposure: NotRequired["Literal['existing', 'none']"] + """ + Indicates if the person or any of their representatives, family members, or other closely related persons, declares that they hold or have held an important public job or function, in any jurisdiction. + """ + registered_address: NotRequired[ + "TokenService.CreateParamsAccountIndividualRegisteredAddress" + ] + """ + The individual's registered address. + """ + ssn_last_4: NotRequired["str"] + """ + The last four digits of the individual's Social Security Number (U.S. only). + """ + verification: NotRequired[ + "TokenService.CreateParamsAccountIndividualVerification" + ] + """ + The individual's verification document information. + """ + + class CreateParamsAccountIndividualAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsAccountIndividualAddressKana(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class CreateParamsAccountIndividualAddressKanji(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class CreateParamsAccountIndividualDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class CreateParamsAccountIndividualRegisteredAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsAccountIndividualVerification(TypedDict): + additional_document: NotRequired[ + "TokenService.CreateParamsAccountIndividualVerificationAdditionalDocument" + ] + """ + A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. + """ + document: NotRequired[ + "TokenService.CreateParamsAccountIndividualVerificationDocument" + ] + """ + An identifying document, either a passport or local ID card. + """ + + class CreateParamsAccountIndividualVerificationAdditionalDocument( + TypedDict, + ): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class CreateParamsAccountIndividualVerificationDocument(TypedDict): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class CreateParamsBankAccount(TypedDict): + account_holder_name: NotRequired["str"] + """ + The name of the person or business that owns the bank account.This field is required when attaching the bank account to a `Customer` object. + """ + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + The type of entity that holds the account. It can be `company` or `individual`. This field is required when attaching the bank account to a `Customer` object. + """ + account_number: str + """ + The account number for the bank account, in string form. Must be a checking account. + """ + account_type: NotRequired[ + "Literal['checking', 'futsu', 'savings', 'toza']" + ] + """ + The bank account type. This can only be `checking` or `savings` in most countries. In Japan, this can only be `futsu` or `toza`. + """ + country: str + """ + The country in which the bank account is located. + """ + currency: NotRequired["str"] + """ + The currency the bank account is in. This must be a country/currency pairing that [Stripe supports.](https://stripe.com/docs/payouts) + """ + routing_number: NotRequired["str"] + """ + The routing number, sort code, or other country-appropriateinstitution number for the bank account. For US bank accounts, this is required and should bethe ACH routing number, not the wire routing number. If you are providing an IBAN for`account_number`, this field is not required. + """ + + class CreateParamsCard(TypedDict): + address_city: NotRequired["str"] + """ + City / District / Suburb / Town / Village. + """ + address_country: NotRequired["str"] + """ + Billing address country, if provided. + """ + address_line1: NotRequired["str"] + """ + Address line 1 (Street address / PO Box / Company name). + """ + address_line2: NotRequired["str"] + """ + Address line 2 (Apartment / Suite / Unit / Building). + """ + address_state: NotRequired["str"] + """ + State / County / Province / Region. + """ + address_zip: NotRequired["str"] + """ + ZIP or postal code. + """ + currency: NotRequired["str"] + """ + Required in order to add the card to an account; in all other cases, this parameter is not used. When added to an account, the card (which must be a debit card) can be used as a transfer destination for funds in this currency. + """ + cvc: NotRequired["str"] + """ + Card security code. Highly recommended to always include this value. + """ + exp_month: str + """ + Two-digit number representing the card's expiration month. + """ + exp_year: str + """ + Two- or four-digit number representing the card's expiration year. + """ + name: NotRequired["str"] + """ + Cardholder's full name. + """ + number: str + """ + The card number, as a string without any separators. + """ + + class CreateParamsCvcUpdate(TypedDict): + cvc: str + """ + The CVC value, in string form. + """ + + class CreateParamsPerson(TypedDict): + additional_tos_acceptances: NotRequired[ + "TokenService.CreateParamsPersonAdditionalTosAcceptances" + ] + """ + Details on the legal guardian's acceptance of the required Stripe agreements. + """ + address: NotRequired["TokenService.CreateParamsPersonAddress"] + """ + The person's address. + """ + address_kana: NotRequired["TokenService.CreateParamsPersonAddressKana"] + """ + The Kana variation of the person's address (Japan only). + """ + address_kanji: NotRequired[ + "TokenService.CreateParamsPersonAddressKanji" + ] + """ + The Kanji variation of the person's address (Japan only). + """ + dob: NotRequired["Literal['']|TokenService.CreateParamsPersonDob"] + """ + The person's date of birth. + """ + documents: NotRequired["TokenService.CreateParamsPersonDocuments"] + """ + Documents that may be submitted to satisfy various informational requests. + """ + email: NotRequired["str"] + """ + The person's email address. + """ + first_name: NotRequired["str"] + """ + The person's first name. + """ + first_name_kana: NotRequired["str"] + """ + The Kana variation of the person's first name (Japan only). + """ + first_name_kanji: NotRequired["str"] + """ + The Kanji variation of the person's first name (Japan only). + """ + full_name_aliases: NotRequired["Literal['']|List[str]"] + """ + A list of alternate names or aliases that the person is known by. + """ + gender: NotRequired["str"] + """ + The person's gender (International regulations require either "male" or "female"). + """ + id_number: NotRequired["str"] + """ + The person's ID number, as appropriate for their country. For example, a social security number in the U.S., social insurance number in Canada, etc. Instead of the number itself, you can also provide a [PII token provided by Stripe.js](https://stripe.com/docs/js/tokens/create_token?type=pii). + """ + id_number_secondary: NotRequired["str"] + """ + The person's secondary ID number, as appropriate for their country, will be used for enhanced verification checks. In Thailand, this would be the laser code found on the back of an ID card. Instead of the number itself, you can also provide a [PII token provided by Stripe.js](https://stripe.com/docs/js/tokens/create_token?type=pii). + """ + last_name: NotRequired["str"] + """ + The person's last name. + """ + last_name_kana: NotRequired["str"] + """ + The Kana variation of the person's last name (Japan only). + """ + last_name_kanji: NotRequired["str"] + """ + The Kanji variation of the person's last name (Japan only). + """ + maiden_name: NotRequired["str"] + """ + The person's maiden name. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + nationality: NotRequired["str"] + """ + The country where the person is a national. Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)), or "XX" if unavailable. + """ + phone: NotRequired["str"] + """ + The person's phone number. + """ + political_exposure: NotRequired["str"] + """ + Indicates if the person or any of their representatives, family members, or other closely related persons, declares that they hold or have held an important public job or function, in any jurisdiction. + """ + registered_address: NotRequired[ + "TokenService.CreateParamsPersonRegisteredAddress" + ] + """ + The person's registered address. + """ + relationship: NotRequired[ + "TokenService.CreateParamsPersonRelationship" + ] + """ + The relationship that this person has with the account's legal entity. + """ + ssn_last_4: NotRequired["str"] + """ + The last four digits of the person's Social Security number (U.S. only). + """ + verification: NotRequired[ + "TokenService.CreateParamsPersonVerification" + ] + """ + The person's verification status. + """ + + class CreateParamsPersonAdditionalTosAcceptances(TypedDict): + account: NotRequired[ + "TokenService.CreateParamsPersonAdditionalTosAcceptancesAccount" + ] + """ + Details on the legal guardian's acceptance of the main Stripe service agreement. + """ + + class CreateParamsPersonAdditionalTosAcceptancesAccount(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the account representative accepted the service agreement. + """ + ip: NotRequired["str"] + """ + The IP address from which the account representative accepted the service agreement. + """ + user_agent: NotRequired["Literal['']|str"] + """ + The user agent of the browser from which the account representative accepted the service agreement. + """ + + class CreateParamsPersonAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsPersonAddressKana(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class CreateParamsPersonAddressKanji(TypedDict): + city: NotRequired["str"] + """ + City or ward. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Block or building number. + """ + line2: NotRequired["str"] + """ + Building details. + """ + postal_code: NotRequired["str"] + """ + Postal code. + """ + state: NotRequired["str"] + """ + Prefecture. + """ + town: NotRequired["str"] + """ + Town or cho-me. + """ + + class CreateParamsPersonDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class CreateParamsPersonDocuments(TypedDict): + company_authorization: NotRequired[ + "TokenService.CreateParamsPersonDocumentsCompanyAuthorization" + ] + """ + One or more documents that demonstrate proof that this person is authorized to represent the company. + """ + passport: NotRequired[ + "TokenService.CreateParamsPersonDocumentsPassport" + ] + """ + One or more documents showing the person's passport page with photo and personal data. + """ + visa: NotRequired["TokenService.CreateParamsPersonDocumentsVisa"] + """ + One or more documents showing the person's visa required for living in the country where they are residing. + """ + + class CreateParamsPersonDocumentsCompanyAuthorization(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class CreateParamsPersonDocumentsPassport(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class CreateParamsPersonDocumentsVisa(TypedDict): + files: NotRequired["List[str]"] + """ + One or more document ids returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `account_requirement`. + """ + + class CreateParamsPersonRegisteredAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsPersonRelationship(TypedDict): + director: NotRequired["bool"] + """ + Whether the person is a director of the account's legal entity. Directors are typically members of the governing board of the company, or responsible for ensuring the company meets its regulatory obligations. + """ + executive: NotRequired["bool"] + """ + Whether the person has significant responsibility to control, manage, or direct the organization. + """ + legal_guardian: NotRequired["bool"] + """ + Whether the person is the legal guardian of the account's representative. + """ + owner: NotRequired["bool"] + """ + Whether the person is an owner of the account's legal entity. + """ + percent_ownership: NotRequired["Literal['']|float"] + """ + The percent owned by the person of the account's legal entity. + """ + representative: NotRequired["bool"] + """ + Whether the person is authorized as the primary representative of the account. This is the person nominated by the business to provide information about themselves, and general information about the account. There can only be one representative at any given time. At the time the account is created, this person should be set to the person responsible for opening the account. + """ + title: NotRequired["str"] + """ + The person's title (e.g., CEO, Support Engineer). + """ + + class CreateParamsPersonVerification(TypedDict): + additional_document: NotRequired[ + "TokenService.CreateParamsPersonVerificationAdditionalDocument" + ] + """ + A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. + """ + document: NotRequired[ + "TokenService.CreateParamsPersonVerificationDocument" + ] + """ + An identifying document, either a passport or local ID card. + """ + + class CreateParamsPersonVerificationAdditionalDocument(TypedDict): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class CreateParamsPersonVerificationDocument(TypedDict): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. The uploaded file needs to be a color image (smaller than 8,000px by 8,000px), in JPG, PNG, or PDF format, and less than 10 MB in size. + """ + + class CreateParamsPii(TypedDict): + id_number: NotRequired["str"] + """ + The `id_number` for the PII, in string form. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def retrieve( + self, + token: str, + params: "TokenService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Token: + """ + Retrieves the token with the given ID. + """ + return cast( + Token, + self._requestor.request( + "get", + "/v1/tokens/{token}".format(token=_util.sanitize_id(token)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "TokenService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Token: + """ + Creates a single-use token that represents a bank account's details. + You can use this token with any API method in place of a bank account dictionary. You can only use this token once. To do so, attach it to a [Custom account](https://stripe.com/docs/api#accounts). + """ + return cast( + Token, + self._requestor.request( + "post", + "/v1/tokens", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_topup.py b/stripe/_topup.py index 1c6e66d4d..9bd03cda1 100644 --- a/stripe/_topup.py +++ b/stripe/_topup.py @@ -233,14 +233,7 @@ class RetrieveParams(RequestOptions): @classmethod def _cls_cancel( - cls, - topup: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Topup.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, topup: str, **params: Unpack["Topup.CancelParams"] ) -> "Topup": """ Cancels a top-up. Only pending top-ups can be canceled. @@ -252,37 +245,20 @@ def _cls_cancel( "/v1/topups/{topup}/cancel".format( topup=_util.sanitize_id(topup) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @overload @staticmethod - def cancel( - topup: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Topup.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Topup": + def cancel(topup: str, **params: Unpack["Topup.CancelParams"]) -> "Topup": """ Cancels a top-up. Only pending top-ups can be canceled. """ ... @overload - def cancel( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Topup.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Topup": + def cancel(self, **params: Unpack["Topup.CancelParams"]) -> "Topup": """ Cancels a top-up. Only pending top-ups can be canceled. """ @@ -290,11 +266,7 @@ def cancel( @class_method_variant("_cls_cancel") def cancel( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Topup.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Topup.CancelParams"] ) -> "Topup": """ Cancels a top-up. Only pending top-ups can be canceled. @@ -306,22 +278,12 @@ def cancel( # pyright: ignore[reportGeneralTypeIssues] "/v1/topups/{topup}/cancel".format( topup=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Topup.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Topup": + def create(cls, **params: Unpack["Topup.CreateParams"]) -> "Topup": """ Top up the balance of an account """ @@ -330,33 +292,18 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod - def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Topup.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> ListObject["Topup"]: + def list(cls, **params: Unpack["Topup.ListParams"]) -> ListObject["Topup"]: """ Returns a list of top-ups. """ result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_topup_service.py b/stripe/_topup_service.py new file mode 100644 index 000000000..89d3969a4 --- /dev/null +++ b/stripe/_topup_service.py @@ -0,0 +1,242 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe._topup import Topup +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class TopupService(StripeService): + class CancelParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CreateParams(TypedDict): + amount: int + """ + A positive integer representing how much to transfer. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + source: NotRequired["str"] + """ + The ID of a source to transfer funds from. For most users, this should be left unspecified which will use the bank account that was set up in the dashboard for the specified currency. In test mode, this can be a test bank token (see [Testing Top-ups](https://stripe.com/docs/connect/testing#testing-top-ups)). + """ + statement_descriptor: NotRequired["str"] + """ + Extra information about a top-up for the source's bank statement. Limited to 15 ASCII characters. + """ + transfer_group: NotRequired["str"] + """ + A string that identifies this top-up as part of a group. + """ + + class ListParams(TypedDict): + amount: NotRequired["TopupService.ListParamsAmount|int"] + """ + A positive integer representing how much to transfer. + """ + created: NotRequired["TopupService.ListParamsCreated|int"] + """ + A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired[ + "Literal['canceled', 'failed', 'pending', 'succeeded']" + ] + """ + Only return top-ups that have the given status. One of `canceled`, `failed`, `pending` or `succeeded`. + """ + + class ListParamsAmount(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + def list( + self, + params: "TopupService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Topup]: + """ + Returns a list of top-ups. + """ + return cast( + ListObject[Topup], + self._requestor.request( + "get", + "/v1/topups", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, params: "TopupService.CreateParams", options: RequestOptions = {} + ) -> Topup: + """ + Top up the balance of an account + """ + return cast( + Topup, + self._requestor.request( + "post", + "/v1/topups", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + topup: str, + params: "TopupService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Topup: + """ + Retrieves the details of a top-up that has previously been created. Supply the unique top-up ID that was returned from your previous request, and Stripe will return the corresponding top-up information. + """ + return cast( + Topup, + self._requestor.request( + "get", + "/v1/topups/{topup}".format(topup=_util.sanitize_id(topup)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + topup: str, + params: "TopupService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Topup: + """ + Updates the metadata of a top-up. Other top-up details are not editable by design. + """ + return cast( + Topup, + self._requestor.request( + "post", + "/v1/topups/{topup}".format(topup=_util.sanitize_id(topup)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def cancel( + self, + topup: str, + params: "TopupService.CancelParams" = {}, + options: RequestOptions = {}, + ) -> Topup: + """ + Cancels a top-up. Only pending top-ups can be canceled. + """ + return cast( + Topup, + self._requestor.request( + "post", + "/v1/topups/{topup}/cancel".format( + topup=_util.sanitize_id(topup), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_transfer.py b/stripe/_transfer.py index 198715758..a26cfebc4 100644 --- a/stripe/_transfer.py +++ b/stripe/_transfer.py @@ -275,16 +275,7 @@ class RetrieveReversalParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transfer.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Transfer": + def create(cls, **params: Unpack["Transfer.CreateParams"]) -> "Transfer": """ To send funds from your Stripe account to a connected account, you create a new transfer object. Your [Stripe balance](https://stripe.com/docs/api#balance) must be able to cover the transfer amount, or you'll receive an “Insufficient Funds” error. """ @@ -293,23 +284,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transfer.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Transfer.ListParams"] ) -> ListObject["Transfer"]: """ Returns a list of existing transfers sent to connected accounts. The transfers are returned in sorted order, with the most recently created transfers appearing first. @@ -317,9 +298,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -359,14 +337,7 @@ def retrieve( @classmethod def create_reversal( - cls, - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transfer.CreateReversalParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, id: str, **params: Unpack["Transfer.CreateReversalParams"] ) -> "Reversal": """ When you create a new reversal, you must specify a transfer to create it on. @@ -382,9 +353,6 @@ def create_reversal( "/v1/transfers/{id}/reversals".format( id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -394,12 +362,7 @@ def retrieve_reversal( cls, transfer: str, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transfer.RetrieveReversalParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Transfer.RetrieveReversalParams"] ) -> "Reversal": """ By default, you can see the 10 most recent reversals stored directly on the transfer object, but you can also retrieve details about a specific reversal stored on the transfer. @@ -412,9 +375,6 @@ def retrieve_reversal( transfer=_util.sanitize_id(transfer), id=_util.sanitize_id(id), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -424,12 +384,7 @@ def modify_reversal( cls, transfer: str, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transfer.ModifyReversalParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Transfer.ModifyReversalParams"] ) -> "Reversal": """ Updates the specified reversal by setting the values of the parameters passed. Any parameters not provided will be left unchanged. @@ -444,23 +399,13 @@ def modify_reversal( transfer=_util.sanitize_id(transfer), id=_util.sanitize_id(id), ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def list_reversals( - cls, - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transfer.ListReversalsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, id: str, **params: Unpack["Transfer.ListReversalsParams"] ) -> ListObject["Reversal"]: """ You can see a list of the reversals belonging to a specific transfer. Note that the 10 most recent reversals are always available by default on the transfer object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page through additional reversals. @@ -472,9 +417,6 @@ def list_reversals( "/v1/transfers/{id}/reversals".format( id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) diff --git a/stripe/_transfer_reversal_service.py b/stripe/_transfer_reversal_service.py new file mode 100644 index 000000000..5a91b5e08 --- /dev/null +++ b/stripe/_transfer_reversal_service.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._reversal import Reversal +from stripe._stripe_service import StripeService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class TransferReversalService(StripeService): + class CreateParams(TypedDict): + amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) representing how much of this transfer to reverse. Can only reverse up to the unreversed amount remaining of the transfer. Partial transfer reversals are only allowed for transfers to Stripe Accounts. Defaults to the entire transfer amount. + """ + description: NotRequired["str"] + """ + An arbitrary string which you can attach to a reversal object. It is displayed alongside the reversal in the Dashboard. This will be unset if you POST an empty value. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + refund_application_fee: NotRequired["bool"] + """ + Boolean indicating whether the application fee should be refunded when reversing this transfer. If a full transfer reversal is given, the full application fee will be refunded. Otherwise, the application fee will be refunded with an amount proportional to the amount of the transfer reversed. + """ + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + def list( + self, + id: str, + params: "TransferReversalService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Reversal]: + """ + You can see a list of the reversals belonging to a specific transfer. Note that the 10 most recent reversals are always available by default on the transfer object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page through additional reversals. + """ + return cast( + ListObject[Reversal], + self._requestor.request( + "get", + "/v1/transfers/{id}/reversals".format( + id=_util.sanitize_id(id) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + id: str, + params: "TransferReversalService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Reversal: + """ + When you create a new reversal, you must specify a transfer to create it on. + + When reversing transfers, you can optionally reverse part of the transfer. You can do so as many times as you wish until the entire transfer has been reversed. + + Once entirely reversed, a transfer can't be reversed again. This method will return an error when called on an already-reversed transfer, or when trying to reverse more money than is left on a transfer. + """ + return cast( + Reversal, + self._requestor.request( + "post", + "/v1/transfers/{id}/reversals".format( + id=_util.sanitize_id(id) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + transfer: str, + id: str, + params: "TransferReversalService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Reversal: + """ + By default, you can see the 10 most recent reversals stored directly on the transfer object, but you can also retrieve details about a specific reversal stored on the transfer. + """ + return cast( + Reversal, + self._requestor.request( + "get", + "/v1/transfers/{transfer}/reversals/{id}".format( + transfer=_util.sanitize_id(transfer), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + transfer: str, + id: str, + params: "TransferReversalService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Reversal: + """ + Updates the specified reversal by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + + This request only accepts metadata and description as arguments. + """ + return cast( + Reversal, + self._requestor.request( + "post", + "/v1/transfers/{transfer}/reversals/{id}".format( + transfer=_util.sanitize_id(transfer), + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_transfer_service.py b/stripe/_transfer_service.py new file mode 100644 index 000000000..ba54721fd --- /dev/null +++ b/stripe/_transfer_service.py @@ -0,0 +1,207 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe._transfer import Transfer +from stripe._transfer_reversal_service import TransferReversalService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class TransferService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.reversals = TransferReversalService(self._requestor) + + class CreateParams(TypedDict): + amount: NotRequired["int"] + """ + A positive integer in cents (or local equivalent) representing how much to transfer. + """ + currency: str + """ + 3-letter [ISO code for currency](https://stripe.com/docs/payouts). + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + destination: str + """ + The ID of a connected Stripe account. [See the Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers) for details. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + source_transaction: NotRequired["str"] + """ + You can use this parameter to transfer funds from a charge before they are added to your available balance. A pending balance will transfer immediately but the funds will not become available until the original charge becomes available. [See the Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-availability) for details. + """ + source_type: NotRequired["Literal['bank_account', 'card', 'fpx']"] + """ + The source balance to use for this transfer. One of `bank_account`, `card`, or `fpx`. For most users, this will default to `card`. + """ + transfer_group: NotRequired["str"] + """ + A string that identifies this transaction as part of a group. See the [Connect documentation](https://stripe.com/docs/connect/separate-charges-and-transfers#transfer-options) for details. + """ + + class ListParams(TypedDict): + created: NotRequired["TransferService.ListParamsCreated|int"] + destination: NotRequired["str"] + """ + Only return transfers for the destination specified by this account ID. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + transfer_group: NotRequired["str"] + """ + Only return transfers with the specified transfer group. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + def list( + self, + params: "TransferService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Transfer]: + """ + Returns a list of existing transfers sent to connected accounts. The transfers are returned in sorted order, with the most recently created transfers appearing first. + """ + return cast( + ListObject[Transfer], + self._requestor.request( + "get", + "/v1/transfers", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "TransferService.CreateParams", + options: RequestOptions = {}, + ) -> Transfer: + """ + To send funds from your Stripe account to a connected account, you create a new transfer object. Your [Stripe balance](https://stripe.com/docs/api#balance) must be able to cover the transfer amount, or you'll receive an “Insufficient Funds” error. + """ + return cast( + Transfer, + self._requestor.request( + "post", + "/v1/transfers", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + transfer: str, + params: "TransferService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Transfer: + """ + Retrieves the details of an existing transfer. Supply the unique transfer ID from either a transfer creation request or the transfer list, and Stripe will return the corresponding transfer information. + """ + return cast( + Transfer, + self._requestor.request( + "get", + "/v1/transfers/{transfer}".format( + transfer=_util.sanitize_id(transfer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + transfer: str, + params: "TransferService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Transfer: + """ + Updates the specified transfer by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + + This request accepts only metadata as an argument. + """ + return cast( + Transfer, + self._requestor.request( + "post", + "/v1/transfers/{transfer}".format( + transfer=_util.sanitize_id(transfer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/_treasury_service.py b/stripe/_treasury_service.py new file mode 100644 index 000000000..5ea2e7652 --- /dev/null +++ b/stripe/_treasury_service.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.treasury._credit_reversal_service import CreditReversalService +from stripe.treasury._debit_reversal_service import DebitReversalService +from stripe.treasury._financial_account_service import FinancialAccountService +from stripe.treasury._inbound_transfer_service import InboundTransferService +from stripe.treasury._outbound_payment_service import OutboundPaymentService +from stripe.treasury._outbound_transfer_service import OutboundTransferService +from stripe.treasury._received_credit_service import ReceivedCreditService +from stripe.treasury._received_debit_service import ReceivedDebitService +from stripe.treasury._transaction_entry_service import TransactionEntryService +from stripe.treasury._transaction_service import TransactionService + + +class TreasuryService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.credit_reversals = CreditReversalService(self._requestor) + self.debit_reversals = DebitReversalService(self._requestor) + self.financial_accounts = FinancialAccountService(self._requestor) + self.inbound_transfers = InboundTransferService(self._requestor) + self.outbound_payments = OutboundPaymentService(self._requestor) + self.outbound_transfers = OutboundTransferService(self._requestor) + self.received_credits = ReceivedCreditService(self._requestor) + self.received_debits = ReceivedDebitService(self._requestor) + self.transactions = TransactionService(self._requestor) + self.transaction_entries = TransactionEntryService(self._requestor) diff --git a/stripe/_updateable_api_resource.py b/stripe/_updateable_api_resource.py index ec289ad4a..e24860bbb 100644 --- a/stripe/_updateable_api_resource.py +++ b/stripe/_updateable_api_resource.py @@ -19,10 +19,10 @@ def modify(cls, sid, **params) -> T: def save(self, idempotency_key=None): updated_params = self.serialize(None) if updated_params: + updated_params["idempotency_key"] = idempotency_key self._request_and_refresh( "post", self.instance_url(), - idempotency_key=idempotency_key, params=updated_params, _usage=["save"], ) diff --git a/stripe/_usage_record.py b/stripe/_usage_record.py index 22d382756..d1835ac5d 100644 --- a/stripe/_usage_record.py +++ b/stripe/_usage_record.py @@ -1,7 +1,5 @@ # -*- coding: utf-8 -*- # File generated from our OpenAPI spec -from stripe import _util -from stripe._api_requestor import APIRequestor from stripe._api_resource import APIResource from typing import ClassVar from typing_extensions import Literal @@ -42,26 +40,17 @@ class UsageRecord(APIResource["UsageRecord"]): """ @classmethod - def create( - cls, - api_key=None, - idempotency_key=None, - stripe_version=None, - stripe_account=None, - **params - ): + def create(cls, **params): if "subscription_item" not in params: raise ValueError("Params must have a subscription_item key") subscription_item = params.pop("subscription_item") - requestor = APIRequestor( - api_key, api_version=stripe_version, account=stripe_account - ) url = "/v1/subscription_items/%s/usage_records" % subscription_item - headers = _util.populate_headers(idempotency_key) - response, api_key = requestor.request("post", url, params, headers) - - return _util.convert_to_stripe_object( - response, api_key, stripe_version, stripe_account + return cls._static_request( + "post", + url, + params=params, + base_address="api", + api_mode="V1", ) diff --git a/stripe/_util.py b/stripe/_util.py index 3b2bde7a8..0c14b2a10 100644 --- a/stripe/_util.py +++ b/stripe/_util.py @@ -7,6 +7,8 @@ import re import warnings +from stripe._api_mode import ApiMode + from urllib.parse import parse_qsl, quote_plus # noqa: F401 from typing_extensions import Type, TYPE_CHECKING @@ -20,15 +22,18 @@ cast, Any, Optional, + Mapping, ) import typing_extensions + # Used for global variables import stripe # noqa: IMP101 if TYPE_CHECKING: from stripe._stripe_response import StripeResponse from stripe._stripe_object import StripeObject + from stripe._api_requestor import _APIRequestor STRIPE_LOG = os.environ.get("STRIPE_LOG") @@ -203,8 +208,10 @@ def convert_to_stripe_object( api_key: Optional[str] = None, stripe_version: Optional[str] = None, stripe_account: Optional[str] = None, - params: Optional[Dict[str, Any]] = None, + params: Optional[Mapping[str, Any]] = None, klass_: Optional[Type["StripeObject"]] = None, + *, + api_mode: ApiMode = "V1", ) -> "StripeObject": ... @@ -215,8 +222,10 @@ def convert_to_stripe_object( api_key: Optional[str] = None, stripe_version: Optional[str] = None, stripe_account: Optional[str] = None, - params: Optional[Dict[str, Any]] = None, + params: Optional[Mapping[str, Any]] = None, klass_: Optional[Type["StripeObject"]] = None, + *, + api_mode: ApiMode = "V1", ) -> List["StripeObject"]: ... @@ -226,8 +235,57 @@ def convert_to_stripe_object( api_key: Optional[str] = None, stripe_version: Optional[str] = None, stripe_account: Optional[str] = None, - params: Optional[Dict[str, Any]] = None, + params: Optional[Mapping[str, Any]] = None, klass_: Optional[Type["StripeObject"]] = None, + *, + api_mode: ApiMode = "V1", +) -> Union["StripeObject", List["StripeObject"]]: + from stripe._api_requestor import _APIRequestor + + return _convert_to_stripe_object( + resp=resp, + params=params, + klass_=klass_, + requestor=_APIRequestor._global_with_options( + api_key=api_key, + stripe_version=stripe_version, + stripe_account=stripe_account, + ), + api_mode=api_mode, + ) + + +@overload +def _convert_to_stripe_object( + *, + resp: Union["StripeResponse", Dict[str, Any]], + params: Optional[Mapping[str, Any]] = None, + klass_: Optional[Type["StripeObject"]] = None, + requestor: "_APIRequestor", + api_mode: ApiMode, +) -> "StripeObject": + ... + + +@overload +def _convert_to_stripe_object( + *, + resp: List[Resp], + params: Optional[Mapping[str, Any]] = None, + klass_: Optional[Type["StripeObject"]] = None, + requestor: "_APIRequestor", + api_mode: ApiMode, +) -> List["StripeObject"]: + ... + + +def _convert_to_stripe_object( + *, + resp: Resp, + params: Optional[Mapping[str, Any]] = None, + klass_: Optional[Type["StripeObject"]] = None, + requestor: "_APIRequestor", + api_mode: ApiMode, ) -> Union["StripeObject", List["StripeObject"]]: # If we get a StripeResponse, we'll want to return a # StripeObject with the last_response field filled out with @@ -244,11 +302,10 @@ def convert_to_stripe_object( if isinstance(resp, list): return [ - convert_to_stripe_object( - cast("Union[StripeResponse, Dict[str, Any]]", i), - api_key, - stripe_version, - stripe_account, + _convert_to_stripe_object( + resp=cast("Union[StripeResponse, Dict[str, Any]]", i), + requestor=requestor, + api_mode=api_mode, klass_=klass_, ) for i in resp @@ -263,12 +320,11 @@ def convert_to_stripe_object( else: klass = StripeObject - obj = klass.construct_from( - resp, - api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, + obj = klass._construct_from( + values=resp, last_response=stripe_response, + requestor=requestor, + api_mode=api_mode, ) # We only need to update _retrieve_params when special params were @@ -332,22 +388,6 @@ def populate_headers( T = TypeVar("T") -def read_special_variable( - params: Optional[Dict[str, Any]], key_name: str, default_value: T -) -> Optional[T]: - value = default_value - params_value = None - - if params is not None and key_name in params: - params_value = params[key_name] - del params[key_name] - - if value is None: - value = params_value - - return value - - def merge_dicts(x, y): z = x.copy() z.update(y) diff --git a/stripe/_verify_mixin.py b/stripe/_verify_mixin.py index f7a9f544d..870eff351 100644 --- a/stripe/_verify_mixin.py +++ b/stripe/_verify_mixin.py @@ -1,4 +1,4 @@ -from typing import Optional, Any, Dict +from typing import Any, Dict from typing_extensions import Protocol from stripe._stripe_object import StripeObject @@ -12,15 +12,12 @@ def _request( self, method: str, url: str, - idempotency_key: Optional[str], params: Dict[str, Any], ) -> StripeObject: ... class VerifyMixin(object): - def verify(self: _Verifiable, idempotency_key=None, **params): + def verify(self: _Verifiable, **params): url = self.instance_url() + "/verify" - return self._request( - "post", url, idempotency_key=idempotency_key, params=params - ) + return self._request("post", url, params=params) diff --git a/stripe/_webhook.py b/stripe/_webhook.py index 12f1789fc..6eaff0a2a 100644 --- a/stripe/_webhook.py +++ b/stripe/_webhook.py @@ -9,6 +9,7 @@ from stripe._event import Event from stripe import _util from stripe._error import SignatureVerificationError +from stripe._api_requestor import _APIRequestor class Webhook(object): @@ -24,7 +25,13 @@ def construct_event( WebhookSignature.verify_header(payload, sig_header, secret, tolerance) data = json.loads(payload, object_pairs_hook=OrderedDict) - event = Event.construct_from(data, api_key or stripe.api_key) + event = Event._construct_from( + values=data, + requestor=_APIRequestor._global_with_options( + api_key=api_key or stripe.api_key + ), + api_mode="V1", + ) return event diff --git a/stripe/_webhook_endpoint.py b/stripe/_webhook_endpoint.py index 1a9800bac..adc1ce8b1 100644 --- a/stripe/_webhook_endpoint.py +++ b/stripe/_webhook_endpoint.py @@ -409,14 +409,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "WebhookEndpoint.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["WebhookEndpoint.CreateParams"] ) -> "WebhookEndpoint": """ A webhook endpoint must have a url and a list of enabled_events. You may optionally specify the Boolean connect parameter. If set to true, then a Connect webhook endpoint that notifies the specified url about events from all connected accounts is created; otherwise an account webhook endpoint that notifies the specified url only about events from your account is created. You can also create webhook endpoints in the [webhooks settings](https://dashboard.stripe.com/account/webhooks) section of the Dashboard. @@ -426,10 +419,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -481,13 +470,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "WebhookEndpoint.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["WebhookEndpoint.ListParams"] ) -> ListObject["WebhookEndpoint"]: """ Returns a list of your webhook endpoints. @@ -495,9 +478,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/_webhook_endpoint_service.py b/stripe/_webhook_endpoint_service.py new file mode 100644 index 000000000..af47d5ea3 --- /dev/null +++ b/stripe/_webhook_endpoint_service.py @@ -0,0 +1,444 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe._webhook_endpoint import WebhookEndpoint +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class WebhookEndpointService(StripeService): + class CreateParams(TypedDict): + api_version: NotRequired[ + "Literal['2011-01-01', '2011-06-21', '2011-06-28', '2011-08-01', '2011-09-15', '2011-11-17', '2012-02-23', '2012-03-25', '2012-06-18', '2012-06-28', '2012-07-09', '2012-09-24', '2012-10-26', '2012-11-07', '2013-02-11', '2013-02-13', '2013-07-05', '2013-08-12', '2013-08-13', '2013-10-29', '2013-12-03', '2014-01-31', '2014-03-13', '2014-03-28', '2014-05-19', '2014-06-13', '2014-06-17', '2014-07-22', '2014-07-26', '2014-08-04', '2014-08-20', '2014-09-08', '2014-10-07', '2014-11-05', '2014-11-20', '2014-12-08', '2014-12-17', '2014-12-22', '2015-01-11', '2015-01-26', '2015-02-10', '2015-02-16', '2015-02-18', '2015-03-24', '2015-04-07', '2015-06-15', '2015-07-07', '2015-07-13', '2015-07-28', '2015-08-07', '2015-08-19', '2015-09-03', '2015-09-08', '2015-09-23', '2015-10-01', '2015-10-12', '2015-10-16', '2016-02-03', '2016-02-19', '2016-02-22', '2016-02-23', '2016-02-29', '2016-03-07', '2016-06-15', '2016-07-06', '2016-10-19', '2017-01-27', '2017-02-14', '2017-04-06', '2017-05-25', '2017-06-05', '2017-08-15', '2017-12-14', '2018-01-23', '2018-02-05', '2018-02-06', '2018-02-28', '2018-05-21', '2018-07-27', '2018-08-23', '2018-09-06', '2018-09-24', '2018-10-31', '2018-11-08', '2019-02-11', '2019-02-19', '2019-03-14', '2019-05-16', '2019-08-14', '2019-09-09', '2019-10-08', '2019-10-17', '2019-11-05', '2019-12-03', '2020-03-02', '2020-08-27', '2022-08-01', '2022-11-15', '2023-08-16', '2023-10-16']" + ] + """ + Events sent to this endpoint will be generated with this Stripe Version instead of your account's default Stripe Version. + """ + connect: NotRequired["bool"] + """ + Whether this endpoint should receive events from connected accounts (`true`), or from your account (`false`). Defaults to `false`. + """ + description: NotRequired["Literal['']|str"] + """ + An optional description of what the webhook is used for. + """ + enabled_events: List[ + Literal[ + "*", + "account.application.authorized", + "account.application.deauthorized", + "account.external_account.created", + "account.external_account.deleted", + "account.external_account.updated", + "account.updated", + "application_fee.created", + "application_fee.refund.updated", + "application_fee.refunded", + "balance.available", + "billing_portal.configuration.created", + "billing_portal.configuration.updated", + "billing_portal.session.created", + "capability.updated", + "cash_balance.funds_available", + "charge.captured", + "charge.dispute.closed", + "charge.dispute.created", + "charge.dispute.funds_reinstated", + "charge.dispute.funds_withdrawn", + "charge.dispute.updated", + "charge.expired", + "charge.failed", + "charge.pending", + "charge.refund.updated", + "charge.refunded", + "charge.succeeded", + "charge.updated", + "checkout.session.async_payment_failed", + "checkout.session.async_payment_succeeded", + "checkout.session.completed", + "checkout.session.expired", + "climate.order.canceled", + "climate.order.created", + "climate.order.delayed", + "climate.order.delivered", + "climate.order.product_substituted", + "climate.product.created", + "climate.product.pricing_updated", + "coupon.created", + "coupon.deleted", + "coupon.updated", + "credit_note.created", + "credit_note.updated", + "credit_note.voided", + "customer.created", + "customer.deleted", + "customer.discount.created", + "customer.discount.deleted", + "customer.discount.updated", + "customer.source.created", + "customer.source.deleted", + "customer.source.expiring", + "customer.source.updated", + "customer.subscription.created", + "customer.subscription.deleted", + "customer.subscription.paused", + "customer.subscription.pending_update_applied", + "customer.subscription.pending_update_expired", + "customer.subscription.resumed", + "customer.subscription.trial_will_end", + "customer.subscription.updated", + "customer.tax_id.created", + "customer.tax_id.deleted", + "customer.tax_id.updated", + "customer.updated", + "customer_cash_balance_transaction.created", + "file.created", + "financial_connections.account.created", + "financial_connections.account.deactivated", + "financial_connections.account.disconnected", + "financial_connections.account.reactivated", + "financial_connections.account.refreshed_balance", + "financial_connections.account.refreshed_transactions", + "identity.verification_session.canceled", + "identity.verification_session.created", + "identity.verification_session.processing", + "identity.verification_session.redacted", + "identity.verification_session.requires_input", + "identity.verification_session.verified", + "invoice.created", + "invoice.deleted", + "invoice.finalization_failed", + "invoice.finalized", + "invoice.marked_uncollectible", + "invoice.paid", + "invoice.payment_action_required", + "invoice.payment_failed", + "invoice.payment_succeeded", + "invoice.sent", + "invoice.upcoming", + "invoice.updated", + "invoice.voided", + "invoiceitem.created", + "invoiceitem.deleted", + "issuing_authorization.created", + "issuing_authorization.request", + "issuing_authorization.updated", + "issuing_card.created", + "issuing_card.updated", + "issuing_cardholder.created", + "issuing_cardholder.updated", + "issuing_dispute.closed", + "issuing_dispute.created", + "issuing_dispute.funds_reinstated", + "issuing_dispute.submitted", + "issuing_dispute.updated", + "issuing_token.created", + "issuing_token.updated", + "issuing_transaction.created", + "issuing_transaction.updated", + "mandate.updated", + "payment_intent.amount_capturable_updated", + "payment_intent.canceled", + "payment_intent.created", + "payment_intent.partially_funded", + "payment_intent.payment_failed", + "payment_intent.processing", + "payment_intent.requires_action", + "payment_intent.succeeded", + "payment_link.created", + "payment_link.updated", + "payment_method.attached", + "payment_method.automatically_updated", + "payment_method.detached", + "payment_method.updated", + "payout.canceled", + "payout.created", + "payout.failed", + "payout.paid", + "payout.reconciliation_completed", + "payout.updated", + "person.created", + "person.deleted", + "person.updated", + "plan.created", + "plan.deleted", + "plan.updated", + "price.created", + "price.deleted", + "price.updated", + "product.created", + "product.deleted", + "product.updated", + "promotion_code.created", + "promotion_code.updated", + "quote.accepted", + "quote.canceled", + "quote.created", + "quote.finalized", + "radar.early_fraud_warning.created", + "radar.early_fraud_warning.updated", + "refund.created", + "refund.updated", + "reporting.report_run.failed", + "reporting.report_run.succeeded", + "reporting.report_type.updated", + "review.closed", + "review.opened", + "setup_intent.canceled", + "setup_intent.created", + "setup_intent.requires_action", + "setup_intent.setup_failed", + "setup_intent.succeeded", + "sigma.scheduled_query_run.created", + "source.canceled", + "source.chargeable", + "source.failed", + "source.mandate_notification", + "source.refund_attributes_required", + "source.transaction.created", + "source.transaction.updated", + "subscription_schedule.aborted", + "subscription_schedule.canceled", + "subscription_schedule.completed", + "subscription_schedule.created", + "subscription_schedule.expiring", + "subscription_schedule.released", + "subscription_schedule.updated", + "tax.settings.updated", + "tax_rate.created", + "tax_rate.updated", + "terminal.reader.action_failed", + "terminal.reader.action_succeeded", + "test_helpers.test_clock.advancing", + "test_helpers.test_clock.created", + "test_helpers.test_clock.deleted", + "test_helpers.test_clock.internal_failure", + "test_helpers.test_clock.ready", + "topup.canceled", + "topup.created", + "topup.failed", + "topup.reversed", + "topup.succeeded", + "transfer.created", + "transfer.reversed", + "transfer.updated", + "treasury.credit_reversal.created", + "treasury.credit_reversal.posted", + "treasury.debit_reversal.completed", + "treasury.debit_reversal.created", + "treasury.debit_reversal.initial_credit_granted", + "treasury.financial_account.closed", + "treasury.financial_account.created", + "treasury.financial_account.features_status_updated", + "treasury.inbound_transfer.canceled", + "treasury.inbound_transfer.created", + "treasury.inbound_transfer.failed", + "treasury.inbound_transfer.succeeded", + "treasury.outbound_payment.canceled", + "treasury.outbound_payment.created", + "treasury.outbound_payment.expected_arrival_date_updated", + "treasury.outbound_payment.failed", + "treasury.outbound_payment.posted", + "treasury.outbound_payment.returned", + "treasury.outbound_transfer.canceled", + "treasury.outbound_transfer.created", + "treasury.outbound_transfer.expected_arrival_date_updated", + "treasury.outbound_transfer.failed", + "treasury.outbound_transfer.posted", + "treasury.outbound_transfer.returned", + "treasury.received_credit.created", + "treasury.received_credit.failed", + "treasury.received_credit.succeeded", + "treasury.received_debit.created", + "invoiceitem.updated", + "order.created", + "recipient.created", + "recipient.deleted", + "recipient.updated", + "sku.created", + "sku.deleted", + "sku.updated", + ] + ] + """ + The list of events to enable for this endpoint. You may specify `['*']` to enable all events, except those that require explicit selection. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + url: str + """ + The URL of the webhook endpoint. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + description: NotRequired["Literal['']|str"] + """ + An optional description of what the webhook is used for. + """ + disabled: NotRequired["bool"] + """ + Disable the webhook endpoint if set to true. + """ + enabled_events: NotRequired[ + "List[Literal['*', 'account.application.authorized', 'account.application.deauthorized', 'account.external_account.created', 'account.external_account.deleted', 'account.external_account.updated', 'account.updated', 'application_fee.created', 'application_fee.refund.updated', 'application_fee.refunded', 'balance.available', 'billing_portal.configuration.created', 'billing_portal.configuration.updated', 'billing_portal.session.created', 'capability.updated', 'cash_balance.funds_available', 'charge.captured', 'charge.dispute.closed', 'charge.dispute.created', 'charge.dispute.funds_reinstated', 'charge.dispute.funds_withdrawn', 'charge.dispute.updated', 'charge.expired', 'charge.failed', 'charge.pending', 'charge.refund.updated', 'charge.refunded', 'charge.succeeded', 'charge.updated', 'checkout.session.async_payment_failed', 'checkout.session.async_payment_succeeded', 'checkout.session.completed', 'checkout.session.expired', 'climate.order.canceled', 'climate.order.created', 'climate.order.delayed', 'climate.order.delivered', 'climate.order.product_substituted', 'climate.product.created', 'climate.product.pricing_updated', 'coupon.created', 'coupon.deleted', 'coupon.updated', 'credit_note.created', 'credit_note.updated', 'credit_note.voided', 'customer.created', 'customer.deleted', 'customer.discount.created', 'customer.discount.deleted', 'customer.discount.updated', 'customer.source.created', 'customer.source.deleted', 'customer.source.expiring', 'customer.source.updated', 'customer.subscription.created', 'customer.subscription.deleted', 'customer.subscription.paused', 'customer.subscription.pending_update_applied', 'customer.subscription.pending_update_expired', 'customer.subscription.resumed', 'customer.subscription.trial_will_end', 'customer.subscription.updated', 'customer.tax_id.created', 'customer.tax_id.deleted', 'customer.tax_id.updated', 'customer.updated', 'customer_cash_balance_transaction.created', 'file.created', 'financial_connections.account.created', 'financial_connections.account.deactivated', 'financial_connections.account.disconnected', 'financial_connections.account.reactivated', 'financial_connections.account.refreshed_balance', 'financial_connections.account.refreshed_transactions', 'identity.verification_session.canceled', 'identity.verification_session.created', 'identity.verification_session.processing', 'identity.verification_session.redacted', 'identity.verification_session.requires_input', 'identity.verification_session.verified', 'invoice.created', 'invoice.deleted', 'invoice.finalization_failed', 'invoice.finalized', 'invoice.marked_uncollectible', 'invoice.paid', 'invoice.payment_action_required', 'invoice.payment_failed', 'invoice.payment_succeeded', 'invoice.sent', 'invoice.upcoming', 'invoice.updated', 'invoice.voided', 'invoiceitem.created', 'invoiceitem.deleted', 'issuing_authorization.created', 'issuing_authorization.request', 'issuing_authorization.updated', 'issuing_card.created', 'issuing_card.updated', 'issuing_cardholder.created', 'issuing_cardholder.updated', 'issuing_dispute.closed', 'issuing_dispute.created', 'issuing_dispute.funds_reinstated', 'issuing_dispute.submitted', 'issuing_dispute.updated', 'issuing_token.created', 'issuing_token.updated', 'issuing_transaction.created', 'issuing_transaction.updated', 'mandate.updated', 'payment_intent.amount_capturable_updated', 'payment_intent.canceled', 'payment_intent.created', 'payment_intent.partially_funded', 'payment_intent.payment_failed', 'payment_intent.processing', 'payment_intent.requires_action', 'payment_intent.succeeded', 'payment_link.created', 'payment_link.updated', 'payment_method.attached', 'payment_method.automatically_updated', 'payment_method.detached', 'payment_method.updated', 'payout.canceled', 'payout.created', 'payout.failed', 'payout.paid', 'payout.reconciliation_completed', 'payout.updated', 'person.created', 'person.deleted', 'person.updated', 'plan.created', 'plan.deleted', 'plan.updated', 'price.created', 'price.deleted', 'price.updated', 'product.created', 'product.deleted', 'product.updated', 'promotion_code.created', 'promotion_code.updated', 'quote.accepted', 'quote.canceled', 'quote.created', 'quote.finalized', 'radar.early_fraud_warning.created', 'radar.early_fraud_warning.updated', 'refund.created', 'refund.updated', 'reporting.report_run.failed', 'reporting.report_run.succeeded', 'reporting.report_type.updated', 'review.closed', 'review.opened', 'setup_intent.canceled', 'setup_intent.created', 'setup_intent.requires_action', 'setup_intent.setup_failed', 'setup_intent.succeeded', 'sigma.scheduled_query_run.created', 'source.canceled', 'source.chargeable', 'source.failed', 'source.mandate_notification', 'source.refund_attributes_required', 'source.transaction.created', 'source.transaction.updated', 'subscription_schedule.aborted', 'subscription_schedule.canceled', 'subscription_schedule.completed', 'subscription_schedule.created', 'subscription_schedule.expiring', 'subscription_schedule.released', 'subscription_schedule.updated', 'tax.settings.updated', 'tax_rate.created', 'tax_rate.updated', 'terminal.reader.action_failed', 'terminal.reader.action_succeeded', 'test_helpers.test_clock.advancing', 'test_helpers.test_clock.created', 'test_helpers.test_clock.deleted', 'test_helpers.test_clock.internal_failure', 'test_helpers.test_clock.ready', 'topup.canceled', 'topup.created', 'topup.failed', 'topup.reversed', 'topup.succeeded', 'transfer.created', 'transfer.reversed', 'transfer.updated', 'treasury.credit_reversal.created', 'treasury.credit_reversal.posted', 'treasury.debit_reversal.completed', 'treasury.debit_reversal.created', 'treasury.debit_reversal.initial_credit_granted', 'treasury.financial_account.closed', 'treasury.financial_account.created', 'treasury.financial_account.features_status_updated', 'treasury.inbound_transfer.canceled', 'treasury.inbound_transfer.created', 'treasury.inbound_transfer.failed', 'treasury.inbound_transfer.succeeded', 'treasury.outbound_payment.canceled', 'treasury.outbound_payment.created', 'treasury.outbound_payment.expected_arrival_date_updated', 'treasury.outbound_payment.failed', 'treasury.outbound_payment.posted', 'treasury.outbound_payment.returned', 'treasury.outbound_transfer.canceled', 'treasury.outbound_transfer.created', 'treasury.outbound_transfer.expected_arrival_date_updated', 'treasury.outbound_transfer.failed', 'treasury.outbound_transfer.posted', 'treasury.outbound_transfer.returned', 'treasury.received_credit.created', 'treasury.received_credit.failed', 'treasury.received_credit.succeeded', 'treasury.received_debit.created', 'invoiceitem.updated', 'order.created', 'recipient.created', 'recipient.deleted', 'recipient.updated', 'sku.created', 'sku.deleted', 'sku.updated']]" + ] + """ + The list of events to enable for this endpoint. You may specify `['*']` to enable all events, except those that require explicit selection. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + url: NotRequired["str"] + """ + The URL of the webhook endpoint. + """ + + def delete( + self, + webhook_endpoint: str, + params: "WebhookEndpointService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> WebhookEndpoint: + """ + You can also delete webhook endpoints via the [webhook endpoint management](https://dashboard.stripe.com/account/webhooks) page of the Stripe dashboard. + """ + return cast( + WebhookEndpoint, + self._requestor.request( + "delete", + "/v1/webhook_endpoints/{webhook_endpoint}".format( + webhook_endpoint=_util.sanitize_id(webhook_endpoint), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + webhook_endpoint: str, + params: "WebhookEndpointService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> WebhookEndpoint: + """ + Retrieves the webhook endpoint with the given ID. + """ + return cast( + WebhookEndpoint, + self._requestor.request( + "get", + "/v1/webhook_endpoints/{webhook_endpoint}".format( + webhook_endpoint=_util.sanitize_id(webhook_endpoint), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + webhook_endpoint: str, + params: "WebhookEndpointService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> WebhookEndpoint: + """ + Updates the webhook endpoint. You may edit the url, the list of enabled_events, and the status of your endpoint. + """ + return cast( + WebhookEndpoint, + self._requestor.request( + "post", + "/v1/webhook_endpoints/{webhook_endpoint}".format( + webhook_endpoint=_util.sanitize_id(webhook_endpoint), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "WebhookEndpointService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[WebhookEndpoint]: + """ + Returns a list of your webhook endpoints. + """ + return cast( + ListObject[WebhookEndpoint], + self._requestor.request( + "get", + "/v1/webhook_endpoints", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "WebhookEndpointService.CreateParams", + options: RequestOptions = {}, + ) -> WebhookEndpoint: + """ + A webhook endpoint must have a url and a list of enabled_events. You may optionally specify the Boolean connect parameter. If set to true, then a Connect webhook endpoint that notifies the specified url about events from all connected accounts is created; otherwise an account webhook endpoint that notifies the specified url only about events from your account is created. You can also create webhook endpoints in the [webhooks settings](https://dashboard.stripe.com/account/webhooks) section of the Dashboard. + """ + return cast( + WebhookEndpoint, + self._requestor.request( + "post", + "/v1/webhook_endpoints", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/api_requestor.py b/stripe/api_requestor.py deleted file mode 100644 index 64f2b0dd1..000000000 --- a/stripe/api_requestor.py +++ /dev/null @@ -1,20 +0,0 @@ -# -*- coding: utf-8 -*- -from typing_extensions import TYPE_CHECKING -from warnings import warn - -warn( - """ - The stripe.api_requestor package is deprecated, please change your - imports to import from stripe directly. - From: - from stripe.api_requestor import APIRequestor - To: - from stripe import APIRequestor - """, - DeprecationWarning, -) - -if not TYPE_CHECKING: - from stripe._api_requestor import ( # noqa - APIRequestor, - ) diff --git a/stripe/apps/__init__.py b/stripe/apps/__init__.py index 3c944f8ea..caa745384 100644 --- a/stripe/apps/__init__.py +++ b/stripe/apps/__init__.py @@ -1,3 +1,4 @@ # -*- coding: utf-8 -*- # File generated from our OpenAPI spec from stripe.apps._secret import Secret as Secret +from stripe.apps._secret_service import SecretService as SecretService diff --git a/stripe/apps/_secret.py b/stripe/apps/_secret.py index b7258d78e..871eb46e2 100644 --- a/stripe/apps/_secret.py +++ b/stripe/apps/_secret.py @@ -181,16 +181,7 @@ class ListParamsScope(TypedDict): scope: Scope @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Secret.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Secret": + def create(cls, **params: Unpack["Secret.CreateParams"]) -> "Secret": """ Create or replace a secret in the secret store. """ @@ -199,23 +190,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def delete_where( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Secret.DeleteWhereParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Secret.DeleteWhereParams"] ) -> "Secret": """ Deletes a secret from the secret store by name and scope. @@ -225,23 +206,12 @@ def delete_where( cls._static_request( "post", "/v1/apps/secrets/delete", - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod - def find( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Secret.FindParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Secret": + def find(cls, **params: Unpack["Secret.FindParams"]) -> "Secret": """ Finds a secret in the secret store by name and scope. """ @@ -250,22 +220,13 @@ def find( cls._static_request( "get", "/v1/apps/secrets/find", - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Secret.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Secret.ListParams"] ) -> ListObject["Secret"]: """ List all secrets stored on the given scope. @@ -273,9 +234,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/apps/_secret_service.py b/stripe/apps/_secret_service.py new file mode 100644 index 000000000..7b3d0411f --- /dev/null +++ b/stripe/apps/_secret_service.py @@ -0,0 +1,198 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.apps._secret import Secret +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class SecretService(StripeService): + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + expires_at: NotRequired["int"] + """ + The Unix timestamp for the expiry time of the secret, after which the secret deletes. + """ + name: str + """ + A name for the secret that's unique within the scope. + """ + payload: str + """ + The plaintext secret value to be stored. + """ + scope: "SecretService.CreateParamsScope" + """ + Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. + """ + + class CreateParamsScope(TypedDict): + type: Literal["account", "user"] + """ + The secret scope type. + """ + user: NotRequired["str"] + """ + The user ID. This field is required if `type` is set to `user`, and should not be provided if `type` is set to `account`. + """ + + class DeleteWhereParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + name: str + """ + A name for the secret that's unique within the scope. + """ + scope: "SecretService.DeleteWhereParamsScope" + """ + Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. + """ + + class DeleteWhereParamsScope(TypedDict): + type: Literal["account", "user"] + """ + The secret scope type. + """ + user: NotRequired["str"] + """ + The user ID. This field is required if `type` is set to `user`, and should not be provided if `type` is set to `account`. + """ + + class FindParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + name: str + """ + A name for the secret that's unique within the scope. + """ + scope: "SecretService.FindParamsScope" + """ + Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. + """ + + class FindParamsScope(TypedDict): + type: Literal["account", "user"] + """ + The secret scope type. + """ + user: NotRequired["str"] + """ + The user ID. This field is required if `type` is set to `user`, and should not be provided if `type` is set to `account`. + """ + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + scope: "SecretService.ListParamsScope" + """ + Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsScope(TypedDict): + type: Literal["account", "user"] + """ + The secret scope type. + """ + user: NotRequired["str"] + """ + The user ID. This field is required if `type` is set to `user`, and should not be provided if `type` is set to `account`. + """ + + def list( + self, params: "SecretService.ListParams", options: RequestOptions = {} + ) -> ListObject[Secret]: + """ + List all secrets stored on the given scope. + """ + return cast( + ListObject[Secret], + self._requestor.request( + "get", + "/v1/apps/secrets", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "SecretService.CreateParams", + options: RequestOptions = {}, + ) -> Secret: + """ + Create or replace a secret in the secret store. + """ + return cast( + Secret, + self._requestor.request( + "post", + "/v1/apps/secrets", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def find( + self, params: "SecretService.FindParams", options: RequestOptions = {} + ) -> Secret: + """ + Finds a secret in the secret store by name and scope. + """ + return cast( + Secret, + self._requestor.request( + "get", + "/v1/apps/secrets/find", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def delete_where( + self, + params: "SecretService.DeleteWhereParams", + options: RequestOptions = {}, + ) -> Secret: + """ + Deletes a secret from the secret store by name and scope. + """ + return cast( + Secret, + self._requestor.request( + "post", + "/v1/apps/secrets/delete", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/billing_portal/__init__.py b/stripe/billing_portal/__init__.py index cbd629a99..89ff23dc8 100644 --- a/stripe/billing_portal/__init__.py +++ b/stripe/billing_portal/__init__.py @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*- # File generated from our OpenAPI spec from stripe.billing_portal._configuration import Configuration as Configuration +from stripe.billing_portal._configuration_service import ( + ConfigurationService as ConfigurationService, +) from stripe.billing_portal._session import Session as Session +from stripe.billing_portal._session_service import ( + SessionService as SessionService, +) diff --git a/stripe/billing_portal/_configuration.py b/stripe/billing_portal/_configuration.py index 5eb02a13a..8022455c3 100644 --- a/stripe/billing_portal/_configuration.py +++ b/stripe/billing_portal/_configuration.py @@ -645,14 +645,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Configuration.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Configuration.CreateParams"] ) -> "Configuration": """ Creates a configuration that describes the functionality and behavior of a PortalSession @@ -662,23 +655,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Configuration.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Configuration.ListParams"] ) -> ListObject["Configuration"]: """ Returns a list of configurations that describe the functionality of the customer portal. @@ -686,9 +669,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/billing_portal/_configuration_service.py b/stripe/billing_portal/_configuration_service.py new file mode 100644 index 000000000..a7a68b4f0 --- /dev/null +++ b/stripe/billing_portal/_configuration_service.py @@ -0,0 +1,516 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.billing_portal._configuration import Configuration +from typing import Dict, List, Union, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ConfigurationService(StripeService): + class CreateParams(TypedDict): + business_profile: "ConfigurationService.CreateParamsBusinessProfile" + """ + The business information shown to customers in the portal. + """ + default_return_url: NotRequired["Literal['']|str"] + """ + The default URL to redirect customers to when they click on the portal's link to return to your website. This can be [overriden](https://stripe.com/docs/api/customer_portal/sessions/create#create_portal_session-return_url) when creating the session. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + features: "ConfigurationService.CreateParamsFeatures" + """ + Information about the features available in the portal. + """ + login_page: NotRequired["ConfigurationService.CreateParamsLoginPage"] + """ + The hosted login page for this configuration. Learn more about the portal login page in our [integration docs](https://stripe.com/docs/billing/subscriptions/integrating-customer-portal#share). + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class CreateParamsBusinessProfile(TypedDict): + headline: NotRequired["Literal['']|str"] + """ + The messaging shown to customers in the portal. + """ + privacy_policy_url: NotRequired["str"] + """ + A link to the business's publicly available privacy policy. + """ + terms_of_service_url: NotRequired["str"] + """ + A link to the business's publicly available terms of service. + """ + + class CreateParamsFeatures(TypedDict): + customer_update: NotRequired[ + "ConfigurationService.CreateParamsFeaturesCustomerUpdate" + ] + """ + Information about updating the customer details in the portal. + """ + invoice_history: NotRequired[ + "ConfigurationService.CreateParamsFeaturesInvoiceHistory" + ] + """ + Information about showing the billing history in the portal. + """ + payment_method_update: NotRequired[ + "ConfigurationService.CreateParamsFeaturesPaymentMethodUpdate" + ] + """ + Information about updating payment methods in the portal. + """ + subscription_cancel: NotRequired[ + "ConfigurationService.CreateParamsFeaturesSubscriptionCancel" + ] + """ + Information about canceling subscriptions in the portal. + """ + subscription_pause: NotRequired[ + "ConfigurationService.CreateParamsFeaturesSubscriptionPause" + ] + """ + Information about pausing subscriptions in the portal. + """ + subscription_update: NotRequired[ + "ConfigurationService.CreateParamsFeaturesSubscriptionUpdate" + ] + """ + Information about updating subscriptions in the portal. + """ + + class CreateParamsFeaturesCustomerUpdate(TypedDict): + allowed_updates: NotRequired[ + "Literal['']|List[Literal['address', 'email', 'name', 'phone', 'shipping', 'tax_id']]" + ] + """ + The types of customer updates that are supported. When empty, customers are not updateable. + """ + enabled: bool + """ + Whether the feature is enabled. + """ + + class CreateParamsFeaturesInvoiceHistory(TypedDict): + enabled: bool + """ + Whether the feature is enabled. + """ + + class CreateParamsFeaturesPaymentMethodUpdate(TypedDict): + enabled: bool + """ + Whether the feature is enabled. + """ + + class CreateParamsFeaturesSubscriptionCancel(TypedDict): + cancellation_reason: NotRequired[ + "ConfigurationService.CreateParamsFeaturesSubscriptionCancelCancellationReason" + ] + """ + Whether the cancellation reasons will be collected in the portal and which options are exposed to the customer + """ + enabled: bool + """ + Whether the feature is enabled. + """ + mode: NotRequired["Literal['at_period_end', 'immediately']"] + """ + Whether to cancel subscriptions immediately or at the end of the billing period. + """ + proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Whether to create prorations when canceling subscriptions. Possible values are `none` and `create_prorations`, which is only compatible with `mode=immediately`. No prorations are generated when canceling a subscription at the end of its natural billing period. + """ + + class CreateParamsFeaturesSubscriptionCancelCancellationReason(TypedDict): + enabled: bool + """ + Whether the feature is enabled. + """ + options: Union[ + Literal[""], + List[ + Literal[ + "customer_service", + "low_quality", + "missing_features", + "other", + "switched_service", + "too_complex", + "too_expensive", + "unused", + ] + ], + ] + """ + Which cancellation reasons will be given as options to the customer. + """ + + class CreateParamsFeaturesSubscriptionPause(TypedDict): + enabled: NotRequired["bool"] + """ + Whether the feature is enabled. + """ + + class CreateParamsFeaturesSubscriptionUpdate(TypedDict): + default_allowed_updates: Union[ + Literal[""], List[Literal["price", "promotion_code", "quantity"]] + ] + """ + The types of subscription updates that are supported. When empty, subscriptions are not updateable. + """ + enabled: bool + """ + Whether the feature is enabled. + """ + products: Union[ + Literal[""], + List[ + "ConfigurationService.CreateParamsFeaturesSubscriptionUpdateProduct" + ], + ] + """ + The list of up to 10 products that support subscription updates. + """ + proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Determines how to handle prorations resulting from subscription updates. Valid values are `none`, `create_prorations`, and `always_invoice`. + """ + + class CreateParamsFeaturesSubscriptionUpdateProduct(TypedDict): + prices: List[str] + """ + The list of price IDs for the product that a subscription can be updated to. + """ + product: str + """ + The product id. + """ + + class CreateParamsLoginPage(TypedDict): + enabled: bool + """ + Set to `true` to generate a shareable URL [`login_page.url`](https://stripe.com/docs/api/customer_portal/configuration#portal_configuration_object-login_page-url) that will take your customers to a hosted login page for the customer portal. + """ + + class ListParams(TypedDict): + active: NotRequired["bool"] + """ + Only return configurations that are active or inactive (e.g., pass `true` to only list active configurations). + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + is_default: NotRequired["bool"] + """ + Only return the default or non-default configurations (e.g., pass `true` to only list the default configuration). + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + active: NotRequired["bool"] + """ + Whether the configuration is active and can be used to create portal sessions. + """ + business_profile: NotRequired[ + "ConfigurationService.UpdateParamsBusinessProfile" + ] + """ + The business information shown to customers in the portal. + """ + default_return_url: NotRequired["Literal['']|str"] + """ + The default URL to redirect customers to when they click on the portal's link to return to your website. This can be [overriden](https://stripe.com/docs/api/customer_portal/sessions/create#create_portal_session-return_url) when creating the session. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + features: NotRequired["ConfigurationService.UpdateParamsFeatures"] + """ + Information about the features available in the portal. + """ + login_page: NotRequired["ConfigurationService.UpdateParamsLoginPage"] + """ + The hosted login page for this configuration. Learn more about the portal login page in our [integration docs](https://stripe.com/docs/billing/subscriptions/integrating-customer-portal#share). + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class UpdateParamsBusinessProfile(TypedDict): + headline: NotRequired["Literal['']|str"] + """ + The messaging shown to customers in the portal. + """ + privacy_policy_url: NotRequired["Literal['']|str"] + """ + A link to the business's publicly available privacy policy. + """ + terms_of_service_url: NotRequired["Literal['']|str"] + """ + A link to the business's publicly available terms of service. + """ + + class UpdateParamsFeatures(TypedDict): + customer_update: NotRequired[ + "ConfigurationService.UpdateParamsFeaturesCustomerUpdate" + ] + """ + Information about updating the customer details in the portal. + """ + invoice_history: NotRequired[ + "ConfigurationService.UpdateParamsFeaturesInvoiceHistory" + ] + """ + Information about showing the billing history in the portal. + """ + payment_method_update: NotRequired[ + "ConfigurationService.UpdateParamsFeaturesPaymentMethodUpdate" + ] + """ + Information about updating payment methods in the portal. + """ + subscription_cancel: NotRequired[ + "ConfigurationService.UpdateParamsFeaturesSubscriptionCancel" + ] + """ + Information about canceling subscriptions in the portal. + """ + subscription_pause: NotRequired[ + "ConfigurationService.UpdateParamsFeaturesSubscriptionPause" + ] + """ + Information about pausing subscriptions in the portal. + """ + subscription_update: NotRequired[ + "ConfigurationService.UpdateParamsFeaturesSubscriptionUpdate" + ] + """ + Information about updating subscriptions in the portal. + """ + + class UpdateParamsFeaturesCustomerUpdate(TypedDict): + allowed_updates: NotRequired[ + "Literal['']|List[Literal['address', 'email', 'name', 'phone', 'shipping', 'tax_id']]" + ] + """ + The types of customer updates that are supported. When empty, customers are not updateable. + """ + enabled: NotRequired["bool"] + """ + Whether the feature is enabled. + """ + + class UpdateParamsFeaturesInvoiceHistory(TypedDict): + enabled: bool + """ + Whether the feature is enabled. + """ + + class UpdateParamsFeaturesPaymentMethodUpdate(TypedDict): + enabled: bool + """ + Whether the feature is enabled. + """ + + class UpdateParamsFeaturesSubscriptionCancel(TypedDict): + cancellation_reason: NotRequired[ + "ConfigurationService.UpdateParamsFeaturesSubscriptionCancelCancellationReason" + ] + """ + Whether the cancellation reasons will be collected in the portal and which options are exposed to the customer + """ + enabled: NotRequired["bool"] + """ + Whether the feature is enabled. + """ + mode: NotRequired["Literal['at_period_end', 'immediately']"] + """ + Whether to cancel subscriptions immediately or at the end of the billing period. + """ + proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Whether to create prorations when canceling subscriptions. Possible values are `none` and `create_prorations`, which is only compatible with `mode=immediately`. No prorations are generated when canceling a subscription at the end of its natural billing period. + """ + + class UpdateParamsFeaturesSubscriptionCancelCancellationReason(TypedDict): + enabled: bool + """ + Whether the feature is enabled. + """ + options: NotRequired[ + "Literal['']|List[Literal['customer_service', 'low_quality', 'missing_features', 'other', 'switched_service', 'too_complex', 'too_expensive', 'unused']]" + ] + """ + Which cancellation reasons will be given as options to the customer. + """ + + class UpdateParamsFeaturesSubscriptionPause(TypedDict): + enabled: NotRequired["bool"] + """ + Whether the feature is enabled. + """ + + class UpdateParamsFeaturesSubscriptionUpdate(TypedDict): + default_allowed_updates: NotRequired[ + "Literal['']|List[Literal['price', 'promotion_code', 'quantity']]" + ] + """ + The types of subscription updates that are supported. When empty, subscriptions are not updateable. + """ + enabled: NotRequired["bool"] + """ + Whether the feature is enabled. + """ + products: NotRequired[ + "Literal['']|List[ConfigurationService.UpdateParamsFeaturesSubscriptionUpdateProduct]" + ] + """ + The list of up to 10 products that support subscription updates. + """ + proration_behavior: NotRequired[ + "Literal['always_invoice', 'create_prorations', 'none']" + ] + """ + Determines how to handle prorations resulting from subscription updates. Valid values are `none`, `create_prorations`, and `always_invoice`. + """ + + class UpdateParamsFeaturesSubscriptionUpdateProduct(TypedDict): + prices: List[str] + """ + The list of price IDs for the product that a subscription can be updated to. + """ + product: str + """ + The product id. + """ + + class UpdateParamsLoginPage(TypedDict): + enabled: bool + """ + Set to `true` to generate a shareable URL [`login_page.url`](https://stripe.com/docs/api/customer_portal/configuration#portal_configuration_object-login_page-url) that will take your customers to a hosted login page for the customer portal. + + Set to `false` to deactivate the `login_page.url`. + """ + + def list( + self, + params: "ConfigurationService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Configuration]: + """ + Returns a list of configurations that describe the functionality of the customer portal. + """ + return cast( + ListObject[Configuration], + self._requestor.request( + "get", + "/v1/billing_portal/configurations", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "ConfigurationService.CreateParams", + options: RequestOptions = {}, + ) -> Configuration: + """ + Creates a configuration that describes the functionality and behavior of a PortalSession + """ + return cast( + Configuration, + self._requestor.request( + "post", + "/v1/billing_portal/configurations", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + configuration: str, + params: "ConfigurationService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Configuration: + """ + Retrieves a configuration that describes the functionality of the customer portal. + """ + return cast( + Configuration, + self._requestor.request( + "get", + "/v1/billing_portal/configurations/{configuration}".format( + configuration=_util.sanitize_id(configuration), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + configuration: str, + params: "ConfigurationService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Configuration: + """ + Updates a configuration that describes the functionality of the customer portal. + """ + return cast( + Configuration, + self._requestor.request( + "post", + "/v1/billing_portal/configurations/{configuration}".format( + configuration=_util.sanitize_id(configuration), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/billing_portal/_session.py b/stripe/billing_portal/_session.py index f0d2715bf..8484c9092 100644 --- a/stripe/billing_portal/_session.py +++ b/stripe/billing_portal/_session.py @@ -443,16 +443,7 @@ class CreateParamsFlowDataSubscriptionUpdateConfirmItem(TypedDict): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Session.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Session": + def create(cls, **params: Unpack["Session.CreateParams"]) -> "Session": """ Creates a session of the customer portal. """ @@ -461,10 +452,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) diff --git a/stripe/billing_portal/_session_service.py b/stripe/billing_portal/_session_service.py new file mode 100644 index 000000000..004de0a8f --- /dev/null +++ b/stripe/billing_portal/_session_service.py @@ -0,0 +1,204 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.billing_portal._session import Session +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class SessionService(StripeService): + class CreateParams(TypedDict): + configuration: NotRequired["str"] + """ + The ID of an existing [configuration](https://stripe.com/docs/api/customer_portal/configuration) to use for this session, describing its functionality and features. If not specified, the session uses the default configuration. + """ + customer: str + """ + The ID of an existing customer. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + flow_data: NotRequired["SessionService.CreateParamsFlowData"] + """ + Information about a specific flow for the customer to go through. See the [docs](https://stripe.com/docs/customer-management/portal-deep-links) to learn more about using customer portal deep links and flows. + """ + locale: NotRequired[ + "Literal['auto', 'bg', 'cs', 'da', 'de', 'el', 'en', 'en-AU', 'en-CA', 'en-GB', 'en-IE', 'en-IN', 'en-NZ', 'en-SG', 'es', 'es-419', 'et', 'fi', 'fil', 'fr', 'fr-CA', 'hr', 'hu', 'id', 'it', 'ja', 'ko', 'lt', 'lv', 'ms', 'mt', 'nb', 'nl', 'pl', 'pt', 'pt-BR', 'ro', 'ru', 'sk', 'sl', 'sv', 'th', 'tr', 'vi', 'zh', 'zh-HK', 'zh-TW']" + ] + """ + The IETF language tag of the locale customer portal is displayed in. If blank or auto, the customer's `preferred_locales` or browser's locale is used. + """ + on_behalf_of: NotRequired["str"] + """ + The `on_behalf_of` account to use for this session. When specified, only subscriptions and invoices with this `on_behalf_of` account appear in the portal. For more information, see the [docs](https://stripe.com/docs/connect/separate-charges-and-transfers#on-behalf-of). Use the [Accounts API](https://stripe.com/docs/api/accounts/object#account_object-settings-branding) to modify the `on_behalf_of` account's branding settings, which the portal displays. + """ + return_url: NotRequired["str"] + """ + The default URL to redirect customers to when they click on the portal's link to return to your website. + """ + + class CreateParamsFlowData(TypedDict): + after_completion: NotRequired[ + "SessionService.CreateParamsFlowDataAfterCompletion" + ] + """ + Behavior after the flow is completed. + """ + subscription_cancel: NotRequired[ + "SessionService.CreateParamsFlowDataSubscriptionCancel" + ] + """ + Configuration when `flow_data.type=subscription_cancel`. + """ + subscription_update: NotRequired[ + "SessionService.CreateParamsFlowDataSubscriptionUpdate" + ] + """ + Configuration when `flow_data.type=subscription_update`. + """ + subscription_update_confirm: NotRequired[ + "SessionService.CreateParamsFlowDataSubscriptionUpdateConfirm" + ] + """ + Configuration when `flow_data.type=subscription_update_confirm`. + """ + type: Literal[ + "payment_method_update", + "subscription_cancel", + "subscription_update", + "subscription_update_confirm", + ] + """ + Type of flow that the customer will go through. + """ + + class CreateParamsFlowDataAfterCompletion(TypedDict): + hosted_confirmation: NotRequired[ + "SessionService.CreateParamsFlowDataAfterCompletionHostedConfirmation" + ] + """ + Configuration when `after_completion.type=hosted_confirmation`. + """ + redirect: NotRequired[ + "SessionService.CreateParamsFlowDataAfterCompletionRedirect" + ] + """ + Configuration when `after_completion.type=redirect`. + """ + type: Literal["hosted_confirmation", "portal_homepage", "redirect"] + """ + The specified behavior after the flow is completed. + """ + + class CreateParamsFlowDataAfterCompletionHostedConfirmation(TypedDict): + custom_message: NotRequired["str"] + """ + A custom message to display to the customer after the flow is completed. + """ + + class CreateParamsFlowDataAfterCompletionRedirect(TypedDict): + return_url: str + """ + The URL the customer will be redirected to after the flow is completed. + """ + + class CreateParamsFlowDataSubscriptionCancel(TypedDict): + retention: NotRequired[ + "SessionService.CreateParamsFlowDataSubscriptionCancelRetention" + ] + """ + Specify a retention strategy to be used in the cancellation flow. + """ + subscription: str + """ + The ID of the subscription to be canceled. + """ + + class CreateParamsFlowDataSubscriptionCancelRetention(TypedDict): + coupon_offer: "SessionService.CreateParamsFlowDataSubscriptionCancelRetentionCouponOffer" + """ + Configuration when `retention.type=coupon_offer`. + """ + type: Literal["coupon_offer"] + """ + Type of retention strategy to use with the customer. + """ + + class CreateParamsFlowDataSubscriptionCancelRetentionCouponOffer( + TypedDict + ): + coupon: str + """ + The ID of the coupon to be offered. + """ + + class CreateParamsFlowDataSubscriptionUpdate(TypedDict): + subscription: str + """ + The ID of the subscription to be updated. + """ + + class CreateParamsFlowDataSubscriptionUpdateConfirm(TypedDict): + discounts: NotRequired[ + "List[SessionService.CreateParamsFlowDataSubscriptionUpdateConfirmDiscount]" + ] + """ + The coupon or promotion code to apply to this subscription update. Currently, only up to one may be specified. + """ + items: List[ + "SessionService.CreateParamsFlowDataSubscriptionUpdateConfirmItem" + ] + """ + The [subscription item](https://stripe.com/docs/api/subscription_items) to be updated through this flow. Currently, only up to one may be specified and subscriptions with multiple items are not updatable. + """ + subscription: str + """ + The ID of the subscription to be updated. + """ + + class CreateParamsFlowDataSubscriptionUpdateConfirmDiscount(TypedDict): + coupon: NotRequired["str"] + """ + The ID of the coupon to apply to this subscription update. + """ + promotion_code: NotRequired["str"] + """ + The ID of a promotion code to apply to this subscription update. + """ + + class CreateParamsFlowDataSubscriptionUpdateConfirmItem(TypedDict): + id: str + """ + The ID of the [subscription item](https://stripe.com/docs/api/subscriptions/object#subscription_object-items-data-id) to be updated. + """ + price: NotRequired["str"] + """ + The price the customer should subscribe to through this flow. The price must also be included in the configuration's [`features.subscription_update.products`](https://stripe.com/docs/api/customer_portal/configuration#portal_configuration_object-features-subscription_update-products). + """ + quantity: NotRequired["int"] + """ + [Quantity](https://stripe.com/docs/subscriptions/quantities) for this item that the customer should subscribe to through this flow. + """ + + def create( + self, + params: "SessionService.CreateParams", + options: RequestOptions = {}, + ) -> Session: + """ + Creates a session of the customer portal. + """ + return cast( + Session, + self._requestor.request( + "post", + "/v1/billing_portal/sessions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/checkout/__init__.py b/stripe/checkout/__init__.py index ff7b48c5a..24665129e 100644 --- a/stripe/checkout/__init__.py +++ b/stripe/checkout/__init__.py @@ -1,3 +1,7 @@ # -*- coding: utf-8 -*- # File generated from our OpenAPI spec from stripe.checkout._session import Session as Session +from stripe.checkout._session_line_item_service import ( + SessionLineItemService as SessionLineItemService, +) +from stripe.checkout._session_service import SessionService as SessionService diff --git a/stripe/checkout/_session.py b/stripe/checkout/_session.py index 7ce0459b3..641935a7a 100644 --- a/stripe/checkout/_session.py +++ b/stripe/checkout/_session.py @@ -3703,16 +3703,7 @@ class RetrieveParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Session.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Session": + def create(cls, **params: Unpack["Session.CreateParams"]) -> "Session": """ Creates a Session object. """ @@ -3721,24 +3712,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def _cls_expire( - cls, - session: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Session.ExpireParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, session: str, **params: Unpack["Session.ExpireParams"] ) -> "Session": """ A Session can be expired when it is in one of these statuses: open @@ -3752,9 +3732,6 @@ def _cls_expire( "/v1/checkout/sessions/{session}/expire".format( session=_util.sanitize_id(session) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -3762,13 +3739,7 @@ def _cls_expire( @overload @staticmethod def expire( - session: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Session.ExpireParams" - ] # pyright: ignore[reportGeneralTypeIssues] + session: str, **params: Unpack["Session.ExpireParams"] ) -> "Session": """ A Session can be expired when it is in one of these statuses: open @@ -3778,13 +3749,7 @@ def expire( ... @overload - def expire( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Session.ExpireParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Session": + def expire(self, **params: Unpack["Session.ExpireParams"]) -> "Session": """ A Session can be expired when it is in one of these statuses: open @@ -3794,11 +3759,7 @@ def expire( @class_method_variant("_cls_expire") def expire( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Session.ExpireParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Session.ExpireParams"] ) -> "Session": """ A Session can be expired when it is in one of these statuses: open @@ -3812,20 +3773,13 @@ def expire( # pyright: ignore[reportGeneralTypeIssues] "/v1/checkout/sessions/{session}/expire".format( session=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Session.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Session.ListParams"] ) -> ListObject["Session"]: """ Returns a list of Checkout Sessions. @@ -3833,9 +3787,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -3849,14 +3800,7 @@ def list( @classmethod def _cls_list_line_items( - cls, - session: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Session.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, session: str, **params: Unpack["Session.ListLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a Checkout Session, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -3868,9 +3812,6 @@ def _cls_list_line_items( "/v1/checkout/sessions/{session}/line_items".format( session=_util.sanitize_id(session) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -3878,13 +3819,7 @@ def _cls_list_line_items( @overload @staticmethod def list_line_items( - session: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Session.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + session: str, **params: Unpack["Session.ListLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a Checkout Session, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -3893,11 +3828,7 @@ def list_line_items( @overload def list_line_items( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Session.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Session.ListLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a Checkout Session, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -3906,11 +3837,7 @@ def list_line_items( @class_method_variant("_cls_list_line_items") def list_line_items( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Session.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Session.ListLineItemsParams"] ) -> ListObject["LineItem"]: """ When retrieving a Checkout Session, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -3922,7 +3849,6 @@ def list_line_items( # pyright: ignore[reportGeneralTypeIssues] "/v1/checkout/sessions/{session}/line_items".format( session=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/checkout/_session_line_item_service.py b/stripe/checkout/_session_line_item_service.py new file mode 100644 index 000000000..a4dd80969 --- /dev/null +++ b/stripe/checkout/_session_line_item_service.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._line_item import LineItem +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class SessionLineItemService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + def list( + self, + session: str, + params: "SessionLineItemService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[LineItem]: + """ + When retrieving a Checkout Session, there is an includable line_items property containing the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. + """ + return cast( + ListObject[LineItem], + self._requestor.request( + "get", + "/v1/checkout/sessions/{session}/line_items".format( + session=_util.sanitize_id(session), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/checkout/_session_service.py b/stripe/checkout/_session_service.py new file mode 100644 index 000000000..232c7890a --- /dev/null +++ b/stripe/checkout/_session_service.py @@ -0,0 +1,2118 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.checkout._session import Session +from stripe.checkout._session_line_item_service import SessionLineItemService +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class SessionService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.line_items = SessionLineItemService(self._requestor) + + class CreateParams(TypedDict): + after_expiration: NotRequired[ + "SessionService.CreateParamsAfterExpiration" + ] + """ + Configure actions after a Checkout Session has expired. + """ + allow_promotion_codes: NotRequired["bool"] + """ + Enables user redeemable promotion codes. + """ + automatic_tax: NotRequired["SessionService.CreateParamsAutomaticTax"] + """ + Settings for automatic tax lookup for this session and resulting payments, invoices, and subscriptions. + """ + billing_address_collection: NotRequired["Literal['auto', 'required']"] + """ + Specify whether Checkout should collect the customer's billing address. + """ + cancel_url: NotRequired["str"] + """ + If set, Checkout displays a back button and customers will be directed to this URL if they decide to cancel payment and return to your website. + """ + client_reference_id: NotRequired["str"] + """ + A unique string to reference the Checkout Session. This can be a + customer ID, a cart ID, or similar, and can be used to reconcile the + session with your internal systems. + """ + consent_collection: NotRequired[ + "SessionService.CreateParamsConsentCollection" + ] + """ + Configure fields for the Checkout Session to gather active consent from customers. + """ + currency: NotRequired["str"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). Required in `setup` mode when `payment_method_types` is not set. + """ + custom_fields: NotRequired[ + "List[SessionService.CreateParamsCustomField]" + ] + """ + Collect additional information from your customer using custom fields. Up to 3 fields are supported. + """ + custom_text: NotRequired["SessionService.CreateParamsCustomText"] + """ + Display additional text for your customers using custom text. + """ + customer: NotRequired["str"] + """ + ID of an existing Customer, if one exists. In `payment` mode, the customer's most recently saved card + payment method will be used to prefill the email, name, card details, and billing address + on the Checkout page. In `subscription` mode, the customer's [default payment method](https://stripe.com/docs/api/customers/update#update_customer-invoice_settings-default_payment_method) + will be used if it's a card, otherwise the most recently saved card will be used. A valid billing address, billing name and billing email are required on the payment method for Checkout to prefill the customer's card details. + + If the Customer already has a valid [email](https://stripe.com/docs/api/customers/object#customer_object-email) set, the email will be prefilled and not editable in Checkout. + If the Customer does not have a valid `email`, Checkout will set the email entered during the session on the Customer. + + If blank for Checkout Sessions in `subscription` mode or with `customer_creation` set as `always` in `payment` mode, Checkout will create a new Customer object based on information provided during the payment flow. + + You can set [`payment_intent_data.setup_future_usage`](https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-payment_intent_data-setup_future_usage) to have Checkout automatically attach the payment method to the Customer you pass in for future reuse. + """ + customer_creation: NotRequired["Literal['always', 'if_required']"] + """ + Configure whether a Checkout Session creates a [Customer](https://stripe.com/docs/api/customers) during Session confirmation. + + When a Customer is not created, you can still retrieve email, address, and other customer data entered in Checkout + with [customer_details](https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-customer_details). + + Sessions that don't create Customers instead are grouped by [guest customers](https://stripe.com/docs/payments/checkout/guest-customers) + in the Dashboard. Promotion codes limited to first time customers will return invalid for these Sessions. + + Can only be set in `payment` and `setup` mode. + """ + customer_email: NotRequired["str"] + """ + If provided, this value will be used when the Customer object is created. + If not provided, customers will be asked to enter their email address. + Use this parameter to prefill customer data if you already have an email + on file. To access information about the customer once a session is + complete, use the `customer` field. + """ + customer_update: NotRequired[ + "SessionService.CreateParamsCustomerUpdate" + ] + """ + Controls what fields on Customer can be updated by the Checkout Session. Can only be provided when `customer` is provided. + """ + discounts: NotRequired["List[SessionService.CreateParamsDiscount]"] + """ + The coupon or promotion code to apply to this Session. Currently, only up to one may be specified. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + expires_at: NotRequired["int"] + """ + The Epoch time in seconds at which the Checkout Session will expire. It can be anywhere from 30 minutes to 24 hours after Checkout Session creation. By default, this value is 24 hours from creation. + """ + invoice_creation: NotRequired[ + "SessionService.CreateParamsInvoiceCreation" + ] + """ + Generate a post-purchase Invoice for one-time payments. + """ + line_items: NotRequired["List[SessionService.CreateParamsLineItem]"] + """ + A list of items the customer is purchasing. Use this parameter to pass one-time or recurring [Prices](https://stripe.com/docs/api/prices). + + For `payment` mode, there is a maximum of 100 line items, however it is recommended to consolidate line items if there are more than a few dozen. + + For `subscription` mode, there is a maximum of 20 line items with recurring Prices and 20 line items with one-time Prices. Line items with one-time Prices will be on the initial invoice only. + """ + locale: NotRequired[ + "Literal['auto', 'bg', 'cs', 'da', 'de', 'el', 'en', 'en-GB', 'es', 'es-419', 'et', 'fi', 'fil', 'fr', 'fr-CA', 'hr', 'hu', 'id', 'it', 'ja', 'ko', 'lt', 'lv', 'ms', 'mt', 'nb', 'nl', 'pl', 'pt', 'pt-BR', 'ro', 'ru', 'sk', 'sl', 'sv', 'th', 'tr', 'vi', 'zh', 'zh-HK', 'zh-TW']" + ] + """ + The IETF language tag of the locale Checkout is displayed in. If blank or `auto`, the browser's locale is used. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + mode: NotRequired["Literal['payment', 'setup', 'subscription']"] + """ + The mode of the Checkout Session. Pass `subscription` if the Checkout Session includes at least one recurring item. + """ + payment_intent_data: NotRequired[ + "SessionService.CreateParamsPaymentIntentData" + ] + """ + A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in `payment` mode. + """ + payment_method_collection: NotRequired[ + "Literal['always', 'if_required']" + ] + """ + Specify whether Checkout should collect a payment method. When set to `if_required`, Checkout will not collect a payment method when the total due for the session is 0. + This may occur if the Checkout Session includes a free trial or a discount. + + Can only be set in `subscription` mode. + + If you'd like information on how to collect a payment method outside of Checkout, read the guide on configuring [subscriptions with a free trial](https://stripe.com/docs/payments/checkout/free-trials). + """ + payment_method_configuration: NotRequired["str"] + """ + The ID of the payment method configuration to use with this Checkout session. + """ + payment_method_options: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptions" + ] + """ + Payment-method-specific configuration. + """ + payment_method_types: NotRequired[ + "List[Literal['acss_debit', 'affirm', 'afterpay_clearpay', 'alipay', 'au_becs_debit', 'bacs_debit', 'bancontact', 'blik', 'boleto', 'card', 'cashapp', 'customer_balance', 'eps', 'fpx', 'giropay', 'grabpay', 'ideal', 'klarna', 'konbini', 'link', 'oxxo', 'p24', 'paynow', 'paypal', 'pix', 'promptpay', 'revolut_pay', 'sepa_debit', 'sofort', 'us_bank_account', 'wechat_pay', 'zip']]" + ] + """ + A list of the types of payment methods (e.g., `card`) this Checkout Session can accept. + + You can omit this attribute to manage your payment methods from the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). + See [Dynamic Payment Methods](https://stripe.com/docs/payments/payment-methods/integration-options#using-dynamic-payment-methods) for more details. + + Read more about the supported payment methods and their requirements in our [payment + method details guide](https://stripe.com/docs/payments/checkout/payment-methods). + + If multiple payment methods are passed, Checkout will dynamically reorder them to + prioritize the most relevant payment methods based on the customer's location and + other characteristics. + """ + phone_number_collection: NotRequired[ + "SessionService.CreateParamsPhoneNumberCollection" + ] + """ + Controls phone number collection settings for the session. + + We recommend that you review your privacy policy and check with your legal contacts + before using this feature. Learn more about [collecting phone numbers with Checkout](https://stripe.com/docs/payments/checkout/phone-numbers). + """ + redirect_on_completion: NotRequired[ + "Literal['always', 'if_required', 'never']" + ] + """ + This parameter applies to `ui_mode: embedded`. By default, Stripe will always redirect to your return_url after a successful confirmation. If you set `redirect_on_completion: 'if_required'`, then we will only redirect if your user chooses a redirect-based payment method. + """ + return_url: NotRequired["str"] + """ + The URL to redirect your customer back to after they authenticate or cancel their payment on the + payment method's app or site. This parameter is required if ui_mode is `embedded` + and redirect-based payment methods are enabled on the session. + """ + setup_intent_data: NotRequired[ + "SessionService.CreateParamsSetupIntentData" + ] + """ + A subset of parameters to be passed to SetupIntent creation for Checkout Sessions in `setup` mode. + """ + shipping_address_collection: NotRequired[ + "SessionService.CreateParamsShippingAddressCollection" + ] + """ + When set, provides configuration for Checkout to collect a shipping address from a customer. + """ + shipping_options: NotRequired[ + "List[SessionService.CreateParamsShippingOption]" + ] + """ + The shipping rate options to apply to this Session. Up to a maximum of 5. + """ + submit_type: NotRequired["Literal['auto', 'book', 'donate', 'pay']"] + """ + Describes the type of transaction being performed by Checkout in order to customize + relevant text on the page, such as the submit button. `submit_type` can only be + specified on Checkout Sessions in `payment` mode, but not Checkout Sessions + in `subscription` or `setup` mode. Possible values are `auto`, `pay`, `book`, `donate`. If blank or `auto`, `pay` is used. + """ + subscription_data: NotRequired[ + "SessionService.CreateParamsSubscriptionData" + ] + """ + A subset of parameters to be passed to subscription creation for Checkout Sessions in `subscription` mode. + """ + success_url: NotRequired["str"] + """ + The URL to which Stripe should send customers when payment or setup + is complete. + This parameter is not allowed if ui_mode is `embedded`. If you'd like to use + information from the successful Checkout Session on your page, read the + guide on [customizing your success page](https://stripe.com/docs/payments/checkout/custom-success-page). + """ + tax_id_collection: NotRequired[ + "SessionService.CreateParamsTaxIdCollection" + ] + """ + Controls tax ID collection settings for the session. + """ + ui_mode: NotRequired["Literal['embedded', 'hosted']"] + """ + `ui_mode` can be `hosted` or `embedded`. The default is `hosted`. + """ + + class CreateParamsAfterExpiration(TypedDict): + recovery: NotRequired[ + "SessionService.CreateParamsAfterExpirationRecovery" + ] + """ + Configure a Checkout Session that can be used to recover an expired session. + """ + + class CreateParamsAfterExpirationRecovery(TypedDict): + allow_promotion_codes: NotRequired["bool"] + """ + Enables user redeemable promotion codes on the recovered Checkout Sessions. Defaults to `false` + """ + enabled: bool + """ + If `true`, a recovery URL will be generated to recover this Checkout Session if it + expires before a successful transaction is completed. It will be attached to the + Checkout Session object upon expiration. + """ + + class CreateParamsAutomaticTax(TypedDict): + enabled: bool + """ + Set to true to enable automatic taxes. + """ + liability: NotRequired[ + "SessionService.CreateParamsAutomaticTaxLiability" + ] + """ + The account that's liable for tax. If set, the business address and tax registrations required to perform the tax calculation are loaded from this account. The tax transaction is returned in the report of the connected account. + """ + + class CreateParamsAutomaticTaxLiability(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsConsentCollection(TypedDict): + payment_method_reuse_agreement: NotRequired[ + "SessionService.CreateParamsConsentCollectionPaymentMethodReuseAgreement" + ] + """ + Determines the display of payment method reuse agreement text in the UI. If set to `hidden`, it will hide legal text related to the reuse of a payment method. + """ + promotions: NotRequired["Literal['auto', 'none']"] + """ + If set to `auto`, enables the collection of customer consent for promotional communications. The Checkout + Session will determine whether to display an option to opt into promotional communication + from the merchant depending on the customer's locale. Only available to US merchants. + """ + terms_of_service: NotRequired["Literal['none', 'required']"] + """ + If set to `required`, it requires customers to check a terms of service checkbox before being able to pay. + There must be a valid terms of service URL set in your [Dashboard settings](https://dashboard.stripe.com/settings/public). + """ + + class CreateParamsConsentCollectionPaymentMethodReuseAgreement(TypedDict): + position: Literal["auto", "hidden"] + """ + Determines the position and visibility of the payment method reuse agreement in the UI. When set to `auto`, Stripe's + defaults will be used. When set to `hidden`, the payment method reuse agreement text will always be hidden in the UI. + """ + + class CreateParamsCustomField(TypedDict): + dropdown: NotRequired["SessionService.CreateParamsCustomFieldDropdown"] + """ + Configuration for `type=dropdown` fields. + """ + key: str + """ + String of your choice that your integration can use to reconcile this field. Must be unique to this field, alphanumeric, and up to 200 characters. + """ + label: "SessionService.CreateParamsCustomFieldLabel" + """ + The label for the field, displayed to the customer. + """ + numeric: NotRequired["SessionService.CreateParamsCustomFieldNumeric"] + """ + Configuration for `type=numeric` fields. + """ + optional: NotRequired["bool"] + """ + Whether the customer is required to complete the field before completing the Checkout Session. Defaults to `false`. + """ + text: NotRequired["SessionService.CreateParamsCustomFieldText"] + """ + Configuration for `type=text` fields. + """ + type: Literal["dropdown", "numeric", "text"] + """ + The type of the field. + """ + + class CreateParamsCustomFieldDropdown(TypedDict): + options: List["SessionService.CreateParamsCustomFieldDropdownOption"] + """ + The options available for the customer to select. Up to 200 options allowed. + """ + + class CreateParamsCustomFieldDropdownOption(TypedDict): + label: str + """ + The label for the option, displayed to the customer. Up to 100 characters. + """ + value: str + """ + The value for this option, not displayed to the customer, used by your integration to reconcile the option selected by the customer. Must be unique to this option, alphanumeric, and up to 100 characters. + """ + + class CreateParamsCustomFieldLabel(TypedDict): + custom: str + """ + Custom text for the label, displayed to the customer. Up to 50 characters. + """ + type: Literal["custom"] + """ + The type of the label. + """ + + class CreateParamsCustomFieldNumeric(TypedDict): + maximum_length: NotRequired["int"] + """ + The maximum character length constraint for the customer's input. + """ + minimum_length: NotRequired["int"] + """ + The minimum character length requirement for the customer's input. + """ + + class CreateParamsCustomFieldText(TypedDict): + maximum_length: NotRequired["int"] + """ + The maximum character length constraint for the customer's input. + """ + minimum_length: NotRequired["int"] + """ + The minimum character length requirement for the customer's input. + """ + + class CreateParamsCustomText(TypedDict): + after_submit: NotRequired[ + "Literal['']|SessionService.CreateParamsCustomTextAfterSubmit" + ] + """ + Custom text that should be displayed after the payment confirmation button. + """ + shipping_address: NotRequired[ + "Literal['']|SessionService.CreateParamsCustomTextShippingAddress" + ] + """ + Custom text that should be displayed alongside shipping address collection. + """ + submit: NotRequired[ + "Literal['']|SessionService.CreateParamsCustomTextSubmit" + ] + """ + Custom text that should be displayed alongside the payment confirmation button. + """ + terms_of_service_acceptance: NotRequired[ + "Literal['']|SessionService.CreateParamsCustomTextTermsOfServiceAcceptance" + ] + """ + Custom text that should be displayed in place of the default terms of service agreement text. + """ + + class CreateParamsCustomTextAfterSubmit(TypedDict): + message: str + """ + Text may be up to 1200 characters in length. + """ + + class CreateParamsCustomTextShippingAddress(TypedDict): + message: str + """ + Text may be up to 1200 characters in length. + """ + + class CreateParamsCustomTextSubmit(TypedDict): + message: str + """ + Text may be up to 1200 characters in length. + """ + + class CreateParamsCustomTextTermsOfServiceAcceptance(TypedDict): + message: str + """ + Text may be up to 1200 characters in length. + """ + + class CreateParamsCustomerUpdate(TypedDict): + address: NotRequired["Literal['auto', 'never']"] + """ + Describes whether Checkout saves the billing address onto `customer.address`. + To always collect a full billing address, use `billing_address_collection`. Defaults to `never`. + """ + name: NotRequired["Literal['auto', 'never']"] + """ + Describes whether Checkout saves the name onto `customer.name`. Defaults to `never`. + """ + shipping: NotRequired["Literal['auto', 'never']"] + """ + Describes whether Checkout saves shipping information onto `customer.shipping`. + To collect shipping information, use `shipping_address_collection`. Defaults to `never`. + """ + + class CreateParamsDiscount(TypedDict): + coupon: NotRequired["str"] + """ + The ID of the coupon to apply to this Session. + """ + promotion_code: NotRequired["str"] + """ + The ID of a promotion code to apply to this Session. + """ + + class CreateParamsInvoiceCreation(TypedDict): + enabled: bool + """ + Set to `true` to enable invoice creation. + """ + invoice_data: NotRequired[ + "SessionService.CreateParamsInvoiceCreationInvoiceData" + ] + """ + Parameters passed when creating invoices for payment-mode Checkout Sessions. + """ + + class CreateParamsInvoiceCreationInvoiceData(TypedDict): + account_tax_ids: NotRequired["Literal['']|List[str]"] + """ + The account tax IDs associated with the invoice. + """ + custom_fields: NotRequired[ + "Literal['']|List[SessionService.CreateParamsInvoiceCreationInvoiceDataCustomField]" + ] + """ + Default custom fields to be displayed on invoices for this customer. + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + footer: NotRequired["str"] + """ + Default footer to be displayed on invoices for this customer. + """ + issuer: NotRequired[ + "SessionService.CreateParamsInvoiceCreationInvoiceDataIssuer" + ] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + rendering_options: NotRequired[ + "Literal['']|SessionService.CreateParamsInvoiceCreationInvoiceDataRenderingOptions" + ] + """ + Default options for invoice PDF rendering for this customer. + """ + + class CreateParamsInvoiceCreationInvoiceDataCustomField(TypedDict): + name: str + """ + The name of the custom field. This may be up to 30 characters. + """ + value: str + """ + The value of the custom field. This may be up to 30 characters. + """ + + class CreateParamsInvoiceCreationInvoiceDataIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsInvoiceCreationInvoiceDataRenderingOptions(TypedDict): + amount_tax_display: NotRequired[ + "Literal['']|Literal['exclude_tax', 'include_inclusive_tax']" + ] + """ + How line-item prices and amounts will be displayed with respect to tax on invoice PDFs. One of `exclude_tax` or `include_inclusive_tax`. `include_inclusive_tax` will include inclusive tax (and exclude exclusive tax) in invoice PDF amounts. `exclude_tax` will exclude all tax (inclusive and exclusive alike) from invoice PDF amounts. + """ + + class CreateParamsLineItem(TypedDict): + adjustable_quantity: NotRequired[ + "SessionService.CreateParamsLineItemAdjustableQuantity" + ] + """ + When set, provides configuration for this item's quantity to be adjusted by the customer during Checkout. + """ + dynamic_tax_rates: NotRequired["List[str]"] + """ + The [tax rates](https://stripe.com/docs/api/tax_rates) that will be applied to this line item depending on the customer's billing/shipping address. We currently support the following countries: US, GB, AU, and all countries in the EU. + """ + price: NotRequired["str"] + """ + The ID of the [Price](https://stripe.com/docs/api/prices) or [Plan](https://stripe.com/docs/api/plans) object. One of `price` or `price_data` is required. + """ + price_data: NotRequired["SessionService.CreateParamsLineItemPriceData"] + """ + Data used to generate a new [Price](https://stripe.com/docs/api/prices) object inline. One of `price` or `price_data` is required. + """ + quantity: NotRequired["int"] + """ + The quantity of the line item being purchased. Quantity should not be defined when `recurring.usage_type=metered`. + """ + tax_rates: NotRequired["List[str]"] + """ + The [tax rates](https://stripe.com/docs/api/tax_rates) which apply to this line item. + """ + + class CreateParamsLineItemAdjustableQuantity(TypedDict): + enabled: bool + """ + Set to true if the quantity can be adjusted to any non-negative integer. By default customers will be able to remove the line item by setting the quantity to 0. + """ + maximum: NotRequired["int"] + """ + The maximum quantity the customer can purchase for the Checkout Session. By default this value is 99. You can specify a value up to 999999. + """ + minimum: NotRequired["int"] + """ + The minimum quantity the customer must purchase for the Checkout Session. By default this value is 0. + """ + + class CreateParamsLineItemPriceData(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + product: NotRequired["str"] + """ + The ID of the product that this price will belong to. One of `product` or `product_data` is required. + """ + product_data: NotRequired[ + "SessionService.CreateParamsLineItemPriceDataProductData" + ] + """ + Data used to generate a new product object inline. One of `product` or `product_data` is required. + """ + recurring: NotRequired[ + "SessionService.CreateParamsLineItemPriceDataRecurring" + ] + """ + The recurring components of a price such as `interval` and `interval_count`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Only required if a [default tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#setting-a-default-tax-behavior-(recommended)) was not provided in the Stripe Tax settings. Specifies whether the price is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. Once specified as either `inclusive` or `exclusive`, it cannot be changed. + """ + unit_amount: NotRequired["int"] + """ + A non-negative integer in cents (or local equivalent) representing how much to charge. One of `unit_amount` or `unit_amount_decimal` is required. + """ + unit_amount_decimal: NotRequired["str"] + """ + Same as `unit_amount`, but accepts a decimal value in cents (or local equivalent) with at most 12 decimal places. Only one of `unit_amount` and `unit_amount_decimal` can be set. + """ + + class CreateParamsLineItemPriceDataProductData(TypedDict): + description: NotRequired["str"] + """ + The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + """ + images: NotRequired["List[str]"] + """ + A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: str + """ + The product's name, meant to be displayable to the customer. + """ + tax_code: NotRequired["str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + """ + + class CreateParamsLineItemPriceDataRecurring(TypedDict): + interval: Literal["day", "month", "week", "year"] + """ + Specifies billing frequency. Either `day`, `week`, `month` or `year`. + """ + interval_count: NotRequired["int"] + """ + The number of intervals between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. Maximum of three years interval allowed (3 years, 36 months, or 156 weeks). + """ + + class CreateParamsPaymentIntentData(TypedDict): + application_fee_amount: NotRequired["int"] + """ + The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner's Stripe account. The amount of the application fee collected will be capped at the total payment amount. For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + """ + capture_method: NotRequired[ + "Literal['automatic', 'automatic_async', 'manual']" + ] + """ + Controls when the funds will be captured from the customer's account. + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + on_behalf_of: NotRequired["str"] + """ + The Stripe account ID for which these funds are intended. For details, + see the PaymentIntents [use case for connected + accounts](https://stripe.com/docs/payments/connected-accounts). + """ + receipt_email: NotRequired["str"] + """ + Email address that the receipt for the resulting payment will be sent to. If `receipt_email` is specified for a payment in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + """ + setup_future_usage: NotRequired["Literal['off_session', 'on_session']"] + """ + Indicates that you intend to [make future payments](https://stripe.com/docs/payments/payment-intents#future-usage) with the payment + method collected by this Checkout Session. + + When setting this to `on_session`, Checkout will show a notice to the + customer that their payment details will be saved. + + When setting this to `off_session`, Checkout will show a notice to the + customer that their payment details will be saved and used for future + payments. + + If a Customer has been provided or Checkout creates a new Customer, + Checkout will attach the payment method to the Customer. + + If Checkout does not create a Customer, the payment method is not attached + to a Customer. To reuse the payment method, you can retrieve it from the + Checkout Session's PaymentIntent. + + When processing card payments, Checkout also uses `setup_future_usage` + to dynamically optimize your payment flow and comply with regional + legislation and network rules, such as SCA. + """ + shipping: NotRequired[ + "SessionService.CreateParamsPaymentIntentDataShipping" + ] + """ + Shipping information for this payment. + """ + statement_descriptor: NotRequired["str"] + """ + Extra information about the payment. This will appear on your + customer's statement when this payment succeeds in creating a charge. + """ + statement_descriptor_suffix: NotRequired["str"] + """ + Provides information about the charge that customers see on their statements. Concatenated with the + prefix (shortened descriptor) or statement descriptor that's set on the account to form the complete + statement descriptor. Maximum 22 characters for the concatenated descriptor. + """ + transfer_data: NotRequired[ + "SessionService.CreateParamsPaymentIntentDataTransferData" + ] + """ + The parameters used to automatically create a Transfer when the payment succeeds. + For more information, see the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + """ + transfer_group: NotRequired["str"] + """ + A string that identifies the resulting payment as part of a group. See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/connect/separate-charges-and-transfers) for details. + """ + + class CreateParamsPaymentIntentDataShipping(TypedDict): + address: "SessionService.CreateParamsPaymentIntentDataShippingAddress" + """ + Shipping address. + """ + carrier: NotRequired["str"] + """ + The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. + """ + name: str + """ + Recipient name. + """ + phone: NotRequired["str"] + """ + Recipient phone (including extension). + """ + tracking_number: NotRequired["str"] + """ + The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas. + """ + + class CreateParamsPaymentIntentDataShippingAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: str + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsPaymentIntentDataTransferData(TypedDict): + amount: NotRequired["int"] + """ + The amount that will be transferred automatically when a charge succeeds. + """ + destination: str + """ + If specified, successful charges will be attributed to the destination + account for tax reporting, and the funds from charges will be transferred + to the destination account. The ID of the resulting transfer will be + returned on the successful charge's `transfer` field. + """ + + class CreateParamsPaymentMethodOptions(TypedDict): + acss_debit: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsAcssDebit" + ] + """ + contains details about the ACSS Debit payment method options. + """ + affirm: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsAffirm" + ] + """ + contains details about the Affirm payment method options. + """ + afterpay_clearpay: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsAfterpayClearpay" + ] + """ + contains details about the Afterpay Clearpay payment method options. + """ + alipay: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsAlipay" + ] + """ + contains details about the Alipay payment method options. + """ + au_becs_debit: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsAuBecsDebit" + ] + """ + contains details about the AU Becs Debit payment method options. + """ + bacs_debit: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsBacsDebit" + ] + """ + contains details about the Bacs Debit payment method options. + """ + bancontact: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsBancontact" + ] + """ + contains details about the Bancontact payment method options. + """ + boleto: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsBoleto" + ] + """ + contains details about the Boleto payment method options. + """ + card: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsCard" + ] + """ + contains details about the Card payment method options. + """ + cashapp: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsCashapp" + ] + """ + contains details about the Cashapp Pay payment method options. + """ + customer_balance: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsCustomerBalance" + ] + """ + contains details about the Customer Balance payment method options. + """ + eps: NotRequired["SessionService.CreateParamsPaymentMethodOptionsEps"] + """ + contains details about the EPS payment method options. + """ + fpx: NotRequired["SessionService.CreateParamsPaymentMethodOptionsFpx"] + """ + contains details about the FPX payment method options. + """ + giropay: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsGiropay" + ] + """ + contains details about the Giropay payment method options. + """ + grabpay: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsGrabpay" + ] + """ + contains details about the Grabpay payment method options. + """ + ideal: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsIdeal" + ] + """ + contains details about the Ideal payment method options. + """ + klarna: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsKlarna" + ] + """ + contains details about the Klarna payment method options. + """ + konbini: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsKonbini" + ] + """ + contains details about the Konbini payment method options. + """ + link: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsLink" + ] + """ + contains details about the Link payment method options. + """ + oxxo: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsOxxo" + ] + """ + contains details about the OXXO payment method options. + """ + p24: NotRequired["SessionService.CreateParamsPaymentMethodOptionsP24"] + """ + contains details about the P24 payment method options. + """ + paynow: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsPaynow" + ] + """ + contains details about the PayNow payment method options. + """ + paypal: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsPaypal" + ] + """ + contains details about the PayPal payment method options. + """ + pix: NotRequired["SessionService.CreateParamsPaymentMethodOptionsPix"] + """ + contains details about the Pix payment method options. + """ + revolut_pay: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsRevolutPay" + ] + """ + contains details about the RevolutPay payment method options. + """ + sepa_debit: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsSepaDebit" + ] + """ + contains details about the Sepa Debit payment method options. + """ + sofort: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsSofort" + ] + """ + contains details about the Sofort payment method options. + """ + us_bank_account: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsUsBankAccount" + ] + """ + contains details about the Us Bank Account payment method options. + """ + wechat_pay: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsWechatPay" + ] + """ + contains details about the WeChat Pay payment method options. + """ + + class CreateParamsPaymentMethodOptionsAcssDebit(TypedDict): + currency: NotRequired["Literal['cad', 'usd']"] + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). This is only accepted for Checkout Sessions in `setup` mode. + """ + mandate_options: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsAcssDebitMandateOptions" + ] + """ + Additional fields for Mandate creation + """ + setup_future_usage: NotRequired[ + "Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + verification_method: NotRequired[ + "Literal['automatic', 'instant', 'microdeposits']" + ] + """ + Verification method for the intent + """ + + class CreateParamsPaymentMethodOptionsAcssDebitMandateOptions(TypedDict): + custom_mandate_url: NotRequired["Literal['']|str"] + """ + A URL for custom mandate text to render during confirmation step. + The URL will be rendered with additional GET parameters `payment_intent` and `payment_intent_client_secret` when confirming a Payment Intent, + or `setup_intent` and `setup_intent_client_secret` when confirming a Setup Intent. + """ + default_for: NotRequired["List[Literal['invoice', 'subscription']]"] + """ + List of Stripe products where this mandate can be selected automatically. Only usable in `setup` mode. + """ + interval_description: NotRequired["str"] + """ + Description of the mandate interval. Only required if 'payment_schedule' parameter is 'interval' or 'combined'. + """ + payment_schedule: NotRequired[ + "Literal['combined', 'interval', 'sporadic']" + ] + """ + Payment schedule for the mandate. + """ + transaction_type: NotRequired["Literal['business', 'personal']"] + """ + Transaction type of the mandate. + """ + + class CreateParamsPaymentMethodOptionsAffirm(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsAfterpayClearpay(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsAlipay(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsAuBecsDebit(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsBacsDebit(TypedDict): + setup_future_usage: NotRequired[ + "Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsBancontact(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsBoleto(TypedDict): + expires_after_days: NotRequired["int"] + """ + The number of calendar days before a Boleto voucher expires. For example, if you create a Boleto voucher on Monday and you set expires_after_days to 2, the Boleto invoice will expire on Wednesday at 23:59 America/Sao_Paulo time. + """ + setup_future_usage: NotRequired[ + "Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsCard(TypedDict): + installments: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsCardInstallments" + ] + """ + Installment options for card payments + """ + setup_future_usage: NotRequired["Literal['off_session', 'on_session']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + statement_descriptor_suffix_kana: NotRequired["str"] + """ + Provides information about a card payment that customers see on their statements. Concatenated with the Kana prefix (shortened Kana descriptor) or Kana statement descriptor that's set on the account to form the complete statement descriptor. Maximum 22 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 22 characters. + """ + statement_descriptor_suffix_kanji: NotRequired["str"] + """ + Provides information about a card payment that customers see on their statements. Concatenated with the Kanji prefix (shortened Kanji descriptor) or Kanji statement descriptor that's set on the account to form the complete statement descriptor. Maximum 17 characters. On card statements, the *concatenation* of both prefix and suffix (including separators) will appear truncated to 17 characters. + """ + + class CreateParamsPaymentMethodOptionsCardInstallments(TypedDict): + enabled: NotRequired["bool"] + """ + Setting to true enables installments for this Checkout Session. + Setting to false will prevent any installment plan from applying to a payment. + """ + + class CreateParamsPaymentMethodOptionsCashapp(TypedDict): + setup_future_usage: NotRequired[ + "Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsCustomerBalance(TypedDict): + bank_transfer: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsCustomerBalanceBankTransfer" + ] + """ + Configuration for the bank transfer funding type, if the `funding_type` is set to `bank_transfer`. + """ + funding_type: NotRequired["Literal['bank_transfer']"] + """ + The funding method type to be used when there are not enough funds in the customer balance. Permitted values include: `bank_transfer`. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsCustomerBalanceBankTransfer( + TypedDict, + ): + eu_bank_transfer: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer" + ] + """ + Configuration for eu_bank_transfer funding type. + """ + requested_address_types: NotRequired[ + "List[Literal['aba', 'iban', 'sepa', 'sort_code', 'spei', 'swift', 'zengin']]" + ] + """ + List of address types that should be returned in the financial_addresses response. If not specified, all valid types will be returned. + + Permitted values include: `sort_code`, `zengin`, `iban`, or `spei`. + """ + type: Literal[ + "eu_bank_transfer", + "gb_bank_transfer", + "jp_bank_transfer", + "mx_bank_transfer", + "us_bank_transfer", + ] + """ + The list of bank transfer types that this PaymentIntent is allowed to use for funding. + """ + + class CreateParamsPaymentMethodOptionsCustomerBalanceBankTransferEuBankTransfer( + TypedDict, + ): + country: str + """ + The desired country code of the bank account information. Permitted values include: `BE`, `DE`, `ES`, `FR`, `IE`, or `NL`. + """ + + class CreateParamsPaymentMethodOptionsEps(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsFpx(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsGiropay(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsGrabpay(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsIdeal(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsKlarna(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsKonbini(TypedDict): + expires_after_days: NotRequired["int"] + """ + The number of calendar days (between 1 and 60) after which Konbini payment instructions will expire. For example, if a PaymentIntent is confirmed with Konbini and `expires_after_days` set to 2 on Monday JST, the instructions will expire on Wednesday 23:59:59 JST. Defaults to 3 days. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsLink(TypedDict): + setup_future_usage: NotRequired["Literal['none', 'off_session']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsOxxo(TypedDict): + expires_after_days: NotRequired["int"] + """ + The number of calendar days before an OXXO voucher expires. For example, if you create an OXXO voucher on Monday and you set expires_after_days to 2, the OXXO invoice will expire on Wednesday at 23:59 America/Mexico_City time. + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsP24(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + tos_shown_and_accepted: NotRequired["bool"] + """ + Confirm that the payer has accepted the P24 terms and conditions. + """ + + class CreateParamsPaymentMethodOptionsPaynow(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsPaypal(TypedDict): + capture_method: NotRequired["Literal['']|Literal['manual']"] + """ + Controls when the funds will be captured from the customer's account. + """ + preferred_locale: NotRequired[ + "Literal['cs-CZ', 'da-DK', 'de-AT', 'de-DE', 'de-LU', 'el-GR', 'en-GB', 'en-US', 'es-ES', 'fi-FI', 'fr-BE', 'fr-FR', 'fr-LU', 'hu-HU', 'it-IT', 'nl-BE', 'nl-NL', 'pl-PL', 'pt-PT', 'sk-SK', 'sv-SE']" + ] + """ + [Preferred locale](https://stripe.com/docs/payments/paypal/supported-locales) of the PayPal checkout page that the customer is redirected to. + """ + reference: NotRequired["str"] + """ + A reference of the PayPal transaction visible to customer which is mapped to PayPal's invoice ID. This must be a globally unique ID if you have configured in your PayPal settings to block multiple payments per invoice ID. + """ + risk_correlation_id: NotRequired["str"] + """ + The risk correlation ID for an on-session payment using a saved PayPal payment method. + """ + setup_future_usage: NotRequired[ + "Literal['']|Literal['none', 'off_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + + If `setup_future_usage` is already set and you are performing a request using a publishable key, you may only update the value from `on_session` to `off_session`. + """ + + class CreateParamsPaymentMethodOptionsPix(TypedDict): + expires_after_seconds: NotRequired["int"] + """ + The number of seconds (between 10 and 1209600) after which Pix payment will expire. Defaults to 86400 seconds. + """ + + class CreateParamsPaymentMethodOptionsRevolutPay(TypedDict): + setup_future_usage: NotRequired["Literal['none', 'off_session']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsSepaDebit(TypedDict): + setup_future_usage: NotRequired[ + "Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsSofort(TypedDict): + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPaymentMethodOptionsUsBankAccount(TypedDict): + financial_connections: NotRequired[ + "SessionService.CreateParamsPaymentMethodOptionsUsBankAccountFinancialConnections" + ] + """ + Additional fields for Financial Connections Session creation + """ + setup_future_usage: NotRequired[ + "Literal['none', 'off_session', 'on_session']" + ] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + verification_method: NotRequired["Literal['automatic', 'instant']"] + """ + Verification method for the intent + """ + + class CreateParamsPaymentMethodOptionsUsBankAccountFinancialConnections( + TypedDict, + ): + permissions: NotRequired[ + "List[Literal['balances', 'ownership', 'payment_method', 'transactions']]" + ] + """ + The list of permissions to request. If this parameter is passed, the `payment_method` permission must be included. Valid permissions include: `balances`, `ownership`, `payment_method`, and `transactions`. + """ + prefetch: NotRequired["List[Literal['balances', 'transactions']]"] + """ + List of data features that you would like to retrieve upon account creation. + """ + + class CreateParamsPaymentMethodOptionsWechatPay(TypedDict): + app_id: NotRequired["str"] + """ + The app ID registered with WeChat Pay. Only required when client is ios or android. + """ + client: Literal["android", "ios", "web"] + """ + The client type that the end customer will pay from + """ + setup_future_usage: NotRequired["Literal['none']"] + """ + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + """ + + class CreateParamsPhoneNumberCollection(TypedDict): + enabled: bool + """ + Set to `true` to enable phone number collection. + """ + + class CreateParamsSetupIntentData(TypedDict): + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + on_behalf_of: NotRequired["str"] + """ + The Stripe account for which the setup is intended. + """ + + class CreateParamsShippingAddressCollection(TypedDict): + allowed_countries: List[ + Literal[ + "AC", + "AD", + "AE", + "AF", + "AG", + "AI", + "AL", + "AM", + "AO", + "AQ", + "AR", + "AT", + "AU", + "AW", + "AX", + "AZ", + "BA", + "BB", + "BD", + "BE", + "BF", + "BG", + "BH", + "BI", + "BJ", + "BL", + "BM", + "BN", + "BO", + "BQ", + "BR", + "BS", + "BT", + "BV", + "BW", + "BY", + "BZ", + "CA", + "CD", + "CF", + "CG", + "CH", + "CI", + "CK", + "CL", + "CM", + "CN", + "CO", + "CR", + "CV", + "CW", + "CY", + "CZ", + "DE", + "DJ", + "DK", + "DM", + "DO", + "DZ", + "EC", + "EE", + "EG", + "EH", + "ER", + "ES", + "ET", + "FI", + "FJ", + "FK", + "FO", + "FR", + "GA", + "GB", + "GD", + "GE", + "GF", + "GG", + "GH", + "GI", + "GL", + "GM", + "GN", + "GP", + "GQ", + "GR", + "GS", + "GT", + "GU", + "GW", + "GY", + "HK", + "HN", + "HR", + "HT", + "HU", + "ID", + "IE", + "IL", + "IM", + "IN", + "IO", + "IQ", + "IS", + "IT", + "JE", + "JM", + "JO", + "JP", + "KE", + "KG", + "KH", + "KI", + "KM", + "KN", + "KR", + "KW", + "KY", + "KZ", + "LA", + "LB", + "LC", + "LI", + "LK", + "LR", + "LS", + "LT", + "LU", + "LV", + "LY", + "MA", + "MC", + "MD", + "ME", + "MF", + "MG", + "MK", + "ML", + "MM", + "MN", + "MO", + "MQ", + "MR", + "MS", + "MT", + "MU", + "MV", + "MW", + "MX", + "MY", + "MZ", + "NA", + "NC", + "NE", + "NG", + "NI", + "NL", + "NO", + "NP", + "NR", + "NU", + "NZ", + "OM", + "PA", + "PE", + "PF", + "PG", + "PH", + "PK", + "PL", + "PM", + "PN", + "PR", + "PS", + "PT", + "PY", + "QA", + "RE", + "RO", + "RS", + "RU", + "RW", + "SA", + "SB", + "SC", + "SE", + "SG", + "SH", + "SI", + "SJ", + "SK", + "SL", + "SM", + "SN", + "SO", + "SR", + "SS", + "ST", + "SV", + "SX", + "SZ", + "TA", + "TC", + "TD", + "TF", + "TG", + "TH", + "TJ", + "TK", + "TL", + "TM", + "TN", + "TO", + "TR", + "TT", + "TV", + "TW", + "TZ", + "UA", + "UG", + "US", + "UY", + "UZ", + "VA", + "VC", + "VE", + "VG", + "VN", + "VU", + "WF", + "WS", + "XK", + "YE", + "YT", + "ZA", + "ZM", + "ZW", + "ZZ", + ] + ] + """ + An array of two-letter ISO country codes representing which countries Checkout should provide as options for + shipping locations. Unsupported country codes: `AS, CX, CC, CU, HM, IR, KP, MH, FM, NF, MP, PW, SD, SY, UM, VI`. + """ + + class CreateParamsShippingOption(TypedDict): + shipping_rate: NotRequired["str"] + """ + The ID of the Shipping Rate to use for this shipping option. + """ + shipping_rate_data: NotRequired[ + "SessionService.CreateParamsShippingOptionShippingRateData" + ] + """ + Parameters to be passed to Shipping Rate creation for this shipping option + """ + + class CreateParamsShippingOptionShippingRateData(TypedDict): + delivery_estimate: NotRequired[ + "SessionService.CreateParamsShippingOptionShippingRateDataDeliveryEstimate" + ] + """ + The estimated range for how long shipping will take, meant to be displayable to the customer. This will appear on CheckoutSessions. + """ + display_name: str + """ + The name of the shipping rate, meant to be displayable to the customer. This will appear on CheckoutSessions. + """ + fixed_amount: NotRequired[ + "SessionService.CreateParamsShippingOptionShippingRateDataFixedAmount" + ] + """ + Describes a fixed amount to charge for shipping. Must be present if type is `fixed_amount`. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + """ + tax_code: NotRequired["str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. The Shipping tax code is `txcd_92010001`. + """ + type: NotRequired["Literal['fixed_amount']"] + """ + The type of calculation to use on the shipping rate. Can only be `fixed_amount` for now. + """ + + class CreateParamsShippingOptionShippingRateDataDeliveryEstimate( + TypedDict + ): + maximum: NotRequired[ + "SessionService.CreateParamsShippingOptionShippingRateDataDeliveryEstimateMaximum" + ] + """ + The upper bound of the estimated range. If empty, represents no upper bound i.e., infinite. + """ + minimum: NotRequired[ + "SessionService.CreateParamsShippingOptionShippingRateDataDeliveryEstimateMinimum" + ] + """ + The lower bound of the estimated range. If empty, represents no lower bound. + """ + + class CreateParamsShippingOptionShippingRateDataDeliveryEstimateMaximum( + TypedDict, + ): + unit: Literal["business_day", "day", "hour", "month", "week"] + """ + A unit of time. + """ + value: int + """ + Must be greater than 0. + """ + + class CreateParamsShippingOptionShippingRateDataDeliveryEstimateMinimum( + TypedDict, + ): + unit: Literal["business_day", "day", "hour", "month", "week"] + """ + A unit of time. + """ + value: int + """ + Must be greater than 0. + """ + + class CreateParamsShippingOptionShippingRateDataFixedAmount(TypedDict): + amount: int + """ + A non-negative integer in cents representing how much to charge. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + currency_options: NotRequired[ + "Dict[str, SessionService.CreateParamsShippingOptionShippingRateDataFixedAmountCurrencyOptions]" + ] + """ + Shipping rates defined in each available currency option. Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies). + """ + + class CreateParamsShippingOptionShippingRateDataFixedAmountCurrencyOptions( + TypedDict, + ): + amount: int + """ + A non-negative integer in cents representing how much to charge. + """ + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'unspecified']" + ] + """ + Specifies whether the rate is considered inclusive of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + """ + + class CreateParamsSubscriptionData(TypedDict): + application_fee_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account. To use an application fee percent, the request must be made on behalf of another account, using the `Stripe-Account` header or an OAuth key. For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + """ + billing_cycle_anchor: NotRequired["int"] + """ + A future timestamp to anchor the subscription's billing cycle for new subscriptions. + """ + default_tax_rates: NotRequired["List[str]"] + """ + The tax rates that will apply to any subscription item that does not have + `tax_rates` set. Invoices created will have their `default_tax_rates` populated + from the subscription. + """ + description: NotRequired["str"] + """ + The subscription's description, meant to be displayable to the customer. + Use this field to optionally store an explanation of the subscription + for rendering in the [customer portal](https://stripe.com/docs/customer-management). + """ + invoice_settings: NotRequired[ + "SessionService.CreateParamsSubscriptionDataInvoiceSettings" + ] + """ + All invoices will be billed using the specified settings. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + on_behalf_of: NotRequired["str"] + """ + The account on behalf of which to charge, for each of the subscription's invoices. + """ + proration_behavior: NotRequired["Literal['create_prorations', 'none']"] + """ + Determines how to handle prorations resulting from the `billing_cycle_anchor`. If no value is passed, the default is `create_prorations`. + """ + transfer_data: NotRequired[ + "SessionService.CreateParamsSubscriptionDataTransferData" + ] + """ + If specified, the funds from the subscription's invoices will be transferred to the destination and the ID of the resulting transfers will be found on the resulting charges. + """ + trial_end: NotRequired["int"] + """ + Unix timestamp representing the end of the trial period the customer + will get before being charged for the first time. Has to be at least + 48 hours in the future. + """ + trial_period_days: NotRequired["int"] + """ + Integer representing the number of trial period days before the + customer is charged for the first time. Has to be at least 1. + """ + trial_settings: NotRequired[ + "SessionService.CreateParamsSubscriptionDataTrialSettings" + ] + """ + Settings related to subscription trials. + """ + + class CreateParamsSubscriptionDataInvoiceSettings(TypedDict): + issuer: NotRequired[ + "SessionService.CreateParamsSubscriptionDataInvoiceSettingsIssuer" + ] + """ + The connected account that issues the invoice. The invoice is presented with the branding and support information of the specified account. + """ + + class CreateParamsSubscriptionDataInvoiceSettingsIssuer(TypedDict): + account: NotRequired["str"] + """ + The connected account being referenced when `type` is `account`. + """ + type: Literal["account", "self"] + """ + Type of the account referenced in the request. + """ + + class CreateParamsSubscriptionDataTransferData(TypedDict): + amount_percent: NotRequired["float"] + """ + A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the destination account. By default, the entire amount is transferred to the destination. + """ + destination: str + """ + ID of an existing, connected Stripe account. + """ + + class CreateParamsSubscriptionDataTrialSettings(TypedDict): + end_behavior: "SessionService.CreateParamsSubscriptionDataTrialSettingsEndBehavior" + """ + Defines how the subscription should behave when the user's free trial ends. + """ + + class CreateParamsSubscriptionDataTrialSettingsEndBehavior(TypedDict): + missing_payment_method: Literal["cancel", "create_invoice", "pause"] + """ + Indicates how the subscription should change when the trial ends if the user did not provide a payment method. + """ + + class CreateParamsTaxIdCollection(TypedDict): + enabled: bool + """ + Set to true to enable Tax ID collection. + """ + + class ExpireParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ListParams(TypedDict): + created: NotRequired["SessionService.ListParamsCreated|int"] + """ + Only return the Checkout Sessions that were created during the given date interval. + """ + customer: NotRequired["str"] + """ + Only return the Checkout Sessions for the Customer specified. + """ + customer_details: NotRequired[ + "SessionService.ListParamsCustomerDetails" + ] + """ + Only return the Checkout Sessions for the Customer details specified. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + payment_intent: NotRequired["str"] + """ + Only return the Checkout Session for the PaymentIntent specified. + """ + payment_link: NotRequired["str"] + """ + Only return the Checkout Sessions for the Payment Link specified. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired["Literal['complete', 'expired', 'open']"] + """ + Only return the Checkout Sessions matching the given status. + """ + subscription: NotRequired["str"] + """ + Only return the Checkout Session for the subscription specified. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ListParamsCustomerDetails(TypedDict): + email: str + """ + Customer's email address. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "SessionService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Session]: + """ + Returns a list of Checkout Sessions. + """ + return cast( + ListObject[Session], + self._requestor.request( + "get", + "/v1/checkout/sessions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "SessionService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Session: + """ + Creates a Session object. + """ + return cast( + Session, + self._requestor.request( + "post", + "/v1/checkout/sessions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + session: str, + params: "SessionService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Session: + """ + Retrieves a Session object. + """ + return cast( + Session, + self._requestor.request( + "get", + "/v1/checkout/sessions/{session}".format( + session=_util.sanitize_id(session), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def expire( + self, + session: str, + params: "SessionService.ExpireParams" = {}, + options: RequestOptions = {}, + ) -> Session: + """ + A Session can be expired when it is in one of these statuses: open + + After it expires, a customer can't complete a Session and customers loading the Session see a message saying the Session is expired. + """ + return cast( + Session, + self._requestor.request( + "post", + "/v1/checkout/sessions/{session}/expire".format( + session=_util.sanitize_id(session), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/climate/__init__.py b/stripe/climate/__init__.py index df69e6864..3bc9fb7ee 100644 --- a/stripe/climate/__init__.py +++ b/stripe/climate/__init__.py @@ -1,5 +1,8 @@ # -*- coding: utf-8 -*- # File generated from our OpenAPI spec from stripe.climate._order import Order as Order +from stripe.climate._order_service import OrderService as OrderService from stripe.climate._product import Product as Product +from stripe.climate._product_service import ProductService as ProductService from stripe.climate._supplier import Supplier as Supplier +from stripe.climate._supplier_service import SupplierService as SupplierService diff --git a/stripe/climate/_order.py b/stripe/climate/_order.py index 5bd51a054..fb258f9bb 100644 --- a/stripe/climate/_order.py +++ b/stripe/climate/_order.py @@ -265,14 +265,7 @@ class RetrieveParams(RequestOptions): @classmethod def _cls_cancel( - cls, - order: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Order.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, order: str, **params: Unpack["Order.CancelParams"] ) -> "Order": """ Cancels a Climate order. You can cancel an order within 30 days of creation. Stripe refunds the @@ -287,24 +280,13 @@ def _cls_cancel( "/v1/climate/orders/{order}/cancel".format( order=_util.sanitize_id(order) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @overload @staticmethod - def cancel( - order: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Order.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Order": + def cancel(order: str, **params: Unpack["Order.CancelParams"]) -> "Order": """ Cancels a Climate order. You can cancel an order within 30 days of creation. Stripe refunds the reservation amount_subtotal, but not the amount_fees for user-triggered cancellations. Frontier @@ -314,13 +296,7 @@ def cancel( ... @overload - def cancel( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Order.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Order": + def cancel(self, **params: Unpack["Order.CancelParams"]) -> "Order": """ Cancels a Climate order. You can cancel an order within 30 days of creation. Stripe refunds the reservation amount_subtotal, but not the amount_fees for user-triggered cancellations. Frontier @@ -331,11 +307,7 @@ def cancel( @class_method_variant("_cls_cancel") def cancel( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Order.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Order.CancelParams"] ) -> "Order": """ Cancels a Climate order. You can cancel an order within 30 days of creation. Stripe refunds the @@ -350,22 +322,12 @@ def cancel( # pyright: ignore[reportGeneralTypeIssues] "/v1/climate/orders/{order}/cancel".format( order=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Order.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Order": + def create(cls, **params: Unpack["Order.CreateParams"]) -> "Order": """ Creates a Climate order object for a given Climate product. The order will be processed immediately after creation and payment will be deducted your Stripe balance. @@ -375,24 +337,12 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod - def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Order.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> ListObject["Order"]: + def list(cls, **params: Unpack["Order.ListParams"]) -> ListObject["Order"]: """ Lists all Climate order objects. The orders are returned sorted by creation date, with the most recently created orders appearing first. @@ -400,9 +350,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/climate/_order_service.py b/stripe/climate/_order_service.py new file mode 100644 index 000000000..bf8a9df7c --- /dev/null +++ b/stripe/climate/_order_service.py @@ -0,0 +1,211 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.climate._order import Order +from typing import Dict, List, Union, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class OrderService(StripeService): + class CancelParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CreateParams(TypedDict): + amount: NotRequired["int"] + """ + Requested amount of carbon removal units. Either this or `metric_tons` must be specified. + """ + beneficiary: NotRequired["OrderService.CreateParamsBeneficiary"] + """ + Publicly sharable reference for the end beneficiary of carbon removal. Assumed to be the Stripe account if not set. + """ + currency: NotRequired["str"] + """ + Request currency for the order as a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a supported [settlement currency for your account](https://stripe.com/docs/currencies). If omitted, the account's default currency will be used. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + metric_tons: NotRequired["str"] + """ + Requested number of tons for the order. Either this or `amount` must be specified. + """ + product: str + """ + Unique identifier of the Climate product. + """ + + class CreateParamsBeneficiary(TypedDict): + public_name: str + """ + Publicly displayable name for the end beneficiary of carbon removal. + """ + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + beneficiary: NotRequired[ + "Literal['']|OrderService.UpdateParamsBeneficiary" + ] + """ + Publicly sharable reference for the end beneficiary of carbon removal. Assumed to be the Stripe account if not set. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class UpdateParamsBeneficiary(TypedDict): + public_name: Union[Literal[""], str] + """ + Publicly displayable name for the end beneficiary of carbon removal. + """ + + def list( + self, + params: "OrderService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Order]: + """ + Lists all Climate order objects. The orders are returned sorted by creation date, with the + most recently created orders appearing first. + """ + return cast( + ListObject[Order], + self._requestor.request( + "get", + "/v1/climate/orders", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, params: "OrderService.CreateParams", options: RequestOptions = {} + ) -> Order: + """ + Creates a Climate order object for a given Climate product. The order will be processed immediately + after creation and payment will be deducted your Stripe balance. + """ + return cast( + Order, + self._requestor.request( + "post", + "/v1/climate/orders", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + order: str, + params: "OrderService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Order: + """ + Retrieves the details of a Climate order object with the given ID. + """ + return cast( + Order, + self._requestor.request( + "get", + "/v1/climate/orders/{order}".format( + order=_util.sanitize_id(order), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + order: str, + params: "OrderService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Order: + """ + Updates the specified order by setting the values of the parameters passed. + """ + return cast( + Order, + self._requestor.request( + "post", + "/v1/climate/orders/{order}".format( + order=_util.sanitize_id(order), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def cancel( + self, + order: str, + params: "OrderService.CancelParams" = {}, + options: RequestOptions = {}, + ) -> Order: + """ + Cancels a Climate order. You can cancel an order within 30 days of creation. Stripe refunds the + reservation amount_subtotal, but not the amount_fees for user-triggered cancellations. Frontier + might cancel reservations if suppliers fail to deliver. If Frontier cancels the reservation, Stripe + provides 90 days advance notice and refunds the amount_total. + """ + return cast( + Order, + self._requestor.request( + "post", + "/v1/climate/orders/{order}/cancel".format( + order=_util.sanitize_id(order), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/climate/_product.py b/stripe/climate/_product.py index b94367da8..a6ba2fa56 100644 --- a/stripe/climate/_product.py +++ b/stripe/climate/_product.py @@ -98,13 +98,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Product.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Product.ListParams"] ) -> ListObject["Product"]: """ Lists all available Climate product objects. @@ -112,9 +106,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/climate/_product_service.py b/stripe/climate/_product_service.py new file mode 100644 index 000000000..a6489d1be --- /dev/null +++ b/stripe/climate/_product_service.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.climate._product import Product +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class ProductService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "ProductService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Product]: + """ + Lists all available Climate product objects. + """ + return cast( + ListObject[Product], + self._requestor.request( + "get", + "/v1/climate/products", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + product: str, + params: "ProductService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Product: + """ + Retrieves the details of a Climate product with the given ID. + """ + return cast( + Product, + self._requestor.request( + "get", + "/v1/climate/products/{product}".format( + product=_util.sanitize_id(product), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/climate/_supplier.py b/stripe/climate/_supplier.py index 3ed3aee89..63e97b0dc 100644 --- a/stripe/climate/_supplier.py +++ b/stripe/climate/_supplier.py @@ -97,13 +97,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Supplier.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Supplier.ListParams"] ) -> ListObject["Supplier"]: """ Lists all available Climate supplier objects. @@ -111,9 +105,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/climate/_supplier_service.py b/stripe/climate/_supplier_service.py new file mode 100644 index 000000000..74782c343 --- /dev/null +++ b/stripe/climate/_supplier_service.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.climate._supplier import Supplier +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class SupplierService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "SupplierService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Supplier]: + """ + Lists all available Climate supplier objects. + """ + return cast( + ListObject[Supplier], + self._requestor.request( + "get", + "/v1/climate/suppliers", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + supplier: str, + params: "SupplierService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Supplier: + """ + Retrieves a Climate supplier object. + """ + return cast( + Supplier, + self._requestor.request( + "get", + "/v1/climate/suppliers/{supplier}".format( + supplier=_util.sanitize_id(supplier), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/financial_connections/__init__.py b/stripe/financial_connections/__init__.py index 066cd8584..66673d1ef 100644 --- a/stripe/financial_connections/__init__.py +++ b/stripe/financial_connections/__init__.py @@ -4,10 +4,22 @@ from stripe.financial_connections._account_owner import ( AccountOwner as AccountOwner, ) +from stripe.financial_connections._account_owner_service import ( + AccountOwnerService as AccountOwnerService, +) from stripe.financial_connections._account_ownership import ( AccountOwnership as AccountOwnership, ) +from stripe.financial_connections._account_service import ( + AccountService as AccountService, +) from stripe.financial_connections._session import Session as Session +from stripe.financial_connections._session_service import ( + SessionService as SessionService, +) from stripe.financial_connections._transaction import ( Transaction as Transaction, ) +from stripe.financial_connections._transaction_service import ( + TransactionService as TransactionService, +) diff --git a/stripe/financial_connections/_account.py b/stripe/financial_connections/_account.py index 4b5041b31..b85080834 100644 --- a/stripe/financial_connections/_account.py +++ b/stripe/financial_connections/_account.py @@ -334,14 +334,7 @@ class UnsubscribeParams(RequestOptions): @classmethod def _cls_disconnect( - cls, - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.DisconnectParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, account: str, **params: Unpack["Account.DisconnectParams"] ) -> "Account": """ Disables your access to a Financial Connections Account. You will no longer be able to access data associated with the account (e.g. balances, transactions). @@ -353,9 +346,6 @@ def _cls_disconnect( "/v1/financial_connections/accounts/{account}/disconnect".format( account=_util.sanitize_id(account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -363,13 +353,7 @@ def _cls_disconnect( @overload @staticmethod def disconnect( - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.DisconnectParams" - ] # pyright: ignore[reportGeneralTypeIssues] + account: str, **params: Unpack["Account.DisconnectParams"] ) -> "Account": """ Disables your access to a Financial Connections Account. You will no longer be able to access data associated with the account (e.g. balances, transactions). @@ -378,11 +362,7 @@ def disconnect( @overload def disconnect( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.DisconnectParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Account.DisconnectParams"] ) -> "Account": """ Disables your access to a Financial Connections Account. You will no longer be able to access data associated with the account (e.g. balances, transactions). @@ -391,11 +371,7 @@ def disconnect( @class_method_variant("_cls_disconnect") def disconnect( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.DisconnectParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Account.DisconnectParams"] ) -> "Account": """ Disables your access to a Financial Connections Account. You will no longer be able to access data associated with the account (e.g. balances, transactions). @@ -407,20 +383,13 @@ def disconnect( # pyright: ignore[reportGeneralTypeIssues] "/v1/financial_connections/accounts/{account}/disconnect".format( account=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Account.ListParams"] ) -> ListObject["Account"]: """ Returns a list of Financial Connections Account objects. @@ -428,9 +397,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -444,14 +410,7 @@ def list( @classmethod def _cls_list_owners( - cls, - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.ListOwnersParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, account: str, **params: Unpack["Account.ListOwnersParams"] ) -> ListObject["AccountOwner"]: """ Lists all owners for a given Account @@ -463,9 +422,6 @@ def _cls_list_owners( "/v1/financial_connections/accounts/{account}/owners".format( account=_util.sanitize_id(account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -473,13 +429,7 @@ def _cls_list_owners( @overload @staticmethod def list_owners( - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.ListOwnersParams" - ] # pyright: ignore[reportGeneralTypeIssues] + account: str, **params: Unpack["Account.ListOwnersParams"] ) -> ListObject["AccountOwner"]: """ Lists all owners for a given Account @@ -488,11 +438,7 @@ def list_owners( @overload def list_owners( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.ListOwnersParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Account.ListOwnersParams"] ) -> ListObject["AccountOwner"]: """ Lists all owners for a given Account @@ -501,11 +447,7 @@ def list_owners( @class_method_variant("_cls_list_owners") def list_owners( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.ListOwnersParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Account.ListOwnersParams"] ) -> ListObject["AccountOwner"]: """ Lists all owners for a given Account @@ -517,21 +459,13 @@ def list_owners( # pyright: ignore[reportGeneralTypeIssues] "/v1/financial_connections/accounts/{account}/owners".format( account=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_refresh_account( - cls, - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.RefreshAccountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, account: str, **params: Unpack["Account.RefreshAccountParams"] ) -> "Account": """ Refreshes the data associated with a Financial Connections Account. @@ -543,9 +477,6 @@ def _cls_refresh_account( "/v1/financial_connections/accounts/{account}/refresh".format( account=_util.sanitize_id(account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -553,13 +484,7 @@ def _cls_refresh_account( @overload @staticmethod def refresh_account( - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.RefreshAccountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + account: str, **params: Unpack["Account.RefreshAccountParams"] ) -> "Account": """ Refreshes the data associated with a Financial Connections Account. @@ -568,11 +493,7 @@ def refresh_account( @overload def refresh_account( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.RefreshAccountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Account.RefreshAccountParams"] ) -> "Account": """ Refreshes the data associated with a Financial Connections Account. @@ -581,11 +502,7 @@ def refresh_account( @class_method_variant("_cls_refresh_account") def refresh_account( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.RefreshAccountParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Account.RefreshAccountParams"] ) -> "Account": """ Refreshes the data associated with a Financial Connections Account. @@ -597,7 +514,6 @@ def refresh_account( # pyright: ignore[reportGeneralTypeIssues] "/v1/financial_connections/accounts/{account}/refresh".format( account=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -615,14 +531,7 @@ def retrieve( @classmethod def _cls_subscribe( - cls, - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.SubscribeParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, account: str, **params: Unpack["Account.SubscribeParams"] ) -> "Account": """ Subscribes to periodic refreshes of data associated with a Financial Connections Account. @@ -634,9 +543,6 @@ def _cls_subscribe( "/v1/financial_connections/accounts/{account}/subscribe".format( account=_util.sanitize_id(account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -644,13 +550,7 @@ def _cls_subscribe( @overload @staticmethod def subscribe( - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.SubscribeParams" - ] # pyright: ignore[reportGeneralTypeIssues] + account: str, **params: Unpack["Account.SubscribeParams"] ) -> "Account": """ Subscribes to periodic refreshes of data associated with a Financial Connections Account. @@ -659,11 +559,7 @@ def subscribe( @overload def subscribe( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.SubscribeParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Account.SubscribeParams"] ) -> "Account": """ Subscribes to periodic refreshes of data associated with a Financial Connections Account. @@ -672,11 +568,7 @@ def subscribe( @class_method_variant("_cls_subscribe") def subscribe( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.SubscribeParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Account.SubscribeParams"] ) -> "Account": """ Subscribes to periodic refreshes of data associated with a Financial Connections Account. @@ -688,21 +580,13 @@ def subscribe( # pyright: ignore[reportGeneralTypeIssues] "/v1/financial_connections/accounts/{account}/subscribe".format( account=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_unsubscribe( - cls, - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.UnsubscribeParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, account: str, **params: Unpack["Account.UnsubscribeParams"] ) -> "Account": """ Unsubscribes from periodic refreshes of data associated with a Financial Connections Account. @@ -714,9 +598,6 @@ def _cls_unsubscribe( "/v1/financial_connections/accounts/{account}/unsubscribe".format( account=_util.sanitize_id(account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -724,13 +605,7 @@ def _cls_unsubscribe( @overload @staticmethod def unsubscribe( - account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Account.UnsubscribeParams" - ] # pyright: ignore[reportGeneralTypeIssues] + account: str, **params: Unpack["Account.UnsubscribeParams"] ) -> "Account": """ Unsubscribes from periodic refreshes of data associated with a Financial Connections Account. @@ -739,11 +614,7 @@ def unsubscribe( @overload def unsubscribe( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.UnsubscribeParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Account.UnsubscribeParams"] ) -> "Account": """ Unsubscribes from periodic refreshes of data associated with a Financial Connections Account. @@ -752,11 +623,7 @@ def unsubscribe( @class_method_variant("_cls_unsubscribe") def unsubscribe( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Account.UnsubscribeParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Account.UnsubscribeParams"] ) -> "Account": """ Unsubscribes from periodic refreshes of data associated with a Financial Connections Account. @@ -768,7 +635,6 @@ def unsubscribe( # pyright: ignore[reportGeneralTypeIssues] "/v1/financial_connections/accounts/{account}/unsubscribe".format( account=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/financial_connections/_account_owner_service.py b/stripe/financial_connections/_account_owner_service.py new file mode 100644 index 000000000..27f56d6ee --- /dev/null +++ b/stripe/financial_connections/_account_owner_service.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.financial_connections._account_owner import AccountOwner +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class AccountOwnerService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + ownership: str + """ + The ID of the ownership object to fetch owners from. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + def list( + self, + account: str, + params: "AccountOwnerService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[AccountOwner]: + """ + Lists all owners for a given Account + """ + return cast( + ListObject[AccountOwner], + self._requestor.request( + "get", + "/v1/financial_connections/accounts/{account}/owners".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/financial_connections/_account_service.py b/stripe/financial_connections/_account_service.py new file mode 100644 index 000000000..4760d4408 --- /dev/null +++ b/stripe/financial_connections/_account_service.py @@ -0,0 +1,231 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.financial_connections._account import Account +from stripe.financial_connections._account_owner_service import ( + AccountOwnerService, +) +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class AccountService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.owners = AccountOwnerService(self._requestor) + + class DisconnectParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ListParams(TypedDict): + account_holder: NotRequired["AccountService.ListParamsAccountHolder"] + """ + If present, only return accounts that belong to the specified account holder. `account_holder[customer]` and `account_holder[account]` are mutually exclusive. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + session: NotRequired["str"] + """ + If present, only return accounts that were collected as part of the given session. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsAccountHolder(TypedDict): + account: NotRequired["str"] + """ + The ID of the Stripe account whose accounts will be retrieved. + """ + customer: NotRequired["str"] + """ + The ID of the Stripe customer whose accounts will be retrieved. + """ + + class RefreshParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + features: List[Literal["balance", "ownership", "transactions"]] + """ + The list of account features that you would like to refresh. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class SubscribeParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + features: List[Literal["transactions"]] + """ + The list of account features to which you would like to subscribe. + """ + + class UnsubscribeParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + features: List[Literal["transactions"]] + """ + The list of account features from which you would like to unsubscribe. + """ + + def list( + self, + params: "AccountService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Account]: + """ + Returns a list of Financial Connections Account objects. + """ + return cast( + ListObject[Account], + self._requestor.request( + "get", + "/v1/financial_connections/accounts", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + account: str, + params: "AccountService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Account: + """ + Retrieves the details of an Financial Connections Account. + """ + return cast( + Account, + self._requestor.request( + "get", + "/v1/financial_connections/accounts/{account}".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def disconnect( + self, + account: str, + params: "AccountService.DisconnectParams" = {}, + options: RequestOptions = {}, + ) -> Account: + """ + Disables your access to a Financial Connections Account. You will no longer be able to access data associated with the account (e.g. balances, transactions). + """ + return cast( + Account, + self._requestor.request( + "post", + "/v1/financial_connections/accounts/{account}/disconnect".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def refresh( + self, + account: str, + params: "AccountService.RefreshParams", + options: RequestOptions = {}, + ) -> Account: + """ + Refreshes the data associated with a Financial Connections Account. + """ + return cast( + Account, + self._requestor.request( + "post", + "/v1/financial_connections/accounts/{account}/refresh".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def subscribe( + self, + account: str, + params: "AccountService.SubscribeParams", + options: RequestOptions = {}, + ) -> Account: + """ + Subscribes to periodic refreshes of data associated with a Financial Connections Account. + """ + return cast( + Account, + self._requestor.request( + "post", + "/v1/financial_connections/accounts/{account}/subscribe".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def unsubscribe( + self, + account: str, + params: "AccountService.UnsubscribeParams", + options: RequestOptions = {}, + ) -> Account: + """ + Unsubscribes from periodic refreshes of data associated with a Financial Connections Account. + """ + return cast( + Account, + self._requestor.request( + "post", + "/v1/financial_connections/accounts/{account}/unsubscribe".format( + account=_util.sanitize_id(account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/financial_connections/_session.py b/stripe/financial_connections/_session.py index 6b9cc8c7c..95945b396 100644 --- a/stripe/financial_connections/_session.py +++ b/stripe/financial_connections/_session.py @@ -150,16 +150,7 @@ class RetrieveParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Session.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Session": + def create(cls, **params: Unpack["Session.CreateParams"]) -> "Session": """ To launch the Financial Connections authorization flow, create a Session. The session's client_secret can be used to launch the flow using Stripe.js. """ @@ -168,10 +159,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) diff --git a/stripe/financial_connections/_session_service.py b/stripe/financial_connections/_session_service.py new file mode 100644 index 000000000..2ef4b32b5 --- /dev/null +++ b/stripe/financial_connections/_session_service.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.financial_connections._session import Session +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class SessionService(StripeService): + class CreateParams(TypedDict): + account_holder: "SessionService.CreateParamsAccountHolder" + """ + The account holder to link accounts for. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + filters: NotRequired["SessionService.CreateParamsFilters"] + """ + Filters to restrict the kinds of accounts to collect. + """ + permissions: List[ + Literal["balances", "ownership", "payment_method", "transactions"] + ] + """ + List of data features that you would like to request access to. + + Possible values are `balances`, `transactions`, `ownership`, and `payment_method`. + """ + prefetch: NotRequired[ + "List[Literal['balances', 'ownership', 'transactions']]" + ] + """ + List of data features that you would like to retrieve upon account creation. + """ + return_url: NotRequired["str"] + """ + For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. + """ + + class CreateParamsAccountHolder(TypedDict): + account: NotRequired["str"] + """ + The ID of the Stripe account whose accounts will be retrieved. Should only be present if `type` is `account`. + """ + customer: NotRequired["str"] + """ + The ID of the Stripe customer whose accounts will be retrieved. Should only be present if `type` is `customer`. + """ + type: Literal["account", "customer"] + """ + Type of account holder to collect accounts for. + """ + + class CreateParamsFilters(TypedDict): + countries: List[str] + """ + List of countries from which to collect accounts. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def retrieve( + self, + session: str, + params: "SessionService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Session: + """ + Retrieves the details of a Financial Connections Session + """ + return cast( + Session, + self._requestor.request( + "get", + "/v1/financial_connections/sessions/{session}".format( + session=_util.sanitize_id(session), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "SessionService.CreateParams", + options: RequestOptions = {}, + ) -> Session: + """ + To launch the Financial Connections authorization flow, create a Session. The session's client_secret can be used to launch the flow using Stripe.js. + """ + return cast( + Session, + self._requestor.request( + "post", + "/v1/financial_connections/sessions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/financial_connections/_transaction.py b/stripe/financial_connections/_transaction.py index fe8da92a1..f08dec81e 100644 --- a/stripe/financial_connections/_transaction.py +++ b/stripe/financial_connections/_transaction.py @@ -137,13 +137,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transaction.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Transaction.ListParams"] ) -> ListObject["Transaction"]: """ Returns a list of Financial Connections Transaction objects. @@ -151,9 +145,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/financial_connections/_transaction_service.py b/stripe/financial_connections/_transaction_service.py new file mode 100644 index 000000000..0e55f28b7 --- /dev/null +++ b/stripe/financial_connections/_transaction_service.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.financial_connections._transaction import Transaction +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class TransactionService(StripeService): + class ListParams(TypedDict): + account: str + """ + The ID of the Stripe account whose transactions will be retrieved. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + transacted_at: NotRequired[ + "TransactionService.ListParamsTransactedAt|int" + ] + """ + A filter on the list based on the object `transacted_at` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with the following options: + """ + transaction_refresh: NotRequired[ + "TransactionService.ListParamsTransactionRefresh" + ] + """ + A filter on the list based on the object `transaction_refresh` field. The value can be a dictionary with the following options: + """ + + class ListParamsTransactedAt(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ListParamsTransactionRefresh(TypedDict): + after: str + """ + Return results where the transactions were created or updated by a refresh that took place after this refresh (non-inclusive). + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "TransactionService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[Transaction]: + """ + Returns a list of Financial Connections Transaction objects. + """ + return cast( + ListObject[Transaction], + self._requestor.request( + "get", + "/v1/financial_connections/transactions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + transaction: str, + params: "TransactionService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Transaction: + """ + Retrieves the details of a Financial Connections Transaction + """ + return cast( + Transaction, + self._requestor.request( + "get", + "/v1/financial_connections/transactions/{transaction}".format( + transaction=_util.sanitize_id(transaction), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/identity/__init__.py b/stripe/identity/__init__.py index 2ec85ca9f..208685588 100644 --- a/stripe/identity/__init__.py +++ b/stripe/identity/__init__.py @@ -3,6 +3,12 @@ from stripe.identity._verification_report import ( VerificationReport as VerificationReport, ) +from stripe.identity._verification_report_service import ( + VerificationReportService as VerificationReportService, +) from stripe.identity._verification_session import ( VerificationSession as VerificationSession, ) +from stripe.identity._verification_session_service import ( + VerificationSessionService as VerificationSessionService, +) diff --git a/stripe/identity/_verification_report.py b/stripe/identity/_verification_report.py index d83fb64b5..c1dec98ff 100644 --- a/stripe/identity/_verification_report.py +++ b/stripe/identity/_verification_report.py @@ -384,13 +384,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "VerificationReport.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["VerificationReport.ListParams"] ) -> ListObject["VerificationReport"]: """ List all verification reports. @@ -398,9 +392,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/identity/_verification_report_service.py b/stripe/identity/_verification_report_service.py new file mode 100644 index 000000000..beae3abad --- /dev/null +++ b/stripe/identity/_verification_report_service.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.identity._verification_report import VerificationReport +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class VerificationReportService(StripeService): + class ListParams(TypedDict): + created: NotRequired["VerificationReportService.ListParamsCreated|int"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + type: NotRequired["Literal['document', 'id_number']"] + """ + Only return VerificationReports of this type + """ + verification_session: NotRequired["str"] + """ + Only return VerificationReports created by this VerificationSession ID. It is allowed to provide a VerificationIntent ID. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "VerificationReportService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[VerificationReport]: + """ + List all verification reports. + """ + return cast( + ListObject[VerificationReport], + self._requestor.request( + "get", + "/v1/identity/verification_reports", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + report: str, + params: "VerificationReportService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> VerificationReport: + """ + Retrieves an existing VerificationReport + """ + return cast( + VerificationReport, + self._requestor.request( + "get", + "/v1/identity/verification_reports/{report}".format( + report=_util.sanitize_id(report), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/identity/_verification_session.py b/stripe/identity/_verification_session.py index 2736d5beb..4f3643c33 100644 --- a/stripe/identity/_verification_session.py +++ b/stripe/identity/_verification_session.py @@ -391,14 +391,7 @@ class RetrieveParams(RequestOptions): @classmethod def _cls_cancel( - cls, - session: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "VerificationSession.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, session: str, **params: Unpack["VerificationSession.CancelParams"] ) -> "VerificationSession": """ A VerificationSession object can be canceled when it is in requires_input [status](https://stripe.com/docs/identity/how-sessions-work). @@ -412,9 +405,6 @@ def _cls_cancel( "/v1/identity/verification_sessions/{session}/cancel".format( session=_util.sanitize_id(session) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -422,13 +412,7 @@ def _cls_cancel( @overload @staticmethod def cancel( - session: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "VerificationSession.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + session: str, **params: Unpack["VerificationSession.CancelParams"] ) -> "VerificationSession": """ A VerificationSession object can be canceled when it is in requires_input [status](https://stripe.com/docs/identity/how-sessions-work). @@ -439,11 +423,7 @@ def cancel( @overload def cancel( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "VerificationSession.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["VerificationSession.CancelParams"] ) -> "VerificationSession": """ A VerificationSession object can be canceled when it is in requires_input [status](https://stripe.com/docs/identity/how-sessions-work). @@ -454,11 +434,7 @@ def cancel( @class_method_variant("_cls_cancel") def cancel( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "VerificationSession.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["VerificationSession.CancelParams"] ) -> "VerificationSession": """ A VerificationSession object can be canceled when it is in requires_input [status](https://stripe.com/docs/identity/how-sessions-work). @@ -472,21 +448,13 @@ def cancel( # pyright: ignore[reportGeneralTypeIssues] "/v1/identity/verification_sessions/{session}/cancel".format( session=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "VerificationSession.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["VerificationSession.CreateParams"] ) -> "VerificationSession": """ Creates a VerificationSession object. @@ -502,23 +470,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "VerificationSession.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["VerificationSession.ListParams"] ) -> ListObject["VerificationSession"]: """ Returns a list of VerificationSessions @@ -526,9 +484,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -558,14 +513,7 @@ def modify( @classmethod def _cls_redact( - cls, - session: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "VerificationSession.RedactParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, session: str, **params: Unpack["VerificationSession.RedactParams"] ) -> "VerificationSession": """ Redact a VerificationSession to remove all collected information from Stripe. This will redact @@ -595,9 +543,6 @@ def _cls_redact( "/v1/identity/verification_sessions/{session}/redact".format( session=_util.sanitize_id(session) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -605,13 +550,7 @@ def _cls_redact( @overload @staticmethod def redact( - session: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "VerificationSession.RedactParams" - ] # pyright: ignore[reportGeneralTypeIssues] + session: str, **params: Unpack["VerificationSession.RedactParams"] ) -> "VerificationSession": """ Redact a VerificationSession to remove all collected information from Stripe. This will redact @@ -638,11 +577,7 @@ def redact( @overload def redact( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "VerificationSession.RedactParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["VerificationSession.RedactParams"] ) -> "VerificationSession": """ Redact a VerificationSession to remove all collected information from Stripe. This will redact @@ -669,11 +604,7 @@ def redact( @class_method_variant("_cls_redact") def redact( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "VerificationSession.RedactParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["VerificationSession.RedactParams"] ) -> "VerificationSession": """ Redact a VerificationSession to remove all collected information from Stripe. This will redact @@ -703,7 +634,6 @@ def redact( # pyright: ignore[reportGeneralTypeIssues] "/v1/identity/verification_sessions/{session}/redact".format( session=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/identity/_verification_session_service.py b/stripe/identity/_verification_session_service.py new file mode 100644 index 000000000..a3973adfe --- /dev/null +++ b/stripe/identity/_verification_session_service.py @@ -0,0 +1,334 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.identity._verification_session import VerificationSession +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class VerificationSessionService(StripeService): + class CancelParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + options: NotRequired["VerificationSessionService.CreateParamsOptions"] + """ + A set of options for the session's verification checks. + """ + return_url: NotRequired["str"] + """ + The URL that the user will be redirected to upon completing the verification flow. + """ + type: Literal["document", "id_number"] + """ + The type of [verification check](https://stripe.com/docs/identity/verification-checks) to be performed. + """ + + class CreateParamsOptions(TypedDict): + document: NotRequired[ + "Literal['']|VerificationSessionService.CreateParamsOptionsDocument" + ] + """ + Options that apply to the [document check](https://stripe.com/docs/identity/verification-checks?type=document). + """ + + class CreateParamsOptionsDocument(TypedDict): + allowed_types: NotRequired[ + "List[Literal['driving_license', 'id_card', 'passport']]" + ] + """ + Array of strings of allowed identity document types. If the provided identity document isn't one of the allowed types, the verification check will fail with a document_type_not_allowed error code. + """ + require_id_number: NotRequired["bool"] + """ + Collect an ID number and perform an [ID number check](https://stripe.com/docs/identity/verification-checks?type=id-number) with the document's extracted name and date of birth. + """ + require_live_capture: NotRequired["bool"] + """ + Disable image uploads, identity document images have to be captured using the device's camera. + """ + require_matching_selfie: NotRequired["bool"] + """ + Capture a face image and perform a [selfie check](https://stripe.com/docs/identity/verification-checks?type=selfie) comparing a photo ID and a picture of your user's face. [Learn more](https://stripe.com/docs/identity/selfie). + """ + + class ListParams(TypedDict): + created: NotRequired[ + "VerificationSessionService.ListParamsCreated|int" + ] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired[ + "Literal['canceled', 'processing', 'requires_input', 'verified']" + ] + """ + Only return VerificationSessions with this status. [Learn more about the lifecycle of sessions](https://stripe.com/docs/identity/how-sessions-work). + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RedactParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + options: NotRequired["VerificationSessionService.UpdateParamsOptions"] + """ + A set of options for the session's verification checks. + """ + type: NotRequired["Literal['document', 'id_number']"] + """ + The type of [verification check](https://stripe.com/docs/identity/verification-checks) to be performed. + """ + + class UpdateParamsOptions(TypedDict): + document: NotRequired[ + "Literal['']|VerificationSessionService.UpdateParamsOptionsDocument" + ] + """ + Options that apply to the [document check](https://stripe.com/docs/identity/verification-checks?type=document). + """ + + class UpdateParamsOptionsDocument(TypedDict): + allowed_types: NotRequired[ + "List[Literal['driving_license', 'id_card', 'passport']]" + ] + """ + Array of strings of allowed identity document types. If the provided identity document isn't one of the allowed types, the verification check will fail with a document_type_not_allowed error code. + """ + require_id_number: NotRequired["bool"] + """ + Collect an ID number and perform an [ID number check](https://stripe.com/docs/identity/verification-checks?type=id-number) with the document's extracted name and date of birth. + """ + require_live_capture: NotRequired["bool"] + """ + Disable image uploads, identity document images have to be captured using the device's camera. + """ + require_matching_selfie: NotRequired["bool"] + """ + Capture a face image and perform a [selfie check](https://stripe.com/docs/identity/verification-checks?type=selfie) comparing a photo ID and a picture of your user's face. [Learn more](https://stripe.com/docs/identity/selfie). + """ + + def list( + self, + params: "VerificationSessionService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[VerificationSession]: + """ + Returns a list of VerificationSessions + """ + return cast( + ListObject[VerificationSession], + self._requestor.request( + "get", + "/v1/identity/verification_sessions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "VerificationSessionService.CreateParams", + options: RequestOptions = {}, + ) -> VerificationSession: + """ + Creates a VerificationSession object. + + After the VerificationSession is created, display a verification modal using the session client_secret or send your users to the session's url. + + If your API key is in test mode, verification checks won't actually process, though everything else will occur as if in live mode. + + Related guide: [Verify your users' identity documents](https://stripe.com/docs/identity/verify-identity-documents) + """ + return cast( + VerificationSession, + self._requestor.request( + "post", + "/v1/identity/verification_sessions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + session: str, + params: "VerificationSessionService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> VerificationSession: + """ + Retrieves the details of a VerificationSession that was previously created. + + When the session status is requires_input, you can use this method to retrieve a valid + client_secret or url to allow re-submission. + """ + return cast( + VerificationSession, + self._requestor.request( + "get", + "/v1/identity/verification_sessions/{session}".format( + session=_util.sanitize_id(session), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + session: str, + params: "VerificationSessionService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> VerificationSession: + """ + Updates a VerificationSession object. + + When the session status is requires_input, you can use this method to update the + verification check and options. + """ + return cast( + VerificationSession, + self._requestor.request( + "post", + "/v1/identity/verification_sessions/{session}".format( + session=_util.sanitize_id(session), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def cancel( + self, + session: str, + params: "VerificationSessionService.CancelParams" = {}, + options: RequestOptions = {}, + ) -> VerificationSession: + """ + A VerificationSession object can be canceled when it is in requires_input [status](https://stripe.com/docs/identity/how-sessions-work). + + Once canceled, future submission attempts are disabled. This cannot be undone. [Learn more](https://stripe.com/docs/identity/verification-sessions#cancel). + """ + return cast( + VerificationSession, + self._requestor.request( + "post", + "/v1/identity/verification_sessions/{session}/cancel".format( + session=_util.sanitize_id(session), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def redact( + self, + session: str, + params: "VerificationSessionService.RedactParams" = {}, + options: RequestOptions = {}, + ) -> VerificationSession: + """ + Redact a VerificationSession to remove all collected information from Stripe. This will redact + the VerificationSession and all objects related to it, including VerificationReports, Events, + request logs, etc. + + A VerificationSession object can be redacted when it is in requires_input or verified + [status](https://stripe.com/docs/identity/how-sessions-work). Redacting a VerificationSession in requires_action + state will automatically cancel it. + + The redaction process may take up to four days. When the redaction process is in progress, the + VerificationSession's redaction.status field will be set to processing; when the process is + finished, it will change to redacted and an identity.verification_session.redacted event + will be emitted. + + Redaction is irreversible. Redacted objects are still accessible in the Stripe API, but all the + fields that contain personal data will be replaced by the string [redacted] or a similar + placeholder. The metadata field will also be erased. Redacted objects cannot be updated or + used for any purpose. + + [Learn more](https://stripe.com/docs/identity/verification-sessions#redact). + """ + return cast( + VerificationSession, + self._requestor.request( + "post", + "/v1/identity/verification_sessions/{session}/redact".format( + session=_util.sanitize_id(session), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/issuing/__init__.py b/stripe/issuing/__init__.py index 1d83cff29..9b76120a0 100644 --- a/stripe/issuing/__init__.py +++ b/stripe/issuing/__init__.py @@ -1,8 +1,20 @@ # -*- coding: utf-8 -*- # File generated from our OpenAPI spec from stripe.issuing._authorization import Authorization as Authorization +from stripe.issuing._authorization_service import ( + AuthorizationService as AuthorizationService, +) from stripe.issuing._card import Card as Card +from stripe.issuing._card_service import CardService as CardService from stripe.issuing._cardholder import Cardholder as Cardholder +from stripe.issuing._cardholder_service import ( + CardholderService as CardholderService, +) from stripe.issuing._dispute import Dispute as Dispute +from stripe.issuing._dispute_service import DisputeService as DisputeService from stripe.issuing._token import Token as Token +from stripe.issuing._token_service import TokenService as TokenService from stripe.issuing._transaction import Transaction as Transaction +from stripe.issuing._transaction_service import ( + TransactionService as TransactionService, +) diff --git a/stripe/issuing/_authorization.py b/stripe/issuing/_authorization.py index 7b3ba6b75..ecc775b73 100644 --- a/stripe/issuing/_authorization.py +++ b/stripe/issuing/_authorization.py @@ -814,12 +814,7 @@ class ReverseParams(RequestOptions): def _cls_approve( cls, authorization: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.ApproveParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Authorization.ApproveParams"] ) -> "Authorization": """ [Deprecated] Approves a pending Issuing Authorization object. This request should be made within the timeout window of the [real-time authorization](https://stripe.com/docs/issuing/controls/real-time-authorizations) flow. @@ -832,9 +827,6 @@ def _cls_approve( "/v1/issuing/authorizations/{authorization}/approve".format( authorization=_util.sanitize_id(authorization) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -842,13 +834,7 @@ def _cls_approve( @overload @staticmethod def approve( - authorization: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.ApproveParams" - ] # pyright: ignore[reportGeneralTypeIssues] + authorization: str, **params: Unpack["Authorization.ApproveParams"] ) -> "Authorization": """ [Deprecated] Approves a pending Issuing Authorization object. This request should be made within the timeout window of the [real-time authorization](https://stripe.com/docs/issuing/controls/real-time-authorizations) flow. @@ -858,11 +844,7 @@ def approve( @overload def approve( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Authorization.ApproveParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Authorization.ApproveParams"] ) -> "Authorization": """ [Deprecated] Approves a pending Issuing Authorization object. This request should be made within the timeout window of the [real-time authorization](https://stripe.com/docs/issuing/controls/real-time-authorizations) flow. @@ -872,11 +854,7 @@ def approve( @class_method_variant("_cls_approve") def approve( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Authorization.ApproveParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Authorization.ApproveParams"] ) -> "Authorization": """ [Deprecated] Approves a pending Issuing Authorization object. This request should be made within the timeout window of the [real-time authorization](https://stripe.com/docs/issuing/controls/real-time-authorizations) flow. @@ -889,7 +867,6 @@ def approve( # pyright: ignore[reportGeneralTypeIssues] "/v1/issuing/authorizations/{authorization}/approve".format( authorization=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -898,12 +875,7 @@ def approve( # pyright: ignore[reportGeneralTypeIssues] def _cls_decline( cls, authorization: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.DeclineParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Authorization.DeclineParams"] ) -> "Authorization": """ [Deprecated] Declines a pending Issuing Authorization object. This request should be made within the timeout window of the [real time authorization](https://stripe.com/docs/issuing/controls/real-time-authorizations) flow. @@ -916,9 +888,6 @@ def _cls_decline( "/v1/issuing/authorizations/{authorization}/decline".format( authorization=_util.sanitize_id(authorization) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -926,13 +895,7 @@ def _cls_decline( @overload @staticmethod def decline( - authorization: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.DeclineParams" - ] # pyright: ignore[reportGeneralTypeIssues] + authorization: str, **params: Unpack["Authorization.DeclineParams"] ) -> "Authorization": """ [Deprecated] Declines a pending Issuing Authorization object. This request should be made within the timeout window of the [real time authorization](https://stripe.com/docs/issuing/controls/real-time-authorizations) flow. @@ -942,11 +905,7 @@ def decline( @overload def decline( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Authorization.DeclineParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Authorization.DeclineParams"] ) -> "Authorization": """ [Deprecated] Declines a pending Issuing Authorization object. This request should be made within the timeout window of the [real time authorization](https://stripe.com/docs/issuing/controls/real-time-authorizations) flow. @@ -956,11 +915,7 @@ def decline( @class_method_variant("_cls_decline") def decline( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Authorization.DeclineParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Authorization.DeclineParams"] ) -> "Authorization": """ [Deprecated] Declines a pending Issuing Authorization object. This request should be made within the timeout window of the [real time authorization](https://stripe.com/docs/issuing/controls/real-time-authorizations) flow. @@ -973,20 +928,13 @@ def decline( # pyright: ignore[reportGeneralTypeIssues] "/v1/issuing/authorizations/{authorization}/decline".format( authorization=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Authorization.ListParams"] ) -> ListObject["Authorization"]: """ Returns a list of Issuing Authorization objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. @@ -994,9 +942,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -1039,12 +984,7 @@ class TestHelpers(APIResourceTestHelpers["Authorization"]): def _cls_capture( cls, authorization: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.CaptureParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Authorization.CaptureParams"] ) -> "Authorization": """ Capture a test-mode authorization. @@ -1056,9 +996,6 @@ def _cls_capture( "/v1/test_helpers/issuing/authorizations/{authorization}/capture".format( authorization=_util.sanitize_id(authorization) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1066,13 +1003,7 @@ def _cls_capture( @overload @staticmethod def capture( - authorization: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.CaptureParams" - ] # pyright: ignore[reportGeneralTypeIssues] + authorization: str, **params: Unpack["Authorization.CaptureParams"] ) -> "Authorization": """ Capture a test-mode authorization. @@ -1081,11 +1012,7 @@ def capture( @overload def capture( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Authorization.CaptureParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Authorization.CaptureParams"] ) -> "Authorization": """ Capture a test-mode authorization. @@ -1094,11 +1021,7 @@ def capture( @class_method_variant("_cls_capture") def capture( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Authorization.CaptureParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Authorization.CaptureParams"] ) -> "Authorization": """ Capture a test-mode authorization. @@ -1112,20 +1035,13 @@ def capture( # pyright: ignore[reportGeneralTypeIssues] self.resource.get("id") ) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def create( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Authorization.CreateParams"] ) -> "Authorization": """ Create a test-mode authorization. @@ -1135,9 +1051,6 @@ def create( cls._static_request( "post", "/v1/test_helpers/issuing/authorizations", - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1146,12 +1059,7 @@ def create( def _cls_expire( cls, authorization: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.ExpireParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Authorization.ExpireParams"] ) -> "Authorization": """ Expire a test-mode Authorization. @@ -1163,9 +1071,6 @@ def _cls_expire( "/v1/test_helpers/issuing/authorizations/{authorization}/expire".format( authorization=_util.sanitize_id(authorization) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1173,13 +1078,7 @@ def _cls_expire( @overload @staticmethod def expire( - authorization: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.ExpireParams" - ] # pyright: ignore[reportGeneralTypeIssues] + authorization: str, **params: Unpack["Authorization.ExpireParams"] ) -> "Authorization": """ Expire a test-mode Authorization. @@ -1188,11 +1087,7 @@ def expire( @overload def expire( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Authorization.ExpireParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Authorization.ExpireParams"] ) -> "Authorization": """ Expire a test-mode Authorization. @@ -1201,11 +1096,7 @@ def expire( @class_method_variant("_cls_expire") def expire( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Authorization.ExpireParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Authorization.ExpireParams"] ) -> "Authorization": """ Expire a test-mode Authorization. @@ -1219,7 +1110,6 @@ def expire( # pyright: ignore[reportGeneralTypeIssues] self.resource.get("id") ) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -1228,12 +1118,7 @@ def expire( # pyright: ignore[reportGeneralTypeIssues] def _cls_increment( cls, authorization: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.IncrementParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Authorization.IncrementParams"] ) -> "Authorization": """ Increment a test-mode Authorization. @@ -1245,9 +1130,6 @@ def _cls_increment( "/v1/test_helpers/issuing/authorizations/{authorization}/increment".format( authorization=_util.sanitize_id(authorization) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1256,12 +1138,7 @@ def _cls_increment( @staticmethod def increment( authorization: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.IncrementParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Authorization.IncrementParams"] ) -> "Authorization": """ Increment a test-mode Authorization. @@ -1270,11 +1147,7 @@ def increment( @overload def increment( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Authorization.IncrementParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Authorization.IncrementParams"] ) -> "Authorization": """ Increment a test-mode Authorization. @@ -1283,11 +1156,7 @@ def increment( @class_method_variant("_cls_increment") def increment( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Authorization.IncrementParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Authorization.IncrementParams"] ) -> "Authorization": """ Increment a test-mode Authorization. @@ -1301,7 +1170,6 @@ def increment( # pyright: ignore[reportGeneralTypeIssues] self.resource.get("id") ) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -1310,12 +1178,7 @@ def increment( # pyright: ignore[reportGeneralTypeIssues] def _cls_reverse( cls, authorization: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.ReverseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Authorization.ReverseParams"] ) -> "Authorization": """ Reverse a test-mode Authorization. @@ -1327,9 +1190,6 @@ def _cls_reverse( "/v1/test_helpers/issuing/authorizations/{authorization}/reverse".format( authorization=_util.sanitize_id(authorization) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1337,13 +1197,7 @@ def _cls_reverse( @overload @staticmethod def reverse( - authorization: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Authorization.ReverseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + authorization: str, **params: Unpack["Authorization.ReverseParams"] ) -> "Authorization": """ Reverse a test-mode Authorization. @@ -1352,11 +1206,7 @@ def reverse( @overload def reverse( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Authorization.ReverseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Authorization.ReverseParams"] ) -> "Authorization": """ Reverse a test-mode Authorization. @@ -1365,11 +1215,7 @@ def reverse( @class_method_variant("_cls_reverse") def reverse( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Authorization.ReverseParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Authorization.ReverseParams"] ) -> "Authorization": """ Reverse a test-mode Authorization. @@ -1383,7 +1229,6 @@ def reverse( # pyright: ignore[reportGeneralTypeIssues] self.resource.get("id") ) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/issuing/_authorization_service.py b/stripe/issuing/_authorization_service.py new file mode 100644 index 000000000..e54268cb0 --- /dev/null +++ b/stripe/issuing/_authorization_service.py @@ -0,0 +1,217 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.issuing._authorization import Authorization +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class AuthorizationService(StripeService): + class ApproveParams(TypedDict): + amount: NotRequired["int"] + """ + If the authorization's `pending_request.is_amount_controllable` property is `true`, you may provide this value to control how much to hold for the authorization. Must be positive (use [`decline`](https://stripe.com/docs/api/issuing/authorizations/decline) to decline an authorization request). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class DeclineParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class ListParams(TypedDict): + card: NotRequired["str"] + """ + Only return authorizations that belong to the given card. + """ + cardholder: NotRequired["str"] + """ + Only return authorizations that belong to the given cardholder. + """ + created: NotRequired["AuthorizationService.ListParamsCreated|int"] + """ + Only return authorizations that were created during the given date interval. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired["Literal['closed', 'pending', 'reversed']"] + """ + Only return authorizations with the given status. One of `pending`, `closed`, or `reversed`. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + def list( + self, + params: "AuthorizationService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Authorization]: + """ + Returns a list of Issuing Authorization objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. + """ + return cast( + ListObject[Authorization], + self._requestor.request( + "get", + "/v1/issuing/authorizations", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + authorization: str, + params: "AuthorizationService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Authorization: + """ + Retrieves an Issuing Authorization object. + """ + return cast( + Authorization, + self._requestor.request( + "get", + "/v1/issuing/authorizations/{authorization}".format( + authorization=_util.sanitize_id(authorization), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + authorization: str, + params: "AuthorizationService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Authorization: + """ + Updates the specified Issuing Authorization object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + """ + return cast( + Authorization, + self._requestor.request( + "post", + "/v1/issuing/authorizations/{authorization}".format( + authorization=_util.sanitize_id(authorization), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def approve( + self, + authorization: str, + params: "AuthorizationService.ApproveParams" = {}, + options: RequestOptions = {}, + ) -> Authorization: + """ + [Deprecated] Approves a pending Issuing Authorization object. This request should be made within the timeout window of the [real-time authorization](https://stripe.com/docs/issuing/controls/real-time-authorizations) flow. + This method is deprecated. Instead, [respond directly to the webhook request to approve an authorization](https://stripe.com/docs/issuing/controls/real-time-authorizations#authorization-handling). + """ + return cast( + Authorization, + self._requestor.request( + "post", + "/v1/issuing/authorizations/{authorization}/approve".format( + authorization=_util.sanitize_id(authorization), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def decline( + self, + authorization: str, + params: "AuthorizationService.DeclineParams" = {}, + options: RequestOptions = {}, + ) -> Authorization: + """ + [Deprecated] Declines a pending Issuing Authorization object. This request should be made within the timeout window of the [real time authorization](https://stripe.com/docs/issuing/controls/real-time-authorizations) flow. + This method is deprecated. Instead, [respond directly to the webhook request to decline an authorization](https://stripe.com/docs/issuing/controls/real-time-authorizations#authorization-handling). + """ + return cast( + Authorization, + self._requestor.request( + "post", + "/v1/issuing/authorizations/{authorization}/decline".format( + authorization=_util.sanitize_id(authorization), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/issuing/_card.py b/stripe/issuing/_card.py index 7c7533506..8bea47699 100644 --- a/stripe/issuing/_card.py +++ b/stripe/issuing/_card.py @@ -1530,16 +1530,7 @@ class ShipCardParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Card.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Card": + def create(cls, **params: Unpack["Card.CreateParams"]) -> "Card": """ Creates an Issuing Card object. """ @@ -1548,33 +1539,18 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod - def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Card.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> ListObject["Card"]: + def list(cls, **params: Unpack["Card.ListParams"]) -> ListObject["Card"]: """ Returns a list of Issuing Card objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. """ result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -1613,14 +1589,7 @@ class TestHelpers(APIResourceTestHelpers["Card"]): @classmethod def _cls_deliver_card( - cls, - card: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Card.DeliverCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, card: str, **params: Unpack["Card.DeliverCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to delivered. @@ -1632,9 +1601,6 @@ def _cls_deliver_card( "/v1/test_helpers/issuing/cards/{card}/shipping/deliver".format( card=_util.sanitize_id(card) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1642,13 +1608,7 @@ def _cls_deliver_card( @overload @staticmethod def deliver_card( - card: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Card.DeliverCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + card: str, **params: Unpack["Card.DeliverCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to delivered. @@ -1657,11 +1617,7 @@ def deliver_card( @overload def deliver_card( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Card.DeliverCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Card.DeliverCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to delivered. @@ -1670,11 +1626,7 @@ def deliver_card( @class_method_variant("_cls_deliver_card") def deliver_card( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Card.DeliverCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Card.DeliverCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to delivered. @@ -1686,21 +1638,13 @@ def deliver_card( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/issuing/cards/{card}/shipping/deliver".format( card=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_fail_card( - cls, - card: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Card.FailCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, card: str, **params: Unpack["Card.FailCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to failure. @@ -1712,9 +1656,6 @@ def _cls_fail_card( "/v1/test_helpers/issuing/cards/{card}/shipping/fail".format( card=_util.sanitize_id(card) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1722,13 +1663,7 @@ def _cls_fail_card( @overload @staticmethod def fail_card( - card: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Card.FailCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + card: str, **params: Unpack["Card.FailCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to failure. @@ -1736,13 +1671,7 @@ def fail_card( ... @overload - def fail_card( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Card.FailCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Card": + def fail_card(self, **params: Unpack["Card.FailCardParams"]) -> "Card": """ Updates the shipping status of the specified Issuing Card object to failure. """ @@ -1750,11 +1679,7 @@ def fail_card( @class_method_variant("_cls_fail_card") def fail_card( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Card.FailCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Card.FailCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to failure. @@ -1766,21 +1691,13 @@ def fail_card( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/issuing/cards/{card}/shipping/fail".format( card=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_return_card( - cls, - card: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Card.ReturnCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, card: str, **params: Unpack["Card.ReturnCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to returned. @@ -1792,9 +1709,6 @@ def _cls_return_card( "/v1/test_helpers/issuing/cards/{card}/shipping/return".format( card=_util.sanitize_id(card) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1802,13 +1716,7 @@ def _cls_return_card( @overload @staticmethod def return_card( - card: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Card.ReturnCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + card: str, **params: Unpack["Card.ReturnCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to returned. @@ -1817,11 +1725,7 @@ def return_card( @overload def return_card( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Card.ReturnCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Card.ReturnCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to returned. @@ -1830,11 +1734,7 @@ def return_card( @class_method_variant("_cls_return_card") def return_card( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Card.ReturnCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Card.ReturnCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to returned. @@ -1846,21 +1746,13 @@ def return_card( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/issuing/cards/{card}/shipping/return".format( card=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_ship_card( - cls, - card: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Card.ShipCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, card: str, **params: Unpack["Card.ShipCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to shipped. @@ -1872,9 +1764,6 @@ def _cls_ship_card( "/v1/test_helpers/issuing/cards/{card}/shipping/ship".format( card=_util.sanitize_id(card) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1882,13 +1771,7 @@ def _cls_ship_card( @overload @staticmethod def ship_card( - card: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Card.ShipCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + card: str, **params: Unpack["Card.ShipCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to shipped. @@ -1896,13 +1779,7 @@ def ship_card( ... @overload - def ship_card( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Card.ShipCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Card": + def ship_card(self, **params: Unpack["Card.ShipCardParams"]) -> "Card": """ Updates the shipping status of the specified Issuing Card object to shipped. """ @@ -1910,11 +1787,7 @@ def ship_card( @class_method_variant("_cls_ship_card") def ship_card( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Card.ShipCardParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Card.ShipCardParams"] ) -> "Card": """ Updates the shipping status of the specified Issuing Card object to shipped. @@ -1926,7 +1799,6 @@ def ship_card( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/issuing/cards/{card}/shipping/ship".format( card=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/issuing/_card_service.py b/stripe/issuing/_card_service.py new file mode 100644 index 000000000..0fea78f60 --- /dev/null +++ b/stripe/issuing/_card_service.py @@ -0,0 +1,404 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.issuing._card import Card +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CardService(StripeService): + class CreateParams(TypedDict): + cardholder: NotRequired["str"] + """ + The [Cardholder](https://stripe.com/docs/api#issuing_cardholder_object) object with which the card will be associated. + """ + currency: str + """ + The currency for the card. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: NotRequired["str"] + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + pin: NotRequired["CardService.CreateParamsPin"] + """ + The desired PIN for this card. + """ + replacement_for: NotRequired["str"] + """ + The card this is meant to be a replacement for (if any). + """ + replacement_reason: NotRequired[ + "Literal['damaged', 'expired', 'lost', 'stolen']" + ] + """ + If `replacement_for` is specified, this should indicate why that card is being replaced. + """ + shipping: NotRequired["CardService.CreateParamsShipping"] + """ + The address where the card will be shipped. + """ + spending_controls: NotRequired[ + "CardService.CreateParamsSpendingControls" + ] + """ + Rules that control spending for this card. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. + """ + status: NotRequired["Literal['active', 'inactive']"] + """ + Whether authorizations can be approved on this card. May be blocked from activating cards depending on past-due Cardholder requirements. Defaults to `inactive`. + """ + type: Literal["physical", "virtual"] + """ + The type of card to issue. Possible values are `physical` or `virtual`. + """ + + class CreateParamsPin(TypedDict): + encrypted_number: NotRequired["str"] + """ + The card's desired new PIN, encrypted under Stripe's public key. + """ + + class CreateParamsShipping(TypedDict): + address: "CardService.CreateParamsShippingAddress" + """ + The address that the card is shipped to. + """ + customs: NotRequired["CardService.CreateParamsShippingCustoms"] + """ + Customs information for the shipment. + """ + name: str + """ + The name printed on the shipping label when shipping the card. + """ + phone_number: NotRequired["str"] + """ + Phone number of the recipient of the shipment. + """ + require_signature: NotRequired["bool"] + """ + Whether a signature is required for card delivery. + """ + service: NotRequired["Literal['express', 'priority', 'standard']"] + """ + Shipment service. + """ + type: NotRequired["Literal['bulk', 'individual']"] + """ + Packaging options. + """ + + class CreateParamsShippingAddress(TypedDict): + city: str + """ + City, district, suburb, town, or village. + """ + country: str + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: str + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: str + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsShippingCustoms(TypedDict): + eori_number: NotRequired["str"] + """ + The Economic Operators Registration and Identification (EORI) number to use for Customs. Required for bulk shipments to Europe. + """ + + class CreateParamsSpendingControls(TypedDict): + allowed_categories: NotRequired[ + "List[Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']]" + ] + """ + Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`. + """ + blocked_categories: NotRequired[ + "List[Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']]" + ] + """ + Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`. + """ + spending_limits: NotRequired[ + "List[CardService.CreateParamsSpendingControlsSpendingLimit]" + ] + """ + Limit spending with amount-based rules that apply across any cards this card replaced (i.e., its `replacement_for` card and _that_ card's `replacement_for` card, up the chain). + """ + + class CreateParamsSpendingControlsSpendingLimit(TypedDict): + amount: int + """ + Maximum amount allowed to spend per interval. + """ + categories: NotRequired[ + "List[Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']]" + ] + """ + Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories. + """ + interval: Literal[ + "all_time", + "daily", + "monthly", + "per_authorization", + "weekly", + "yearly", + ] + """ + Interval (or event) to which the amount applies. + """ + + class ListParams(TypedDict): + cardholder: NotRequired["str"] + """ + Only return cards belonging to the Cardholder with the provided ID. + """ + created: NotRequired["CardService.ListParamsCreated|int"] + """ + Only return cards that were issued during the given date interval. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + exp_month: NotRequired["int"] + """ + Only return cards that have the given expiration month. + """ + exp_year: NotRequired["int"] + """ + Only return cards that have the given expiration year. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + last4: NotRequired["str"] + """ + Only return cards that have the given last four digits. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired["Literal['active', 'canceled', 'inactive']"] + """ + Only return cards that have the given status. One of `active`, `inactive`, or `canceled`. + """ + type: NotRequired["Literal['physical', 'virtual']"] + """ + Only return cards that have the given type. One of `virtual` or `physical`. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + cancellation_reason: NotRequired["Literal['lost', 'stolen']"] + """ + Reason why the `status` of this card is `canceled`. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + pin: NotRequired["CardService.UpdateParamsPin"] + """ + The desired new PIN for this card. + """ + spending_controls: NotRequired[ + "CardService.UpdateParamsSpendingControls" + ] + """ + Rules that control spending for this card. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. + """ + status: NotRequired["Literal['active', 'canceled', 'inactive']"] + """ + Dictates whether authorizations can be approved on this card. May be blocked from activating cards depending on past-due Cardholder requirements. Defaults to `inactive`. If this card is being canceled because it was lost or stolen, this information should be provided as `cancellation_reason`. + """ + + class UpdateParamsPin(TypedDict): + encrypted_number: NotRequired["str"] + """ + The card's desired new PIN, encrypted under Stripe's public key. + """ + + class UpdateParamsSpendingControls(TypedDict): + allowed_categories: NotRequired[ + "List[Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']]" + ] + """ + Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`. + """ + blocked_categories: NotRequired[ + "List[Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']]" + ] + """ + Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`. + """ + spending_limits: NotRequired[ + "List[CardService.UpdateParamsSpendingControlsSpendingLimit]" + ] + """ + Limit spending with amount-based rules that apply across any cards this card replaced (i.e., its `replacement_for` card and _that_ card's `replacement_for` card, up the chain). + """ + + class UpdateParamsSpendingControlsSpendingLimit(TypedDict): + amount: int + """ + Maximum amount allowed to spend per interval. + """ + categories: NotRequired[ + "List[Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']]" + ] + """ + Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories. + """ + interval: Literal[ + "all_time", + "daily", + "monthly", + "per_authorization", + "weekly", + "yearly", + ] + """ + Interval (or event) to which the amount applies. + """ + + def list( + self, + params: "CardService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Card]: + """ + Returns a list of Issuing Card objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. + """ + return cast( + ListObject[Card], + self._requestor.request( + "get", + "/v1/issuing/cards", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, params: "CardService.CreateParams", options: RequestOptions = {} + ) -> Card: + """ + Creates an Issuing Card object. + """ + return cast( + Card, + self._requestor.request( + "post", + "/v1/issuing/cards", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + card: str, + params: "CardService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Card: + """ + Retrieves an Issuing Card object. + """ + return cast( + Card, + self._requestor.request( + "get", + "/v1/issuing/cards/{card}".format( + card=_util.sanitize_id(card) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + card: str, + params: "CardService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Card: + """ + Updates the specified Issuing Card object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + """ + return cast( + Card, + self._requestor.request( + "post", + "/v1/issuing/cards/{card}".format( + card=_util.sanitize_id(card) + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/issuing/_cardholder.py b/stripe/issuing/_cardholder.py index 33a4b4f83..31050af9e 100644 --- a/stripe/issuing/_cardholder.py +++ b/stripe/issuing/_cardholder.py @@ -1676,14 +1676,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Cardholder.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Cardholder.CreateParams"] ) -> "Cardholder": """ Creates a new Issuing Cardholder object that can be issued cards. @@ -1693,23 +1686,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Cardholder.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Cardholder.ListParams"] ) -> ListObject["Cardholder"]: """ Returns a list of Issuing Cardholder objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. @@ -1717,9 +1700,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/issuing/_cardholder_service.py b/stripe/issuing/_cardholder_service.py new file mode 100644 index 000000000..15bfc467c --- /dev/null +++ b/stripe/issuing/_cardholder_service.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.issuing._cardholder import Cardholder +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CardholderService(StripeService): + class CreateParams(TypedDict): + billing: "CardholderService.CreateParamsBilling" + """ + The cardholder's billing address. + """ + company: NotRequired["CardholderService.CreateParamsCompany"] + """ + Additional information about a `company` cardholder. + """ + email: NotRequired["str"] + """ + The cardholder's email address. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + individual: NotRequired["CardholderService.CreateParamsIndividual"] + """ + Additional information about an `individual` cardholder. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: str + """ + The cardholder's name. This will be printed on cards issued to them. The maximum length of this field is 24 characters. This field cannot contain any special characters or numbers. + """ + phone_number: NotRequired["str"] + """ + The cardholder's phone number. This will be transformed to [E.164](https://en.wikipedia.org/wiki/E.164) if it is not provided in that format already. This is required for all cardholders who will be creating EU cards. See the [3D Secure documentation](https://stripe.com/docs/issuing/3d-secure#when-is-3d-secure-applied) for more details. + """ + preferred_locales: NotRequired[ + "List[Literal['de', 'en', 'es', 'fr', 'it']]" + ] + """ + The cardholder's preferred locales (languages), ordered by preference. Locales can be `de`, `en`, `es`, `fr`, or `it`. + This changes the language of the [3D Secure flow](https://stripe.com/docs/issuing/3d-secure) and one-time password messages sent to the cardholder. + """ + spending_controls: NotRequired[ + "CardholderService.CreateParamsSpendingControls" + ] + """ + Rules that control spending across this cardholder's cards. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. + """ + status: NotRequired["Literal['active', 'inactive']"] + """ + Specifies whether to permit authorizations on this cardholder's cards. Defaults to `active`. + """ + type: NotRequired["Literal['company', 'individual']"] + """ + One of `individual` or `company`. See [Choose a cardholder type](https://stripe.com/docs/issuing/other/choose-cardholder) for more details. + """ + + class CreateParamsBilling(TypedDict): + address: "CardholderService.CreateParamsBillingAddress" + """ + The cardholder's billing address. + """ + + class CreateParamsBillingAddress(TypedDict): + city: str + """ + City, district, suburb, town, or village. + """ + country: str + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: str + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: str + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsCompany(TypedDict): + tax_id: NotRequired["str"] + """ + The entity's business ID number. + """ + + class CreateParamsIndividual(TypedDict): + card_issuing: NotRequired[ + "CardholderService.CreateParamsIndividualCardIssuing" + ] + """ + Information related to the card_issuing program for this cardholder. + """ + dob: NotRequired["CardholderService.CreateParamsIndividualDob"] + """ + The date of birth of this cardholder. Cardholders must be older than 13 years old. + """ + first_name: NotRequired["str"] + """ + The first name of this cardholder. Required before activating Cards. This field cannot contain any numbers, special characters (except periods, commas, hyphens, spaces and apostrophes) or non-latin letters. + """ + last_name: NotRequired["str"] + """ + The last name of this cardholder. Required before activating Cards. This field cannot contain any numbers, special characters (except periods, commas, hyphens, spaces and apostrophes) or non-latin letters. + """ + verification: NotRequired[ + "CardholderService.CreateParamsIndividualVerification" + ] + """ + Government-issued ID document for this cardholder. + """ + + class CreateParamsIndividualCardIssuing(TypedDict): + user_terms_acceptance: NotRequired[ + "CardholderService.CreateParamsIndividualCardIssuingUserTermsAcceptance" + ] + """ + Information about cardholder acceptance of Celtic [Authorized User Terms](https://stripe.com/docs/issuing/cards#accept-authorized-user-terms). Required for cards backed by a Celtic program. + """ + + class CreateParamsIndividualCardIssuingUserTermsAcceptance(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the cardholder accepted the Authorized User Terms. Required for Celtic Spend Card users. + """ + ip: NotRequired["str"] + """ + The IP address from which the cardholder accepted the Authorized User Terms. Required for Celtic Spend Card users. + """ + user_agent: NotRequired["Literal['']|str"] + """ + The user agent of the browser from which the cardholder accepted the Authorized User Terms. + """ + + class CreateParamsIndividualDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class CreateParamsIndividualVerification(TypedDict): + document: NotRequired[ + "CardholderService.CreateParamsIndividualVerificationDocument" + ] + """ + An identifying document, either a passport or local ID card. + """ + + class CreateParamsIndividualVerificationDocument(TypedDict): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + """ + + class CreateParamsSpendingControls(TypedDict): + allowed_categories: NotRequired[ + "List[Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']]" + ] + """ + Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`. + """ + blocked_categories: NotRequired[ + "List[Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']]" + ] + """ + Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`. + """ + spending_limits: NotRequired[ + "List[CardholderService.CreateParamsSpendingControlsSpendingLimit]" + ] + """ + Limit spending with amount-based rules that apply across this cardholder's cards. + """ + spending_limits_currency: NotRequired["str"] + """ + Currency of amounts within `spending_limits`. Defaults to your merchant country's currency. + """ + + class CreateParamsSpendingControlsSpendingLimit(TypedDict): + amount: int + """ + Maximum amount allowed to spend per interval. + """ + categories: NotRequired[ + "List[Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']]" + ] + """ + Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories. + """ + interval: Literal[ + "all_time", + "daily", + "monthly", + "per_authorization", + "weekly", + "yearly", + ] + """ + Interval (or event) to which the amount applies. + """ + + class ListParams(TypedDict): + created: NotRequired["CardholderService.ListParamsCreated|int"] + """ + Only return cardholders that were created during the given date interval. + """ + email: NotRequired["str"] + """ + Only return cardholders that have the given email address. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + phone_number: NotRequired["str"] + """ + Only return cardholders that have the given phone number. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired["Literal['active', 'blocked', 'inactive']"] + """ + Only return cardholders that have the given status. One of `active`, `inactive`, or `blocked`. + """ + type: NotRequired["Literal['company', 'individual']"] + """ + Only return cardholders that have the given type. One of `individual` or `company`. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + billing: NotRequired["CardholderService.UpdateParamsBilling"] + """ + The cardholder's billing address. + """ + company: NotRequired["CardholderService.UpdateParamsCompany"] + """ + Additional information about a `company` cardholder. + """ + email: NotRequired["str"] + """ + The cardholder's email address. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + individual: NotRequired["CardholderService.UpdateParamsIndividual"] + """ + Additional information about an `individual` cardholder. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + phone_number: NotRequired["str"] + """ + The cardholder's phone number. This is required for all cardholders who will be creating EU cards. See the [3D Secure documentation](https://stripe.com/docs/issuing/3d-secure) for more details. + """ + preferred_locales: NotRequired[ + "List[Literal['de', 'en', 'es', 'fr', 'it']]" + ] + """ + The cardholder's preferred locales (languages), ordered by preference. Locales can be `de`, `en`, `es`, `fr`, or `it`. + This changes the language of the [3D Secure flow](https://stripe.com/docs/issuing/3d-secure) and one-time password messages sent to the cardholder. + """ + spending_controls: NotRequired[ + "CardholderService.UpdateParamsSpendingControls" + ] + """ + Rules that control spending across this cardholder's cards. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details. + """ + status: NotRequired["Literal['active', 'inactive']"] + """ + Specifies whether to permit authorizations on this cardholder's cards. + """ + + class UpdateParamsBilling(TypedDict): + address: "CardholderService.UpdateParamsBillingAddress" + """ + The cardholder's billing address. + """ + + class UpdateParamsBillingAddress(TypedDict): + city: str + """ + City, district, suburb, town, or village. + """ + country: str + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: str + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: str + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class UpdateParamsCompany(TypedDict): + tax_id: NotRequired["str"] + """ + The entity's business ID number. + """ + + class UpdateParamsIndividual(TypedDict): + card_issuing: NotRequired[ + "CardholderService.UpdateParamsIndividualCardIssuing" + ] + """ + Information related to the card_issuing program for this cardholder. + """ + dob: NotRequired["CardholderService.UpdateParamsIndividualDob"] + """ + The date of birth of this cardholder. Cardholders must be older than 13 years old. + """ + first_name: NotRequired["str"] + """ + The first name of this cardholder. Required before activating Cards. This field cannot contain any numbers, special characters (except periods, commas, hyphens, spaces and apostrophes) or non-latin letters. + """ + last_name: NotRequired["str"] + """ + The last name of this cardholder. Required before activating Cards. This field cannot contain any numbers, special characters (except periods, commas, hyphens, spaces and apostrophes) or non-latin letters. + """ + verification: NotRequired[ + "CardholderService.UpdateParamsIndividualVerification" + ] + """ + Government-issued ID document for this cardholder. + """ + + class UpdateParamsIndividualCardIssuing(TypedDict): + user_terms_acceptance: NotRequired[ + "CardholderService.UpdateParamsIndividualCardIssuingUserTermsAcceptance" + ] + """ + Information about cardholder acceptance of Celtic [Authorized User Terms](https://stripe.com/docs/issuing/cards#accept-authorized-user-terms). Required for cards backed by a Celtic program. + """ + + class UpdateParamsIndividualCardIssuingUserTermsAcceptance(TypedDict): + date: NotRequired["int"] + """ + The Unix timestamp marking when the cardholder accepted the Authorized User Terms. Required for Celtic Spend Card users. + """ + ip: NotRequired["str"] + """ + The IP address from which the cardholder accepted the Authorized User Terms. Required for Celtic Spend Card users. + """ + user_agent: NotRequired["Literal['']|str"] + """ + The user agent of the browser from which the cardholder accepted the Authorized User Terms. + """ + + class UpdateParamsIndividualDob(TypedDict): + day: int + """ + The day of birth, between 1 and 31. + """ + month: int + """ + The month of birth, between 1 and 12. + """ + year: int + """ + The four-digit year of birth. + """ + + class UpdateParamsIndividualVerification(TypedDict): + document: NotRequired[ + "CardholderService.UpdateParamsIndividualVerificationDocument" + ] + """ + An identifying document, either a passport or local ID card. + """ + + class UpdateParamsIndividualVerificationDocument(TypedDict): + back: NotRequired["str"] + """ + The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + """ + front: NotRequired["str"] + """ + The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + """ + + class UpdateParamsSpendingControls(TypedDict): + allowed_categories: NotRequired[ + "List[Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']]" + ] + """ + Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`. + """ + blocked_categories: NotRequired[ + "List[Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']]" + ] + """ + Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`. + """ + spending_limits: NotRequired[ + "List[CardholderService.UpdateParamsSpendingControlsSpendingLimit]" + ] + """ + Limit spending with amount-based rules that apply across this cardholder's cards. + """ + spending_limits_currency: NotRequired["str"] + """ + Currency of amounts within `spending_limits`. Defaults to your merchant country's currency. + """ + + class UpdateParamsSpendingControlsSpendingLimit(TypedDict): + amount: int + """ + Maximum amount allowed to spend per interval. + """ + categories: NotRequired[ + "List[Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']]" + ] + """ + Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories. + """ + interval: Literal[ + "all_time", + "daily", + "monthly", + "per_authorization", + "weekly", + "yearly", + ] + """ + Interval (or event) to which the amount applies. + """ + + def list( + self, + params: "CardholderService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Cardholder]: + """ + Returns a list of Issuing Cardholder objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. + """ + return cast( + ListObject[Cardholder], + self._requestor.request( + "get", + "/v1/issuing/cardholders", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "CardholderService.CreateParams", + options: RequestOptions = {}, + ) -> Cardholder: + """ + Creates a new Issuing Cardholder object that can be issued cards. + """ + return cast( + Cardholder, + self._requestor.request( + "post", + "/v1/issuing/cardholders", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + cardholder: str, + params: "CardholderService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Cardholder: + """ + Retrieves an Issuing Cardholder object. + """ + return cast( + Cardholder, + self._requestor.request( + "get", + "/v1/issuing/cardholders/{cardholder}".format( + cardholder=_util.sanitize_id(cardholder), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + cardholder: str, + params: "CardholderService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Cardholder: + """ + Updates the specified Issuing Cardholder object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + """ + return cast( + Cardholder, + self._requestor.request( + "post", + "/v1/issuing/cardholders/{cardholder}".format( + cardholder=_util.sanitize_id(cardholder), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/issuing/_dispute.py b/stripe/issuing/_dispute.py index 889acc3d0..7f322d5c2 100644 --- a/stripe/issuing/_dispute.py +++ b/stripe/issuing/_dispute.py @@ -855,16 +855,7 @@ class SubmitParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Dispute.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Dispute": + def create(cls, **params: Unpack["Dispute.CreateParams"]) -> "Dispute": """ Creates an Issuing Dispute object. Individual pieces of evidence within the evidence object are optional at this point. Stripe only validates that required evidence is present during submission. Refer to [Dispute reasons and evidence](https://stripe.com/docs/issuing/purchases/disputes#dispute-reasons-and-evidence) for more details about evidence requirements. """ @@ -873,23 +864,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Dispute.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Dispute.ListParams"] ) -> ListObject["Dispute"]: """ Returns a list of Issuing Dispute objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. @@ -897,9 +878,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -937,14 +915,7 @@ def retrieve( @classmethod def _cls_submit( - cls, - dispute: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Dispute.SubmitParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, dispute: str, **params: Unpack["Dispute.SubmitParams"] ) -> "Dispute": """ Submits an Issuing Dispute to the card network. Stripe validates that all evidence fields required for the dispute's reason are present. For more details, see [Dispute reasons and evidence](https://stripe.com/docs/issuing/purchases/disputes#dispute-reasons-and-evidence). @@ -956,9 +927,6 @@ def _cls_submit( "/v1/issuing/disputes/{dispute}/submit".format( dispute=_util.sanitize_id(dispute) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -966,13 +934,7 @@ def _cls_submit( @overload @staticmethod def submit( - dispute: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Dispute.SubmitParams" - ] # pyright: ignore[reportGeneralTypeIssues] + dispute: str, **params: Unpack["Dispute.SubmitParams"] ) -> "Dispute": """ Submits an Issuing Dispute to the card network. Stripe validates that all evidence fields required for the dispute's reason are present. For more details, see [Dispute reasons and evidence](https://stripe.com/docs/issuing/purchases/disputes#dispute-reasons-and-evidence). @@ -980,13 +942,7 @@ def submit( ... @overload - def submit( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Dispute.SubmitParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Dispute": + def submit(self, **params: Unpack["Dispute.SubmitParams"]) -> "Dispute": """ Submits an Issuing Dispute to the card network. Stripe validates that all evidence fields required for the dispute's reason are present. For more details, see [Dispute reasons and evidence](https://stripe.com/docs/issuing/purchases/disputes#dispute-reasons-and-evidence). """ @@ -994,11 +950,7 @@ def submit( @class_method_variant("_cls_submit") def submit( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Dispute.SubmitParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Dispute.SubmitParams"] ) -> "Dispute": """ Submits an Issuing Dispute to the card network. Stripe validates that all evidence fields required for the dispute's reason are present. For more details, see [Dispute reasons and evidence](https://stripe.com/docs/issuing/purchases/disputes#dispute-reasons-and-evidence). @@ -1010,7 +962,6 @@ def submit( # pyright: ignore[reportGeneralTypeIssues] "/v1/issuing/disputes/{dispute}/submit".format( dispute=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/issuing/_dispute_service.py b/stripe/issuing/_dispute_service.py new file mode 100644 index 000000000..ed1d2c528 --- /dev/null +++ b/stripe/issuing/_dispute_service.py @@ -0,0 +1,688 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.issuing._dispute import Dispute +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class DisputeService(StripeService): + class CreateParams(TypedDict): + amount: NotRequired["int"] + """ + The dispute amount in the card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). If not set, defaults to the full transaction amount. + """ + evidence: NotRequired["DisputeService.CreateParamsEvidence"] + """ + Evidence provided for the dispute. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + transaction: NotRequired["str"] + """ + The ID of the issuing transaction to create a dispute for. For transaction on Treasury FinancialAccounts, use `treasury.received_debit`. + """ + treasury: NotRequired["DisputeService.CreateParamsTreasury"] + """ + Params for disputes related to Treasury FinancialAccounts + """ + + class CreateParamsEvidence(TypedDict): + canceled: NotRequired[ + "Literal['']|DisputeService.CreateParamsEvidenceCanceled" + ] + """ + Evidence provided when `reason` is 'canceled'. + """ + duplicate: NotRequired[ + "Literal['']|DisputeService.CreateParamsEvidenceDuplicate" + ] + """ + Evidence provided when `reason` is 'duplicate'. + """ + fraudulent: NotRequired[ + "Literal['']|DisputeService.CreateParamsEvidenceFraudulent" + ] + """ + Evidence provided when `reason` is 'fraudulent'. + """ + merchandise_not_as_described: NotRequired[ + "Literal['']|DisputeService.CreateParamsEvidenceMerchandiseNotAsDescribed" + ] + """ + Evidence provided when `reason` is 'merchandise_not_as_described'. + """ + not_received: NotRequired[ + "Literal['']|DisputeService.CreateParamsEvidenceNotReceived" + ] + """ + Evidence provided when `reason` is 'not_received'. + """ + other: NotRequired[ + "Literal['']|DisputeService.CreateParamsEvidenceOther" + ] + """ + Evidence provided when `reason` is 'other'. + """ + reason: NotRequired[ + "Literal['canceled', 'duplicate', 'fraudulent', 'merchandise_not_as_described', 'not_received', 'other', 'service_not_as_described']" + ] + """ + The reason for filing the dispute. The evidence should be submitted in the field of the same name. + """ + service_not_as_described: NotRequired[ + "Literal['']|DisputeService.CreateParamsEvidenceServiceNotAsDescribed" + ] + """ + Evidence provided when `reason` is 'service_not_as_described'. + """ + + class CreateParamsEvidenceCanceled(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + canceled_at: NotRequired["Literal['']|int"] + """ + Date when order was canceled. + """ + cancellation_policy_provided: NotRequired["Literal['']|bool"] + """ + Whether the cardholder was provided with a cancellation policy. + """ + cancellation_reason: NotRequired["Literal['']|str"] + """ + Reason for canceling the order. + """ + expected_at: NotRequired["Literal['']|int"] + """ + Date when the cardholder expected to receive the product. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + product_description: NotRequired["Literal['']|str"] + """ + Description of the merchandise or service that was purchased. + """ + product_type: NotRequired[ + "Literal['']|Literal['merchandise', 'service']" + ] + """ + Whether the product was a merchandise or service. + """ + return_status: NotRequired[ + "Literal['']|Literal['merchant_rejected', 'successful']" + ] + """ + Result of cardholder's attempt to return the product. + """ + returned_at: NotRequired["Literal['']|int"] + """ + Date when the product was returned or attempted to be returned. + """ + + class CreateParamsEvidenceDuplicate(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + card_statement: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Copy of the card statement showing that the product had already been paid for. + """ + cash_receipt: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Copy of the receipt showing that the product had been paid for in cash. + """ + check_image: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Image of the front and back of the check that was used to pay for the product. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + original_transaction: NotRequired["str"] + """ + Transaction (e.g., ipi_...) that the disputed transaction is a duplicate of. Of the two or more transactions that are copies of each other, this is original undisputed one. + """ + + class CreateParamsEvidenceFraudulent(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + + class CreateParamsEvidenceMerchandiseNotAsDescribed(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + received_at: NotRequired["Literal['']|int"] + """ + Date when the product was received. + """ + return_description: NotRequired["Literal['']|str"] + """ + Description of the cardholder's attempt to return the product. + """ + return_status: NotRequired[ + "Literal['']|Literal['merchant_rejected', 'successful']" + ] + """ + Result of cardholder's attempt to return the product. + """ + returned_at: NotRequired["Literal['']|int"] + """ + Date when the product was returned or attempted to be returned. + """ + + class CreateParamsEvidenceNotReceived(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + expected_at: NotRequired["Literal['']|int"] + """ + Date when the cardholder expected to receive the product. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + product_description: NotRequired["Literal['']|str"] + """ + Description of the merchandise or service that was purchased. + """ + product_type: NotRequired[ + "Literal['']|Literal['merchandise', 'service']" + ] + """ + Whether the product was a merchandise or service. + """ + + class CreateParamsEvidenceOther(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + product_description: NotRequired["Literal['']|str"] + """ + Description of the merchandise or service that was purchased. + """ + product_type: NotRequired[ + "Literal['']|Literal['merchandise', 'service']" + ] + """ + Whether the product was a merchandise or service. + """ + + class CreateParamsEvidenceServiceNotAsDescribed(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + canceled_at: NotRequired["Literal['']|int"] + """ + Date when order was canceled. + """ + cancellation_reason: NotRequired["Literal['']|str"] + """ + Reason for canceling the order. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + received_at: NotRequired["Literal['']|int"] + """ + Date when the product was received. + """ + + class CreateParamsTreasury(TypedDict): + received_debit: str + """ + The ID of the ReceivedDebit to initiate an Issuings dispute for. + """ + + class ListParams(TypedDict): + created: NotRequired["DisputeService.ListParamsCreated|int"] + """ + Select Issuing disputes that were created during the given date interval. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired[ + "Literal['expired', 'lost', 'submitted', 'unsubmitted', 'won']" + ] + """ + Select Issuing disputes with the given status. + """ + transaction: NotRequired["str"] + """ + Select the Issuing dispute for the given transaction. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class SubmitParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class UpdateParams(TypedDict): + amount: NotRequired["int"] + """ + The dispute amount in the card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + """ + evidence: NotRequired["DisputeService.UpdateParamsEvidence"] + """ + Evidence provided for the dispute. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class UpdateParamsEvidence(TypedDict): + canceled: NotRequired[ + "Literal['']|DisputeService.UpdateParamsEvidenceCanceled" + ] + """ + Evidence provided when `reason` is 'canceled'. + """ + duplicate: NotRequired[ + "Literal['']|DisputeService.UpdateParamsEvidenceDuplicate" + ] + """ + Evidence provided when `reason` is 'duplicate'. + """ + fraudulent: NotRequired[ + "Literal['']|DisputeService.UpdateParamsEvidenceFraudulent" + ] + """ + Evidence provided when `reason` is 'fraudulent'. + """ + merchandise_not_as_described: NotRequired[ + "Literal['']|DisputeService.UpdateParamsEvidenceMerchandiseNotAsDescribed" + ] + """ + Evidence provided when `reason` is 'merchandise_not_as_described'. + """ + not_received: NotRequired[ + "Literal['']|DisputeService.UpdateParamsEvidenceNotReceived" + ] + """ + Evidence provided when `reason` is 'not_received'. + """ + other: NotRequired[ + "Literal['']|DisputeService.UpdateParamsEvidenceOther" + ] + """ + Evidence provided when `reason` is 'other'. + """ + reason: NotRequired[ + "Literal['canceled', 'duplicate', 'fraudulent', 'merchandise_not_as_described', 'not_received', 'other', 'service_not_as_described']" + ] + """ + The reason for filing the dispute. The evidence should be submitted in the field of the same name. + """ + service_not_as_described: NotRequired[ + "Literal['']|DisputeService.UpdateParamsEvidenceServiceNotAsDescribed" + ] + """ + Evidence provided when `reason` is 'service_not_as_described'. + """ + + class UpdateParamsEvidenceCanceled(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + canceled_at: NotRequired["Literal['']|int"] + """ + Date when order was canceled. + """ + cancellation_policy_provided: NotRequired["Literal['']|bool"] + """ + Whether the cardholder was provided with a cancellation policy. + """ + cancellation_reason: NotRequired["Literal['']|str"] + """ + Reason for canceling the order. + """ + expected_at: NotRequired["Literal['']|int"] + """ + Date when the cardholder expected to receive the product. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + product_description: NotRequired["Literal['']|str"] + """ + Description of the merchandise or service that was purchased. + """ + product_type: NotRequired[ + "Literal['']|Literal['merchandise', 'service']" + ] + """ + Whether the product was a merchandise or service. + """ + return_status: NotRequired[ + "Literal['']|Literal['merchant_rejected', 'successful']" + ] + """ + Result of cardholder's attempt to return the product. + """ + returned_at: NotRequired["Literal['']|int"] + """ + Date when the product was returned or attempted to be returned. + """ + + class UpdateParamsEvidenceDuplicate(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + card_statement: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Copy of the card statement showing that the product had already been paid for. + """ + cash_receipt: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Copy of the receipt showing that the product had been paid for in cash. + """ + check_image: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Image of the front and back of the check that was used to pay for the product. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + original_transaction: NotRequired["str"] + """ + Transaction (e.g., ipi_...) that the disputed transaction is a duplicate of. Of the two or more transactions that are copies of each other, this is original undisputed one. + """ + + class UpdateParamsEvidenceFraudulent(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + + class UpdateParamsEvidenceMerchandiseNotAsDescribed(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + received_at: NotRequired["Literal['']|int"] + """ + Date when the product was received. + """ + return_description: NotRequired["Literal['']|str"] + """ + Description of the cardholder's attempt to return the product. + """ + return_status: NotRequired[ + "Literal['']|Literal['merchant_rejected', 'successful']" + ] + """ + Result of cardholder's attempt to return the product. + """ + returned_at: NotRequired["Literal['']|int"] + """ + Date when the product was returned or attempted to be returned. + """ + + class UpdateParamsEvidenceNotReceived(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + expected_at: NotRequired["Literal['']|int"] + """ + Date when the cardholder expected to receive the product. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + product_description: NotRequired["Literal['']|str"] + """ + Description of the merchandise or service that was purchased. + """ + product_type: NotRequired[ + "Literal['']|Literal['merchandise', 'service']" + ] + """ + Whether the product was a merchandise or service. + """ + + class UpdateParamsEvidenceOther(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + product_description: NotRequired["Literal['']|str"] + """ + Description of the merchandise or service that was purchased. + """ + product_type: NotRequired[ + "Literal['']|Literal['merchandise', 'service']" + ] + """ + Whether the product was a merchandise or service. + """ + + class UpdateParamsEvidenceServiceNotAsDescribed(TypedDict): + additional_documentation: NotRequired["Literal['']|str"] + """ + (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Additional documentation supporting the dispute. + """ + canceled_at: NotRequired["Literal['']|int"] + """ + Date when order was canceled. + """ + cancellation_reason: NotRequired["Literal['']|str"] + """ + Reason for canceling the order. + """ + explanation: NotRequired["Literal['']|str"] + """ + Explanation of why the cardholder is disputing this transaction. + """ + received_at: NotRequired["Literal['']|int"] + """ + Date when the product was received. + """ + + def list( + self, + params: "DisputeService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Dispute]: + """ + Returns a list of Issuing Dispute objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. + """ + return cast( + ListObject[Dispute], + self._requestor.request( + "get", + "/v1/issuing/disputes", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "DisputeService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Dispute: + """ + Creates an Issuing Dispute object. Individual pieces of evidence within the evidence object are optional at this point. Stripe only validates that required evidence is present during submission. Refer to [Dispute reasons and evidence](https://stripe.com/docs/issuing/purchases/disputes#dispute-reasons-and-evidence) for more details about evidence requirements. + """ + return cast( + Dispute, + self._requestor.request( + "post", + "/v1/issuing/disputes", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + dispute: str, + params: "DisputeService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Dispute: + """ + Retrieves an Issuing Dispute object. + """ + return cast( + Dispute, + self._requestor.request( + "get", + "/v1/issuing/disputes/{dispute}".format( + dispute=_util.sanitize_id(dispute), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + dispute: str, + params: "DisputeService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Dispute: + """ + Updates the specified Issuing Dispute object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. Properties on the evidence object can be unset by passing in an empty string. + """ + return cast( + Dispute, + self._requestor.request( + "post", + "/v1/issuing/disputes/{dispute}".format( + dispute=_util.sanitize_id(dispute), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def submit( + self, + dispute: str, + params: "DisputeService.SubmitParams" = {}, + options: RequestOptions = {}, + ) -> Dispute: + """ + Submits an Issuing Dispute to the card network. Stripe validates that all evidence fields required for the dispute's reason are present. For more details, see [Dispute reasons and evidence](https://stripe.com/docs/issuing/purchases/disputes#dispute-reasons-and-evidence). + """ + return cast( + Dispute, + self._requestor.request( + "post", + "/v1/issuing/disputes/{dispute}/submit".format( + dispute=_util.sanitize_id(dispute), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/issuing/_token.py b/stripe/issuing/_token.py index cb73e0248..2f1336ef9 100644 --- a/stripe/issuing/_token.py +++ b/stripe/issuing/_token.py @@ -307,24 +307,13 @@ class RetrieveParams(RequestOptions): """ @classmethod - def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Token.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> ListObject["Token"]: + def list(cls, **params: Unpack["Token.ListParams"]) -> ListObject["Token"]: """ Lists all Issuing Token objects for a given card. """ result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/issuing/_token_service.py b/stripe/issuing/_token_service.py new file mode 100644 index 000000000..a5cab97a1 --- /dev/null +++ b/stripe/issuing/_token_service.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.issuing._token import Token +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class TokenService(StripeService): + class ListParams(TypedDict): + card: str + """ + The Issuing card identifier to list tokens for. + """ + created: NotRequired["TokenService.ListParamsCreated|int"] + """ + Select Issuing tokens that were created during the given date interval. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired[ + "Literal['active', 'deleted', 'requested', 'suspended']" + ] + """ + Select Issuing tokens with the given status. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + status: Literal["active", "deleted", "suspended"] + """ + Specifies which status the token should be updated to. + """ + + def list( + self, params: "TokenService.ListParams", options: RequestOptions = {} + ) -> ListObject[Token]: + """ + Lists all Issuing Token objects for a given card. + """ + return cast( + ListObject[Token], + self._requestor.request( + "get", + "/v1/issuing/tokens", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + token: str, + params: "TokenService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Token: + """ + Retrieves an Issuing Token object. + """ + return cast( + Token, + self._requestor.request( + "get", + "/v1/issuing/tokens/{token}".format( + token=_util.sanitize_id(token), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + token: str, + params: "TokenService.UpdateParams", + options: RequestOptions = {}, + ) -> Token: + """ + Attempts to update the specified Issuing Token object to the status specified. + """ + return cast( + Token, + self._requestor.request( + "post", + "/v1/issuing/tokens/{token}".format( + token=_util.sanitize_id(token), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/issuing/_transaction.py b/stripe/issuing/_transaction.py index e4f32d6d4..63d56944e 100644 --- a/stripe/issuing/_transaction.py +++ b/stripe/issuing/_transaction.py @@ -782,13 +782,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transaction.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Transaction.ListParams"] ) -> ListObject["Transaction"]: """ Returns a list of Issuing Transaction objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. @@ -796,9 +790,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -839,13 +830,7 @@ class TestHelpers(APIResourceTestHelpers["Transaction"]): @classmethod def create_force_capture( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transaction.CreateForceCaptureParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Transaction.CreateForceCaptureParams"] ) -> "Transaction": """ Allows the user to capture an arbitrary amount, also known as a forced capture. @@ -855,22 +840,13 @@ def create_force_capture( cls._static_request( "post", "/v1/test_helpers/issuing/transactions/create_force_capture", - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def create_unlinked_refund( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transaction.CreateUnlinkedRefundParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Transaction.CreateUnlinkedRefundParams"] ) -> "Transaction": """ Allows the user to refund an arbitrary amount, also known as a unlinked refund. @@ -880,23 +856,13 @@ def create_unlinked_refund( cls._static_request( "post", "/v1/test_helpers/issuing/transactions/create_unlinked_refund", - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def _cls_refund( - cls, - transaction: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transaction.RefundParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, transaction: str, **params: Unpack["Transaction.RefundParams"] ) -> "Transaction": """ Refund a test-mode Transaction. @@ -908,9 +874,6 @@ def _cls_refund( "/v1/test_helpers/issuing/transactions/{transaction}/refund".format( transaction=_util.sanitize_id(transaction) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -918,13 +881,7 @@ def _cls_refund( @overload @staticmethod def refund( - transaction: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transaction.RefundParams" - ] # pyright: ignore[reportGeneralTypeIssues] + transaction: str, **params: Unpack["Transaction.RefundParams"] ) -> "Transaction": """ Refund a test-mode Transaction. @@ -933,11 +890,7 @@ def refund( @overload def refund( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Transaction.RefundParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Transaction.RefundParams"] ) -> "Transaction": """ Refund a test-mode Transaction. @@ -946,11 +899,7 @@ def refund( @class_method_variant("_cls_refund") def refund( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Transaction.RefundParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Transaction.RefundParams"] ) -> "Transaction": """ Refund a test-mode Transaction. @@ -962,7 +911,6 @@ def refund( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/issuing/transactions/{transaction}/refund".format( transaction=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/issuing/_transaction_service.py b/stripe/issuing/_transaction_service.py new file mode 100644 index 000000000..8f6b5bdf8 --- /dev/null +++ b/stripe/issuing/_transaction_service.py @@ -0,0 +1,145 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.issuing._transaction import Transaction +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class TransactionService(StripeService): + class ListParams(TypedDict): + card: NotRequired["str"] + """ + Only return transactions that belong to the given card. + """ + cardholder: NotRequired["str"] + """ + Only return transactions that belong to the given cardholder. + """ + created: NotRequired["TransactionService.ListParamsCreated|int"] + """ + Only return transactions that were created during the given date interval. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + type: NotRequired["Literal['capture', 'refund']"] + """ + Only return transactions that have the given type. One of `capture` or `refund`. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + def list( + self, + params: "TransactionService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Transaction]: + """ + Returns a list of Issuing Transaction objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. + """ + return cast( + ListObject[Transaction], + self._requestor.request( + "get", + "/v1/issuing/transactions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + transaction: str, + params: "TransactionService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Transaction: + """ + Retrieves an Issuing Transaction object. + """ + return cast( + Transaction, + self._requestor.request( + "get", + "/v1/issuing/transactions/{transaction}".format( + transaction=_util.sanitize_id(transaction), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + transaction: str, + params: "TransactionService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Transaction: + """ + Updates the specified Issuing Transaction object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + """ + return cast( + Transaction, + self._requestor.request( + "post", + "/v1/issuing/transactions/{transaction}".format( + transaction=_util.sanitize_id(transaction), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/oauth_error.py b/stripe/oauth_error.py index 034c89b6c..baad50887 100644 --- a/stripe/oauth_error.py +++ b/stripe/oauth_error.py @@ -17,12 +17,14 @@ def __init__( description, http_body, http_status, json_body, headers, code ) - def construct_error_object(self): + def _construct_error_object(self): if self.json_body is None: return None - return stripe.error_object.OAuthErrorObject.construct_from( # pyright: ignore - self.json_body, stripe.api_key + return stripe.error_object.OAuthErrorObject._construct_from( # pyright: ignore + values=self.json_body, + requestor=stripe._APIRequestor._global_instance(), + api_mode="V1", ) diff --git a/stripe/radar/__init__.py b/stripe/radar/__init__.py index 18cc09b28..7af17ee3d 100644 --- a/stripe/radar/__init__.py +++ b/stripe/radar/__init__.py @@ -3,5 +3,14 @@ from stripe.radar._early_fraud_warning import ( EarlyFraudWarning as EarlyFraudWarning, ) +from stripe.radar._early_fraud_warning_service import ( + EarlyFraudWarningService as EarlyFraudWarningService, +) from stripe.radar._value_list import ValueList as ValueList from stripe.radar._value_list_item import ValueListItem as ValueListItem +from stripe.radar._value_list_item_service import ( + ValueListItemService as ValueListItemService, +) +from stripe.radar._value_list_service import ( + ValueListService as ValueListService, +) diff --git a/stripe/radar/_early_fraud_warning.py b/stripe/radar/_early_fraud_warning.py index 28f883e99..2204622c2 100644 --- a/stripe/radar/_early_fraud_warning.py +++ b/stripe/radar/_early_fraud_warning.py @@ -119,13 +119,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "EarlyFraudWarning.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["EarlyFraudWarning.ListParams"] ) -> ListObject["EarlyFraudWarning"]: """ Returns a list of early fraud warnings. @@ -133,9 +127,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/radar/_early_fraud_warning_service.py b/stripe/radar/_early_fraud_warning_service.py new file mode 100644 index 000000000..2d4a2b0f7 --- /dev/null +++ b/stripe/radar/_early_fraud_warning_service.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.radar._early_fraud_warning import EarlyFraudWarning +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class EarlyFraudWarningService(StripeService): + class ListParams(TypedDict): + charge: NotRequired["str"] + """ + Only return early fraud warnings for the charge specified by this charge ID. + """ + created: NotRequired["EarlyFraudWarningService.ListParamsCreated|int"] + """ + Only return early fraud warnings that were created during the given date interval. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + payment_intent: NotRequired["str"] + """ + Only return early fraud warnings for charges that were created by the PaymentIntent specified by this PaymentIntent ID. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "EarlyFraudWarningService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[EarlyFraudWarning]: + """ + Returns a list of early fraud warnings. + """ + return cast( + ListObject[EarlyFraudWarning], + self._requestor.request( + "get", + "/v1/radar/early_fraud_warnings", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + early_fraud_warning: str, + params: "EarlyFraudWarningService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> EarlyFraudWarning: + """ + Retrieves the details of an early fraud warning that has previously been created. + + Please refer to the [early fraud warning](https://stripe.com/docs/api#early_fraud_warning_object) object reference for more details. + """ + return cast( + EarlyFraudWarning, + self._requestor.request( + "get", + "/v1/radar/early_fraud_warnings/{early_fraud_warning}".format( + early_fraud_warning=_util.sanitize_id(early_fraud_warning), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/radar/_value_list.py b/stripe/radar/_value_list.py index 5e5bb19d7..3ffe09d27 100644 --- a/stripe/radar/_value_list.py +++ b/stripe/radar/_value_list.py @@ -188,16 +188,7 @@ class RetrieveParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ValueList.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "ValueList": + def create(cls, **params: Unpack["ValueList.CreateParams"]) -> "ValueList": """ Creates a new ValueList object, which can then be referenced in rules. """ @@ -206,10 +197,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -261,13 +248,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ValueList.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ValueList.ListParams"] ) -> ListObject["ValueList"]: """ Returns a list of ValueList objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. @@ -275,9 +256,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/radar/_value_list_item.py b/stripe/radar/_value_list_item.py index 28fb64bc4..f27bdf021 100644 --- a/stripe/radar/_value_list_item.py +++ b/stripe/radar/_value_list_item.py @@ -129,14 +129,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ValueListItem.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ValueListItem.CreateParams"] ) -> "ValueListItem": """ Creates a new ValueListItem object, which is added to the specified parent value list. @@ -146,10 +139,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -201,13 +190,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ValueListItem.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ValueListItem.ListParams"] ) -> ListObject["ValueListItem"]: """ Returns a list of ValueListItem objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. @@ -215,9 +198,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/radar/_value_list_item_service.py b/stripe/radar/_value_list_item_service.py new file mode 100644 index 000000000..26138f75f --- /dev/null +++ b/stripe/radar/_value_list_item_service.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.radar._value_list_item import ValueListItem +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class ValueListItemService(StripeService): + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + value: str + """ + The value of the item (whose type must match the type of the parent value list). + """ + value_list: str + """ + The identifier of the value list which the created item will be added to. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + created: NotRequired["ValueListItemService.ListParamsCreated|int"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + value: NotRequired["str"] + """ + Return items belonging to the parent list whose value matches the specified value (using an "is like" match). + """ + value_list: str + """ + Identifier for the parent value list this item belongs to. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def delete( + self, + item: str, + params: "ValueListItemService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> ValueListItem: + """ + Deletes a ValueListItem object, removing it from its parent value list. + """ + return cast( + ValueListItem, + self._requestor.request( + "delete", + "/v1/radar/value_list_items/{item}".format( + item=_util.sanitize_id(item), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + item: str, + params: "ValueListItemService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> ValueListItem: + """ + Retrieves a ValueListItem object. + """ + return cast( + ValueListItem, + self._requestor.request( + "get", + "/v1/radar/value_list_items/{item}".format( + item=_util.sanitize_id(item), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "ValueListItemService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[ValueListItem]: + """ + Returns a list of ValueListItem objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. + """ + return cast( + ListObject[ValueListItem], + self._requestor.request( + "get", + "/v1/radar/value_list_items", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "ValueListItemService.CreateParams", + options: RequestOptions = {}, + ) -> ValueListItem: + """ + Creates a new ValueListItem object, which is added to the specified parent value list. + """ + return cast( + ValueListItem, + self._requestor.request( + "post", + "/v1/radar/value_list_items", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/radar/_value_list_service.py b/stripe/radar/_value_list_service.py new file mode 100644 index 000000000..b801935e9 --- /dev/null +++ b/stripe/radar/_value_list_service.py @@ -0,0 +1,216 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.radar._value_list import ValueList +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ValueListService(StripeService): + class CreateParams(TypedDict): + alias: str + """ + The name of the value list for use in rules. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + item_type: NotRequired[ + "Literal['card_bin', 'card_fingerprint', 'case_sensitive_string', 'country', 'customer_id', 'email', 'ip_address', 'sepa_debit_fingerprint', 'string', 'us_bank_account_fingerprint']" + ] + """ + Type of the items in the value list. One of `card_fingerprint`, `us_bank_account_fingerprint`, `sepa_debit_fingerprint`, `card_bin`, `email`, `ip_address`, `country`, `string`, `case_sensitive_string`, or `customer_id`. Use `string` if the item type is unknown or mixed. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: str + """ + The human-readable name of the value list. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + alias: NotRequired["str"] + """ + The alias used to reference the value list when writing rules. + """ + contains: NotRequired["str"] + """ + A value contained within a value list - returns all value lists containing this value. + """ + created: NotRequired["ValueListService.ListParamsCreated|int"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + alias: NotRequired["str"] + """ + The name of the value list for use in rules. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + name: NotRequired["str"] + """ + The human-readable name of the value list. + """ + + def delete( + self, + value_list: str, + params: "ValueListService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> ValueList: + """ + Deletes a ValueList object, also deleting any items contained within the value list. To be deleted, a value list must not be referenced in any rules. + """ + return cast( + ValueList, + self._requestor.request( + "delete", + "/v1/radar/value_lists/{value_list}".format( + value_list=_util.sanitize_id(value_list), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + value_list: str, + params: "ValueListService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> ValueList: + """ + Retrieves a ValueList object. + """ + return cast( + ValueList, + self._requestor.request( + "get", + "/v1/radar/value_lists/{value_list}".format( + value_list=_util.sanitize_id(value_list), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + value_list: str, + params: "ValueListService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> ValueList: + """ + Updates a ValueList object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. Note that item_type is immutable. + """ + return cast( + ValueList, + self._requestor.request( + "post", + "/v1/radar/value_lists/{value_list}".format( + value_list=_util.sanitize_id(value_list), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "ValueListService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[ValueList]: + """ + Returns a list of ValueList objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first. + """ + return cast( + ListObject[ValueList], + self._requestor.request( + "get", + "/v1/radar/value_lists", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "ValueListService.CreateParams", + options: RequestOptions = {}, + ) -> ValueList: + """ + Creates a new ValueList object, which can then be referenced in rules. + """ + return cast( + ValueList, + self._requestor.request( + "post", + "/v1/radar/value_lists", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/reporting/__init__.py b/stripe/reporting/__init__.py index 4089326e8..c06dc2c41 100644 --- a/stripe/reporting/__init__.py +++ b/stripe/reporting/__init__.py @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*- # File generated from our OpenAPI spec from stripe.reporting._report_run import ReportRun as ReportRun +from stripe.reporting._report_run_service import ( + ReportRunService as ReportRunService, +) from stripe.reporting._report_type import ReportType as ReportType +from stripe.reporting._report_type_service import ( + ReportTypeService as ReportTypeService, +) diff --git a/stripe/reporting/_report_run.py b/stripe/reporting/_report_run.py index 78fd6fd63..bfbfda3b6 100644 --- a/stripe/reporting/_report_run.py +++ b/stripe/reporting/_report_run.py @@ -210,16 +210,7 @@ class RetrieveParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ReportRun.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "ReportRun": + def create(cls, **params: Unpack["ReportRun.CreateParams"]) -> "ReportRun": """ Creates a new object and begin running the report. (Certain report types require a [live-mode API key](https://stripe.com/docs/keys#test-live-modes).) """ @@ -228,23 +219,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ReportRun.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ReportRun.ListParams"] ) -> ListObject["ReportRun"]: """ Returns a list of Report Runs, with the most recent appearing first. @@ -252,9 +233,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/reporting/_report_run_service.py b/stripe/reporting/_report_run_service.py new file mode 100644 index 000000000..3cfeca801 --- /dev/null +++ b/stripe/reporting/_report_run_service.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.reporting._report_run import ReportRun +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ReportRunService(StripeService): + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + parameters: NotRequired["ReportRunService.CreateParamsParameters"] + """ + Parameters specifying how the report should be run. Different Report Types have different required and optional parameters, listed in the [API Access to Reports](https://stripe.com/docs/reporting/statements/api) documentation. + """ + report_type: str + """ + The ID of the [report type](https://stripe.com/docs/reporting/statements/api#report-types) to run, such as `"balance.summary.1"`. + """ + + class CreateParamsParameters(TypedDict): + columns: NotRequired["List[str]"] + """ + The set of report columns to include in the report output. If omitted, the Report Type is run with its default column set. + """ + connected_account: NotRequired["str"] + """ + Connected account ID to filter for in the report run. + """ + currency: NotRequired["str"] + """ + Currency of objects to be included in the report run. + """ + interval_end: NotRequired["int"] + """ + Ending timestamp of data to be included in the report run (exclusive). + """ + interval_start: NotRequired["int"] + """ + Starting timestamp of data to be included in the report run. + """ + payout: NotRequired["str"] + """ + Payout ID by which to filter the report run. + """ + reporting_category: NotRequired[ + "Literal['advance', 'advance_funding', 'anticipation_repayment', 'charge', 'charge_failure', 'climate_order_purchase', 'climate_order_refund', 'connect_collection_transfer', 'connect_reserved_funds', 'contribution', 'dispute', 'dispute_reversal', 'fee', 'financing_paydown', 'financing_paydown_reversal', 'financing_payout', 'financing_payout_reversal', 'issuing_authorization_hold', 'issuing_authorization_release', 'issuing_dispute', 'issuing_transaction', 'network_cost', 'other_adjustment', 'partial_capture_reversal', 'payout', 'payout_reversal', 'platform_earning', 'platform_earning_refund', 'refund', 'refund_failure', 'risk_reserved_funds', 'tax', 'topup', 'topup_reversal', 'transfer', 'transfer_reversal', 'unreconciled_customer_funds', 'obligation']" + ] + """ + Category of balance transactions to be included in the report run. + """ + timezone: NotRequired[ + "Literal['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara', 'Africa/Asmera', 'Africa/Bamako', 'Africa/Bangui', 'Africa/Banjul', 'Africa/Bissau', 'Africa/Blantyre', 'Africa/Brazzaville', 'Africa/Bujumbura', 'Africa/Cairo', 'Africa/Casablanca', 'Africa/Ceuta', 'Africa/Conakry', 'Africa/Dakar', 'Africa/Dar_es_Salaam', 'Africa/Djibouti', 'Africa/Douala', 'Africa/El_Aaiun', 'Africa/Freetown', 'Africa/Gaborone', 'Africa/Harare', 'Africa/Johannesburg', 'Africa/Juba', 'Africa/Kampala', 'Africa/Khartoum', 'Africa/Kigali', 'Africa/Kinshasa', 'Africa/Lagos', 'Africa/Libreville', 'Africa/Lome', 'Africa/Luanda', 'Africa/Lubumbashi', 'Africa/Lusaka', 'Africa/Malabo', 'Africa/Maputo', 'Africa/Maseru', 'Africa/Mbabane', 'Africa/Mogadishu', 'Africa/Monrovia', 'Africa/Nairobi', 'Africa/Ndjamena', 'Africa/Niamey', 'Africa/Nouakchott', 'Africa/Ouagadougou', 'Africa/Porto-Novo', 'Africa/Sao_Tome', 'Africa/Timbuktu', 'Africa/Tripoli', 'Africa/Tunis', 'Africa/Windhoek', 'America/Adak', 'America/Anchorage', 'America/Anguilla', 'America/Antigua', 'America/Araguaina', 'America/Argentina/Buenos_Aires', 'America/Argentina/Catamarca', 'America/Argentina/ComodRivadavia', 'America/Argentina/Cordoba', 'America/Argentina/Jujuy', 'America/Argentina/La_Rioja', 'America/Argentina/Mendoza', 'America/Argentina/Rio_Gallegos', 'America/Argentina/Salta', 'America/Argentina/San_Juan', 'America/Argentina/San_Luis', 'America/Argentina/Tucuman', 'America/Argentina/Ushuaia', 'America/Aruba', 'America/Asuncion', 'America/Atikokan', 'America/Atka', 'America/Bahia', 'America/Bahia_Banderas', 'America/Barbados', 'America/Belem', 'America/Belize', 'America/Blanc-Sablon', 'America/Boa_Vista', 'America/Bogota', 'America/Boise', 'America/Buenos_Aires', 'America/Cambridge_Bay', 'America/Campo_Grande', 'America/Cancun', 'America/Caracas', 'America/Catamarca', 'America/Cayenne', 'America/Cayman', 'America/Chicago', 'America/Chihuahua', 'America/Ciudad_Juarez', 'America/Coral_Harbour', 'America/Cordoba', 'America/Costa_Rica', 'America/Creston', 'America/Cuiaba', 'America/Curacao', 'America/Danmarkshavn', 'America/Dawson', 'America/Dawson_Creek', 'America/Denver', 'America/Detroit', 'America/Dominica', 'America/Edmonton', 'America/Eirunepe', 'America/El_Salvador', 'America/Ensenada', 'America/Fort_Nelson', 'America/Fort_Wayne', 'America/Fortaleza', 'America/Glace_Bay', 'America/Godthab', 'America/Goose_Bay', 'America/Grand_Turk', 'America/Grenada', 'America/Guadeloupe', 'America/Guatemala', 'America/Guayaquil', 'America/Guyana', 'America/Halifax', 'America/Havana', 'America/Hermosillo', 'America/Indiana/Indianapolis', 'America/Indiana/Knox', 'America/Indiana/Marengo', 'America/Indiana/Petersburg', 'America/Indiana/Tell_City', 'America/Indiana/Vevay', 'America/Indiana/Vincennes', 'America/Indiana/Winamac', 'America/Indianapolis', 'America/Inuvik', 'America/Iqaluit', 'America/Jamaica', 'America/Jujuy', 'America/Juneau', 'America/Kentucky/Louisville', 'America/Kentucky/Monticello', 'America/Knox_IN', 'America/Kralendijk', 'America/La_Paz', 'America/Lima', 'America/Los_Angeles', 'America/Louisville', 'America/Lower_Princes', 'America/Maceio', 'America/Managua', 'America/Manaus', 'America/Marigot', 'America/Martinique', 'America/Matamoros', 'America/Mazatlan', 'America/Mendoza', 'America/Menominee', 'America/Merida', 'America/Metlakatla', 'America/Mexico_City', 'America/Miquelon', 'America/Moncton', 'America/Monterrey', 'America/Montevideo', 'America/Montreal', 'America/Montserrat', 'America/Nassau', 'America/New_York', 'America/Nipigon', 'America/Nome', 'America/Noronha', 'America/North_Dakota/Beulah', 'America/North_Dakota/Center', 'America/North_Dakota/New_Salem', 'America/Nuuk', 'America/Ojinaga', 'America/Panama', 'America/Pangnirtung', 'America/Paramaribo', 'America/Phoenix', 'America/Port-au-Prince', 'America/Port_of_Spain', 'America/Porto_Acre', 'America/Porto_Velho', 'America/Puerto_Rico', 'America/Punta_Arenas', 'America/Rainy_River', 'America/Rankin_Inlet', 'America/Recife', 'America/Regina', 'America/Resolute', 'America/Rio_Branco', 'America/Rosario', 'America/Santa_Isabel', 'America/Santarem', 'America/Santiago', 'America/Santo_Domingo', 'America/Sao_Paulo', 'America/Scoresbysund', 'America/Shiprock', 'America/Sitka', 'America/St_Barthelemy', 'America/St_Johns', 'America/St_Kitts', 'America/St_Lucia', 'America/St_Thomas', 'America/St_Vincent', 'America/Swift_Current', 'America/Tegucigalpa', 'America/Thule', 'America/Thunder_Bay', 'America/Tijuana', 'America/Toronto', 'America/Tortola', 'America/Vancouver', 'America/Virgin', 'America/Whitehorse', 'America/Winnipeg', 'America/Yakutat', 'America/Yellowknife', 'Antarctica/Casey', 'Antarctica/Davis', 'Antarctica/DumontDUrville', 'Antarctica/Macquarie', 'Antarctica/Mawson', 'Antarctica/McMurdo', 'Antarctica/Palmer', 'Antarctica/Rothera', 'Antarctica/South_Pole', 'Antarctica/Syowa', 'Antarctica/Troll', 'Antarctica/Vostok', 'Arctic/Longyearbyen', 'Asia/Aden', 'Asia/Almaty', 'Asia/Amman', 'Asia/Anadyr', 'Asia/Aqtau', 'Asia/Aqtobe', 'Asia/Ashgabat', 'Asia/Ashkhabad', 'Asia/Atyrau', 'Asia/Baghdad', 'Asia/Bahrain', 'Asia/Baku', 'Asia/Bangkok', 'Asia/Barnaul', 'Asia/Beirut', 'Asia/Bishkek', 'Asia/Brunei', 'Asia/Calcutta', 'Asia/Chita', 'Asia/Choibalsan', 'Asia/Chongqing', 'Asia/Chungking', 'Asia/Colombo', 'Asia/Dacca', 'Asia/Damascus', 'Asia/Dhaka', 'Asia/Dili', 'Asia/Dubai', 'Asia/Dushanbe', 'Asia/Famagusta', 'Asia/Gaza', 'Asia/Harbin', 'Asia/Hebron', 'Asia/Ho_Chi_Minh', 'Asia/Hong_Kong', 'Asia/Hovd', 'Asia/Irkutsk', 'Asia/Istanbul', 'Asia/Jakarta', 'Asia/Jayapura', 'Asia/Jerusalem', 'Asia/Kabul', 'Asia/Kamchatka', 'Asia/Karachi', 'Asia/Kashgar', 'Asia/Kathmandu', 'Asia/Katmandu', 'Asia/Khandyga', 'Asia/Kolkata', 'Asia/Krasnoyarsk', 'Asia/Kuala_Lumpur', 'Asia/Kuching', 'Asia/Kuwait', 'Asia/Macao', 'Asia/Macau', 'Asia/Magadan', 'Asia/Makassar', 'Asia/Manila', 'Asia/Muscat', 'Asia/Nicosia', 'Asia/Novokuznetsk', 'Asia/Novosibirsk', 'Asia/Omsk', 'Asia/Oral', 'Asia/Phnom_Penh', 'Asia/Pontianak', 'Asia/Pyongyang', 'Asia/Qatar', 'Asia/Qostanay', 'Asia/Qyzylorda', 'Asia/Rangoon', 'Asia/Riyadh', 'Asia/Saigon', 'Asia/Sakhalin', 'Asia/Samarkand', 'Asia/Seoul', 'Asia/Shanghai', 'Asia/Singapore', 'Asia/Srednekolymsk', 'Asia/Taipei', 'Asia/Tashkent', 'Asia/Tbilisi', 'Asia/Tehran', 'Asia/Tel_Aviv', 'Asia/Thimbu', 'Asia/Thimphu', 'Asia/Tokyo', 'Asia/Tomsk', 'Asia/Ujung_Pandang', 'Asia/Ulaanbaatar', 'Asia/Ulan_Bator', 'Asia/Urumqi', 'Asia/Ust-Nera', 'Asia/Vientiane', 'Asia/Vladivostok', 'Asia/Yakutsk', 'Asia/Yangon', 'Asia/Yekaterinburg', 'Asia/Yerevan', 'Atlantic/Azores', 'Atlantic/Bermuda', 'Atlantic/Canary', 'Atlantic/Cape_Verde', 'Atlantic/Faeroe', 'Atlantic/Faroe', 'Atlantic/Jan_Mayen', 'Atlantic/Madeira', 'Atlantic/Reykjavik', 'Atlantic/South_Georgia', 'Atlantic/St_Helena', 'Atlantic/Stanley', 'Australia/ACT', 'Australia/Adelaide', 'Australia/Brisbane', 'Australia/Broken_Hill', 'Australia/Canberra', 'Australia/Currie', 'Australia/Darwin', 'Australia/Eucla', 'Australia/Hobart', 'Australia/LHI', 'Australia/Lindeman', 'Australia/Lord_Howe', 'Australia/Melbourne', 'Australia/NSW', 'Australia/North', 'Australia/Perth', 'Australia/Queensland', 'Australia/South', 'Australia/Sydney', 'Australia/Tasmania', 'Australia/Victoria', 'Australia/West', 'Australia/Yancowinna', 'Brazil/Acre', 'Brazil/DeNoronha', 'Brazil/East', 'Brazil/West', 'CET', 'CST6CDT', 'Canada/Atlantic', 'Canada/Central', 'Canada/Eastern', 'Canada/Mountain', 'Canada/Newfoundland', 'Canada/Pacific', 'Canada/Saskatchewan', 'Canada/Yukon', 'Chile/Continental', 'Chile/EasterIsland', 'Cuba', 'EET', 'EST', 'EST5EDT', 'Egypt', 'Eire', 'Etc/GMT', 'Etc/GMT+0', 'Etc/GMT+1', 'Etc/GMT+10', 'Etc/GMT+11', 'Etc/GMT+12', 'Etc/GMT+2', 'Etc/GMT+3', 'Etc/GMT+4', 'Etc/GMT+5', 'Etc/GMT+6', 'Etc/GMT+7', 'Etc/GMT+8', 'Etc/GMT+9', 'Etc/GMT-0', 'Etc/GMT-1', 'Etc/GMT-10', 'Etc/GMT-11', 'Etc/GMT-12', 'Etc/GMT-13', 'Etc/GMT-14', 'Etc/GMT-2', 'Etc/GMT-3', 'Etc/GMT-4', 'Etc/GMT-5', 'Etc/GMT-6', 'Etc/GMT-7', 'Etc/GMT-8', 'Etc/GMT-9', 'Etc/GMT0', 'Etc/Greenwich', 'Etc/UCT', 'Etc/UTC', 'Etc/Universal', 'Etc/Zulu', 'Europe/Amsterdam', 'Europe/Andorra', 'Europe/Astrakhan', 'Europe/Athens', 'Europe/Belfast', 'Europe/Belgrade', 'Europe/Berlin', 'Europe/Bratislava', 'Europe/Brussels', 'Europe/Bucharest', 'Europe/Budapest', 'Europe/Busingen', 'Europe/Chisinau', 'Europe/Copenhagen', 'Europe/Dublin', 'Europe/Gibraltar', 'Europe/Guernsey', 'Europe/Helsinki', 'Europe/Isle_of_Man', 'Europe/Istanbul', 'Europe/Jersey', 'Europe/Kaliningrad', 'Europe/Kiev', 'Europe/Kirov', 'Europe/Kyiv', 'Europe/Lisbon', 'Europe/Ljubljana', 'Europe/London', 'Europe/Luxembourg', 'Europe/Madrid', 'Europe/Malta', 'Europe/Mariehamn', 'Europe/Minsk', 'Europe/Monaco', 'Europe/Moscow', 'Europe/Nicosia', 'Europe/Oslo', 'Europe/Paris', 'Europe/Podgorica', 'Europe/Prague', 'Europe/Riga', 'Europe/Rome', 'Europe/Samara', 'Europe/San_Marino', 'Europe/Sarajevo', 'Europe/Saratov', 'Europe/Simferopol', 'Europe/Skopje', 'Europe/Sofia', 'Europe/Stockholm', 'Europe/Tallinn', 'Europe/Tirane', 'Europe/Tiraspol', 'Europe/Ulyanovsk', 'Europe/Uzhgorod', 'Europe/Vaduz', 'Europe/Vatican', 'Europe/Vienna', 'Europe/Vilnius', 'Europe/Volgograd', 'Europe/Warsaw', 'Europe/Zagreb', 'Europe/Zaporozhye', 'Europe/Zurich', 'Factory', 'GB', 'GB-Eire', 'GMT', 'GMT+0', 'GMT-0', 'GMT0', 'Greenwich', 'HST', 'Hongkong', 'Iceland', 'Indian/Antananarivo', 'Indian/Chagos', 'Indian/Christmas', 'Indian/Cocos', 'Indian/Comoro', 'Indian/Kerguelen', 'Indian/Mahe', 'Indian/Maldives', 'Indian/Mauritius', 'Indian/Mayotte', 'Indian/Reunion', 'Iran', 'Israel', 'Jamaica', 'Japan', 'Kwajalein', 'Libya', 'MET', 'MST', 'MST7MDT', 'Mexico/BajaNorte', 'Mexico/BajaSur', 'Mexico/General', 'NZ', 'NZ-CHAT', 'Navajo', 'PRC', 'PST8PDT', 'Pacific/Apia', 'Pacific/Auckland', 'Pacific/Bougainville', 'Pacific/Chatham', 'Pacific/Chuuk', 'Pacific/Easter', 'Pacific/Efate', 'Pacific/Enderbury', 'Pacific/Fakaofo', 'Pacific/Fiji', 'Pacific/Funafuti', 'Pacific/Galapagos', 'Pacific/Gambier', 'Pacific/Guadalcanal', 'Pacific/Guam', 'Pacific/Honolulu', 'Pacific/Johnston', 'Pacific/Kanton', 'Pacific/Kiritimati', 'Pacific/Kosrae', 'Pacific/Kwajalein', 'Pacific/Majuro', 'Pacific/Marquesas', 'Pacific/Midway', 'Pacific/Nauru', 'Pacific/Niue', 'Pacific/Norfolk', 'Pacific/Noumea', 'Pacific/Pago_Pago', 'Pacific/Palau', 'Pacific/Pitcairn', 'Pacific/Pohnpei', 'Pacific/Ponape', 'Pacific/Port_Moresby', 'Pacific/Rarotonga', 'Pacific/Saipan', 'Pacific/Samoa', 'Pacific/Tahiti', 'Pacific/Tarawa', 'Pacific/Tongatapu', 'Pacific/Truk', 'Pacific/Wake', 'Pacific/Wallis', 'Pacific/Yap', 'Poland', 'Portugal', 'ROC', 'ROK', 'Singapore', 'Turkey', 'UCT', 'US/Alaska', 'US/Aleutian', 'US/Arizona', 'US/Central', 'US/East-Indiana', 'US/Eastern', 'US/Hawaii', 'US/Indiana-Starke', 'US/Michigan', 'US/Mountain', 'US/Pacific', 'US/Pacific-New', 'US/Samoa', 'UTC', 'Universal', 'W-SU', 'WET', 'Zulu']" + ] + """ + Defaults to `Etc/UTC`. The output timezone for all timestamps in the report. A list of possible time zone values is maintained at the [IANA Time Zone Database](http://www.iana.org/time-zones). Has no effect on `interval_start` or `interval_end`. + """ + + class ListParams(TypedDict): + created: NotRequired["ReportRunService.ListParamsCreated|int"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "ReportRunService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[ReportRun]: + """ + Returns a list of Report Runs, with the most recent appearing first. + """ + return cast( + ListObject[ReportRun], + self._requestor.request( + "get", + "/v1/reporting/report_runs", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "ReportRunService.CreateParams", + options: RequestOptions = {}, + ) -> ReportRun: + """ + Creates a new object and begin running the report. (Certain report types require a [live-mode API key](https://stripe.com/docs/keys#test-live-modes).) + """ + return cast( + ReportRun, + self._requestor.request( + "post", + "/v1/reporting/report_runs", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + report_run: str, + params: "ReportRunService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> ReportRun: + """ + Retrieves the details of an existing Report Run. + """ + return cast( + ReportRun, + self._requestor.request( + "get", + "/v1/reporting/report_runs/{report_run}".format( + report_run=_util.sanitize_id(report_run), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/reporting/_report_type.py b/stripe/reporting/_report_type.py index bfb4ee2da..3fa5375fe 100644 --- a/stripe/reporting/_report_type.py +++ b/stripe/reporting/_report_type.py @@ -74,13 +74,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ReportType.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ReportType.ListParams"] ) -> ListObject["ReportType"]: """ Returns a full list of Report Types. @@ -88,9 +82,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/reporting/_report_type_service.py b/stripe/reporting/_report_type_service.py new file mode 100644 index 000000000..9446f45c5 --- /dev/null +++ b/stripe/reporting/_report_type_service.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.reporting._report_type import ReportType +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class ReportTypeService(StripeService): + class ListParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "ReportTypeService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[ReportType]: + """ + Returns a full list of Report Types. + """ + return cast( + ListObject[ReportType], + self._requestor.request( + "get", + "/v1/reporting/report_types", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + report_type: str, + params: "ReportTypeService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> ReportType: + """ + Retrieves the details of a Report Type. (Certain report types require a [live-mode API key](https://stripe.com/docs/keys#test-live-modes).) + """ + return cast( + ReportType, + self._requestor.request( + "get", + "/v1/reporting/report_types/{report_type}".format( + report_type=_util.sanitize_id(report_type), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/sigma/__init__.py b/stripe/sigma/__init__.py index 1ee9e996c..def6c586d 100644 --- a/stripe/sigma/__init__.py +++ b/stripe/sigma/__init__.py @@ -3,3 +3,6 @@ from stripe.sigma._scheduled_query_run import ( ScheduledQueryRun as ScheduledQueryRun, ) +from stripe.sigma._scheduled_query_run_service import ( + ScheduledQueryRunService as ScheduledQueryRunService, +) diff --git a/stripe/sigma/_scheduled_query_run.py b/stripe/sigma/_scheduled_query_run.py index 8416c2da0..a31c701a6 100644 --- a/stripe/sigma/_scheduled_query_run.py +++ b/stripe/sigma/_scheduled_query_run.py @@ -97,13 +97,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ScheduledQueryRun.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ScheduledQueryRun.ListParams"] ) -> ListObject["ScheduledQueryRun"]: """ Returns a list of scheduled query runs. @@ -111,9 +105,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/sigma/_scheduled_query_run_service.py b/stripe/sigma/_scheduled_query_run_service.py new file mode 100644 index 000000000..787135111 --- /dev/null +++ b/stripe/sigma/_scheduled_query_run_service.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.sigma._scheduled_query_run import ScheduledQueryRun +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class ScheduledQueryRunService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "ScheduledQueryRunService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[ScheduledQueryRun]: + """ + Returns a list of scheduled query runs. + """ + return cast( + ListObject[ScheduledQueryRun], + self._requestor.request( + "get", + "/v1/sigma/scheduled_query_runs", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + scheduled_query_run: str, + params: "ScheduledQueryRunService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> ScheduledQueryRun: + """ + Retrieves the details of an scheduled query run. + """ + return cast( + ScheduledQueryRun, + self._requestor.request( + "get", + "/v1/sigma/scheduled_query_runs/{scheduled_query_run}".format( + scheduled_query_run=_util.sanitize_id(scheduled_query_run), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/tax/__init__.py b/stripe/tax/__init__.py index d292171ed..4328458b6 100644 --- a/stripe/tax/__init__.py +++ b/stripe/tax/__init__.py @@ -4,9 +4,25 @@ from stripe.tax._calculation_line_item import ( CalculationLineItem as CalculationLineItem, ) +from stripe.tax._calculation_line_item_service import ( + CalculationLineItemService as CalculationLineItemService, +) +from stripe.tax._calculation_service import ( + CalculationService as CalculationService, +) from stripe.tax._registration import Registration as Registration +from stripe.tax._registration_service import ( + RegistrationService as RegistrationService, +) from stripe.tax._settings import Settings as Settings +from stripe.tax._settings_service import SettingsService as SettingsService from stripe.tax._transaction import Transaction as Transaction from stripe.tax._transaction_line_item import ( TransactionLineItem as TransactionLineItem, ) +from stripe.tax._transaction_line_item_service import ( + TransactionLineItemService as TransactionLineItemService, +) +from stripe.tax._transaction_service import ( + TransactionService as TransactionService, +) diff --git a/stripe/tax/_calculation.py b/stripe/tax/_calculation.py index 32dec80a4..ac403a2f1 100644 --- a/stripe/tax/_calculation.py +++ b/stripe/tax/_calculation.py @@ -622,14 +622,7 @@ class ListLineItemsParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Calculation.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Calculation.CreateParams"] ) -> "Calculation": """ Calculates tax based on input and returns a Tax Calculation object. @@ -639,10 +632,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -651,12 +640,7 @@ def create( def _cls_list_line_items( cls, calculation: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Calculation.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Calculation.ListLineItemsParams"] ) -> ListObject["CalculationLineItem"]: """ Retrieves the line items of a persisted tax calculation as a collection. @@ -668,9 +652,6 @@ def _cls_list_line_items( "/v1/tax/calculations/{calculation}/line_items".format( calculation=_util.sanitize_id(calculation) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -678,13 +659,7 @@ def _cls_list_line_items( @overload @staticmethod def list_line_items( - calculation: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Calculation.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + calculation: str, **params: Unpack["Calculation.ListLineItemsParams"] ) -> ListObject["CalculationLineItem"]: """ Retrieves the line items of a persisted tax calculation as a collection. @@ -693,11 +668,7 @@ def list_line_items( @overload def list_line_items( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Calculation.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Calculation.ListLineItemsParams"] ) -> ListObject["CalculationLineItem"]: """ Retrieves the line items of a persisted tax calculation as a collection. @@ -706,11 +677,7 @@ def list_line_items( @class_method_variant("_cls_list_line_items") def list_line_items( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Calculation.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Calculation.ListLineItemsParams"] ) -> ListObject["CalculationLineItem"]: """ Retrieves the line items of a persisted tax calculation as a collection. @@ -722,7 +689,6 @@ def list_line_items( # pyright: ignore[reportGeneralTypeIssues] "/v1/tax/calculations/{calculation}/line_items".format( calculation=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/tax/_calculation_line_item_service.py b/stripe/tax/_calculation_line_item_service.py new file mode 100644 index 000000000..343771849 --- /dev/null +++ b/stripe/tax/_calculation_line_item_service.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.tax._calculation_line_item import CalculationLineItem +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class CalculationLineItemService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + def list( + self, + calculation: str, + params: "CalculationLineItemService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[CalculationLineItem]: + """ + Retrieves the line items of a persisted tax calculation as a collection. + """ + return cast( + ListObject[CalculationLineItem], + self._requestor.request( + "get", + "/v1/tax/calculations/{calculation}/line_items".format( + calculation=_util.sanitize_id(calculation), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/tax/_calculation_service.py b/stripe/tax/_calculation_service.py new file mode 100644 index 000000000..e7cfcb2cb --- /dev/null +++ b/stripe/tax/_calculation_service.py @@ -0,0 +1,245 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.tax._calculation import Calculation +from stripe.tax._calculation_line_item_service import ( + CalculationLineItemService, +) +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CalculationService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.line_items = CalculationLineItemService(self._requestor) + + class CreateParams(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + customer: NotRequired["str"] + """ + The ID of an existing customer to use for this calculation. If provided, the customer's address and tax IDs are copied to `customer_details`. + """ + customer_details: NotRequired[ + "CalculationService.CreateParamsCustomerDetails" + ] + """ + Details about the customer, including address and tax IDs. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + line_items: List["CalculationService.CreateParamsLineItem"] + """ + A list of items the customer is purchasing. + """ + shipping_cost: NotRequired[ + "CalculationService.CreateParamsShippingCost" + ] + """ + Shipping cost details to be used for the calculation. + """ + tax_date: NotRequired["int"] + """ + Timestamp of date at which the tax rules and rates in effect applies for the calculation. Measured in seconds since the Unix epoch. Can be up to 48 hours in the past, and up to 48 hours in the future. + """ + + class CreateParamsCustomerDetails(TypedDict): + address: NotRequired[ + "CalculationService.CreateParamsCustomerDetailsAddress" + ] + """ + The customer's postal address (for example, home or business location). + """ + address_source: NotRequired["Literal['billing', 'shipping']"] + """ + The type of customer address provided. + """ + ip_address: NotRequired["str"] + """ + The customer's IP address (IPv4 or IPv6). + """ + tax_ids: NotRequired[ + "List[CalculationService.CreateParamsCustomerDetailsTaxId]" + ] + """ + The customer's tax IDs. Stripe Tax might consider a transaction with applicable tax IDs to be B2B, which might affect the tax calculation result. Stripe Tax doesn't validate tax IDs for correctness. + """ + taxability_override: NotRequired[ + "Literal['customer_exempt', 'none', 'reverse_charge']" + ] + """ + Overrides the tax calculation result to allow you to not collect tax from your customer. Use this if you've manually checked your customer's tax exemptions. Prefer providing the customer's `tax_ids` where possible, which automatically determines whether `reverse_charge` applies. + """ + + class CreateParamsCustomerDetailsAddress(TypedDict): + city: NotRequired["Literal['']|str"] + """ + City, district, suburb, town, or village. + """ + country: str + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["Literal['']|str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["Literal['']|str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["Literal['']|str"] + """ + ZIP or postal code. + """ + state: NotRequired["Literal['']|str"] + """ + State, county, province, or region. We recommend sending [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) subdivision code value when possible. + """ + + class CreateParamsCustomerDetailsTaxId(TypedDict): + type: Literal[ + "ad_nrt", + "ae_trn", + "ar_cuit", + "au_abn", + "au_arn", + "bg_uic", + "bo_tin", + "br_cnpj", + "br_cpf", + "ca_bn", + "ca_gst_hst", + "ca_pst_bc", + "ca_pst_mb", + "ca_pst_sk", + "ca_qst", + "ch_vat", + "cl_tin", + "cn_tin", + "co_nit", + "cr_tin", + "do_rcn", + "ec_ruc", + "eg_tin", + "es_cif", + "eu_oss_vat", + "eu_vat", + "gb_vat", + "ge_vat", + "hk_br", + "hu_tin", + "id_npwp", + "il_vat", + "in_gst", + "is_vat", + "jp_cn", + "jp_rn", + "jp_trn", + "ke_pin", + "kr_brn", + "li_uid", + "mx_rfc", + "my_frp", + "my_itn", + "my_sst", + "no_vat", + "nz_gst", + "pe_ruc", + "ph_tin", + "ro_tin", + "rs_pib", + "ru_inn", + "ru_kpp", + "sa_vat", + "sg_gst", + "sg_uen", + "si_tin", + "sv_nit", + "th_vat", + "tr_tin", + "tw_vat", + "ua_vat", + "us_ein", + "uy_ruc", + "ve_rif", + "vn_tin", + "za_vat", + ] + """ + Type of the tax ID, one of `ad_nrt`, `ae_trn`, `ar_cuit`, `au_abn`, `au_arn`, `bg_uic`, `bo_tin`, `br_cnpj`, `br_cpf`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `ca_qst`, `ch_vat`, `cl_tin`, `cn_tin`, `co_nit`, `cr_tin`, `do_rcn`, `ec_ruc`, `eg_tin`, `es_cif`, `eu_oss_vat`, `eu_vat`, `gb_vat`, `ge_vat`, `hk_br`, `hu_tin`, `id_npwp`, `il_vat`, `in_gst`, `is_vat`, `jp_cn`, `jp_rn`, `jp_trn`, `ke_pin`, `kr_brn`, `li_uid`, `mx_rfc`, `my_frp`, `my_itn`, `my_sst`, `no_vat`, `nz_gst`, `pe_ruc`, `ph_tin`, `ro_tin`, `rs_pib`, `ru_inn`, `ru_kpp`, `sa_vat`, `sg_gst`, `sg_uen`, `si_tin`, `sv_nit`, `th_vat`, `tr_tin`, `tw_vat`, `ua_vat`, `us_ein`, `uy_ruc`, `ve_rif`, `vn_tin`, or `za_vat` + """ + value: str + """ + Value of the tax ID. + """ + + class CreateParamsLineItem(TypedDict): + amount: int + """ + A positive integer in cents representing the line item's total price. If `tax_behavior=inclusive`, then this amount includes taxes. Otherwise, taxes are calculated on top of this amount. + """ + product: NotRequired["str"] + """ + If provided, the product's `tax_code` will be used as the line item's `tax_code`. + """ + quantity: NotRequired["int"] + """ + The number of units of the item being purchased. Used to calculate the per-unit price from the total `amount` for the line. For example, if `amount=100` and `quantity=4`, the calculated unit price is 25. + """ + reference: NotRequired["str"] + """ + A custom identifier for this line item, which must be unique across the line items in the calculation. The reference helps identify each line item in exported [tax reports](https://stripe.com/docs/tax/reports). + """ + tax_behavior: NotRequired["Literal['exclusive', 'inclusive']"] + """ + Specifies whether the `amount` includes taxes. Defaults to `exclusive`. + """ + tax_code: NotRequired["str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID to use for this line item. If not provided, we will use the tax code from the provided `product` param. If neither `tax_code` nor `product` is provided, we will use the default tax code from your Tax Settings. + """ + + class CreateParamsShippingCost(TypedDict): + amount: NotRequired["int"] + """ + A positive integer in cents representing the shipping charge. If `tax_behavior=inclusive`, then this amount includes taxes. Otherwise, taxes are calculated on top of this amount. + """ + shipping_rate: NotRequired["str"] + """ + If provided, the [shipping rate](https://stripe.com/docs/api/shipping_rates/object)'s `amount`, `tax_code` and `tax_behavior` are used. If you provide a shipping rate, then you cannot pass the `amount`, `tax_code`, or `tax_behavior` parameters. + """ + tax_behavior: NotRequired["Literal['exclusive', 'inclusive']"] + """ + Specifies whether the `amount` includes taxes. If `tax_behavior=inclusive`, then the amount includes taxes. Defaults to `exclusive`. + """ + tax_code: NotRequired["str"] + """ + The [tax code](https://stripe.com/docs/tax/tax-categories) used to calculate tax on shipping. If not provided, the default shipping tax code from your [Tax Settings](https://stripe.com/settings/tax) is used. + """ + + def create( + self, + params: "CalculationService.CreateParams", + options: RequestOptions = {}, + ) -> Calculation: + """ + Calculates tax based on input and returns a Tax Calculation object. + """ + return cast( + Calculation, + self._requestor.request( + "post", + "/v1/tax/calculations", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/tax/_registration.py b/stripe/tax/_registration.py index 4deec2682..208303771 100644 --- a/stripe/tax/_registration.py +++ b/stripe/tax/_registration.py @@ -1636,14 +1636,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Registration.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Registration.CreateParams"] ) -> "Registration": """ Creates a new Tax Registration object. @@ -1653,23 +1646,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Registration.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Registration.ListParams"] ) -> ListObject["Registration"]: """ Returns a list of Tax Registration objects. @@ -1677,9 +1660,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/tax/_registration_service.py b/stripe/tax/_registration_service.py new file mode 100644 index 000000000..ff939d779 --- /dev/null +++ b/stripe/tax/_registration_service.py @@ -0,0 +1,1025 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.tax._registration import Registration +from typing import List, Union, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class RegistrationService(StripeService): + class CreateParams(TypedDict): + active_from: Union[Literal["now"], int] + """ + Time at which the Tax Registration becomes active. It can be either `now` to indicate the current time, or a future timestamp measured in seconds since the Unix epoch. + """ + country: str + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + country_options: "RegistrationService.CreateParamsCountryOptions" + """ + Specific options for a registration in the specified `country`. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + expires_at: NotRequired["int"] + """ + If set, the Tax Registration stops being active at this time. If not set, the Tax Registration will be active indefinitely. Timestamp measured in seconds since the Unix epoch. + """ + + _CreateParamsCountryOptionsBase = TypedDict( + "CreateParamsCountryOptions", + { + "is": NotRequired[ + "RegistrationService.CreateParamsCountryOptionsIs" + ] + }, + ) + + class CreateParamsCountryOptions(_CreateParamsCountryOptionsBase): + ae: NotRequired["RegistrationService.CreateParamsCountryOptionsAe"] + """ + Options for the registration in AE. + """ + at: NotRequired["RegistrationService.CreateParamsCountryOptionsAt"] + """ + Options for the registration in AT. + """ + au: NotRequired["RegistrationService.CreateParamsCountryOptionsAu"] + """ + Options for the registration in AU. + """ + be: NotRequired["RegistrationService.CreateParamsCountryOptionsBe"] + """ + Options for the registration in BE. + """ + bg: NotRequired["RegistrationService.CreateParamsCountryOptionsBg"] + """ + Options for the registration in BG. + """ + ca: NotRequired["RegistrationService.CreateParamsCountryOptionsCa"] + """ + Options for the registration in CA. + """ + ch: NotRequired["RegistrationService.CreateParamsCountryOptionsCh"] + """ + Options for the registration in CH. + """ + cl: NotRequired["RegistrationService.CreateParamsCountryOptionsCl"] + """ + Options for the registration in CL. + """ + co: NotRequired["RegistrationService.CreateParamsCountryOptionsCo"] + """ + Options for the registration in CO. + """ + cy: NotRequired["RegistrationService.CreateParamsCountryOptionsCy"] + """ + Options for the registration in CY. + """ + cz: NotRequired["RegistrationService.CreateParamsCountryOptionsCz"] + """ + Options for the registration in CZ. + """ + de: NotRequired["RegistrationService.CreateParamsCountryOptionsDe"] + """ + Options for the registration in DE. + """ + dk: NotRequired["RegistrationService.CreateParamsCountryOptionsDk"] + """ + Options for the registration in DK. + """ + ee: NotRequired["RegistrationService.CreateParamsCountryOptionsEe"] + """ + Options for the registration in EE. + """ + es: NotRequired["RegistrationService.CreateParamsCountryOptionsEs"] + """ + Options for the registration in ES. + """ + fi: NotRequired["RegistrationService.CreateParamsCountryOptionsFi"] + """ + Options for the registration in FI. + """ + fr: NotRequired["RegistrationService.CreateParamsCountryOptionsFr"] + """ + Options for the registration in FR. + """ + gb: NotRequired["RegistrationService.CreateParamsCountryOptionsGb"] + """ + Options for the registration in GB. + """ + gr: NotRequired["RegistrationService.CreateParamsCountryOptionsGr"] + """ + Options for the registration in GR. + """ + hr: NotRequired["RegistrationService.CreateParamsCountryOptionsHr"] + """ + Options for the registration in HR. + """ + hu: NotRequired["RegistrationService.CreateParamsCountryOptionsHu"] + """ + Options for the registration in HU. + """ + id: NotRequired["RegistrationService.CreateParamsCountryOptionsId"] + """ + Options for the registration in ID. + """ + ie: NotRequired["RegistrationService.CreateParamsCountryOptionsIe"] + """ + Options for the registration in IE. + """ + it: NotRequired["RegistrationService.CreateParamsCountryOptionsIt"] + """ + Options for the registration in IT. + """ + jp: NotRequired["RegistrationService.CreateParamsCountryOptionsJp"] + """ + Options for the registration in JP. + """ + kr: NotRequired["RegistrationService.CreateParamsCountryOptionsKr"] + """ + Options for the registration in KR. + """ + lt: NotRequired["RegistrationService.CreateParamsCountryOptionsLt"] + """ + Options for the registration in LT. + """ + lu: NotRequired["RegistrationService.CreateParamsCountryOptionsLu"] + """ + Options for the registration in LU. + """ + lv: NotRequired["RegistrationService.CreateParamsCountryOptionsLv"] + """ + Options for the registration in LV. + """ + mt: NotRequired["RegistrationService.CreateParamsCountryOptionsMt"] + """ + Options for the registration in MT. + """ + mx: NotRequired["RegistrationService.CreateParamsCountryOptionsMx"] + """ + Options for the registration in MX. + """ + my: NotRequired["RegistrationService.CreateParamsCountryOptionsMy"] + """ + Options for the registration in MY. + """ + nl: NotRequired["RegistrationService.CreateParamsCountryOptionsNl"] + """ + Options for the registration in NL. + """ + no: NotRequired["RegistrationService.CreateParamsCountryOptionsNo"] + """ + Options for the registration in NO. + """ + nz: NotRequired["RegistrationService.CreateParamsCountryOptionsNz"] + """ + Options for the registration in NZ. + """ + pl: NotRequired["RegistrationService.CreateParamsCountryOptionsPl"] + """ + Options for the registration in PL. + """ + pt: NotRequired["RegistrationService.CreateParamsCountryOptionsPt"] + """ + Options for the registration in PT. + """ + ro: NotRequired["RegistrationService.CreateParamsCountryOptionsRo"] + """ + Options for the registration in RO. + """ + sa: NotRequired["RegistrationService.CreateParamsCountryOptionsSa"] + """ + Options for the registration in SA. + """ + se: NotRequired["RegistrationService.CreateParamsCountryOptionsSe"] + """ + Options for the registration in SE. + """ + sg: NotRequired["RegistrationService.CreateParamsCountryOptionsSg"] + """ + Options for the registration in SG. + """ + si: NotRequired["RegistrationService.CreateParamsCountryOptionsSi"] + """ + Options for the registration in SI. + """ + sk: NotRequired["RegistrationService.CreateParamsCountryOptionsSk"] + """ + Options for the registration in SK. + """ + th: NotRequired["RegistrationService.CreateParamsCountryOptionsTh"] + """ + Options for the registration in TH. + """ + tr: NotRequired["RegistrationService.CreateParamsCountryOptionsTr"] + """ + Options for the registration in TR. + """ + us: NotRequired["RegistrationService.CreateParamsCountryOptionsUs"] + """ + Options for the registration in US. + """ + vn: NotRequired["RegistrationService.CreateParamsCountryOptionsVn"] + """ + Options for the registration in VN. + """ + za: NotRequired["RegistrationService.CreateParamsCountryOptionsZa"] + """ + Options for the registration in ZA. + """ + + class CreateParamsCountryOptionsAe(TypedDict): + type: Literal["standard"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsAt(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsAtStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsAtStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsAu(TypedDict): + type: Literal["standard"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsBe(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsBeStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsBeStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsBg(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsBgStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsBgStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsCa(TypedDict): + province_standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsCaProvinceStandard" + ] + """ + Options for the provincial tax registration. + """ + type: Literal["province_standard", "simplified", "standard"] + """ + Type of registration to be created in Canada. + """ + + class CreateParamsCountryOptionsCaProvinceStandard(TypedDict): + province: str + """ + Two-letter CA province code ([ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2)). + """ + + class CreateParamsCountryOptionsCh(TypedDict): + type: Literal["standard"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsCl(TypedDict): + type: Literal["simplified"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsCo(TypedDict): + type: Literal["simplified"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsCy(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsCyStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsCyStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsCz(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsCzStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsCzStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsDe(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsDeStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsDeStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsDk(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsDkStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsDkStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsEe(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsEeStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsEeStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsEs(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsEsStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsEsStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsFi(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsFiStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsFiStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsFr(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsFrStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsFrStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsGb(TypedDict): + type: Literal["standard"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsGr(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsGrStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsGrStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsHr(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsHrStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsHrStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsHu(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsHuStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsHuStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsId(TypedDict): + type: Literal["simplified"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsIe(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsIeStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsIeStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsIs(TypedDict): + type: Literal["standard"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsIt(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsItStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsItStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsJp(TypedDict): + type: Literal["standard"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsKr(TypedDict): + type: Literal["simplified"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsLt(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsLtStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsLtStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsLu(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsLuStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsLuStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsLv(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsLvStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsLvStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsMt(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsMtStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsMtStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsMx(TypedDict): + type: Literal["simplified"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsMy(TypedDict): + type: Literal["simplified"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsNl(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsNlStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsNlStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsNo(TypedDict): + type: Literal["standard"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsNz(TypedDict): + type: Literal["standard"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsPl(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsPlStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsPlStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsPt(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsPtStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsPtStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsRo(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsRoStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsRoStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsSa(TypedDict): + type: Literal["simplified"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsSe(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsSeStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsSeStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsSg(TypedDict): + type: Literal["standard"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsSi(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsSiStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsSiStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsSk(TypedDict): + standard: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsSkStandard" + ] + """ + Options for the standard registration. + """ + type: Literal["ioss", "oss_non_union", "oss_union", "standard"] + """ + Type of registration to be created in an EU country. + """ + + class CreateParamsCountryOptionsSkStandard(TypedDict): + place_of_supply_scheme: Literal["small_seller", "standard"] + """ + Place of supply scheme used in an EU standard registration. + """ + + class CreateParamsCountryOptionsTh(TypedDict): + type: Literal["simplified"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsTr(TypedDict): + type: Literal["simplified"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsUs(TypedDict): + local_amusement_tax: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsUsLocalAmusementTax" + ] + """ + Options for the local amusement tax registration. + """ + local_lease_tax: NotRequired[ + "RegistrationService.CreateParamsCountryOptionsUsLocalLeaseTax" + ] + """ + Options for the local lease tax registration. + """ + state: str + """ + Two-letter US state code ([ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2)). + """ + type: Literal[ + "local_amusement_tax", + "local_lease_tax", + "state_communications_tax", + "state_sales_tax", + ] + """ + Type of registration to be created in the US. + """ + + class CreateParamsCountryOptionsUsLocalAmusementTax(TypedDict): + jurisdiction: str + """ + A [FIPS code](https://www.census.gov/library/reference/code-lists/ansi.html) representing the local jurisdiction. Supported FIPS codes are: `14000` (Chicago), `06613` (Bloomington), `21696` (East Dundee), `24582` (Evanston), and `68081` (Schiller Park). + """ + + class CreateParamsCountryOptionsUsLocalLeaseTax(TypedDict): + jurisdiction: str + """ + A [FIPS code](https://www.census.gov/library/reference/code-lists/ansi.html) representing the local jurisdiction. Supported FIPS codes are: `14000` (Chicago). + """ + + class CreateParamsCountryOptionsVn(TypedDict): + type: Literal["simplified"] + """ + Type of registration to be created in `country`. + """ + + class CreateParamsCountryOptionsZa(TypedDict): + type: Literal["standard"] + """ + Type of registration to be created in `country`. + """ + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired["Literal['active', 'all', 'expired', 'scheduled']"] + """ + The status of the Tax Registration. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + active_from: NotRequired["Literal['now']|int"] + """ + Time at which the registration becomes active. It can be either `now` to indicate the current time, or a timestamp measured in seconds since the Unix epoch. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + expires_at: NotRequired["Literal['']|Literal['now']|int"] + """ + If set, the registration stops being active at this time. If not set, the registration will be active indefinitely. It can be either `now` to indicate the current time, or a timestamp measured in seconds since the Unix epoch. + """ + + def list( + self, + params: "RegistrationService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Registration]: + """ + Returns a list of Tax Registration objects. + """ + return cast( + ListObject[Registration], + self._requestor.request( + "get", + "/v1/tax/registrations", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "RegistrationService.CreateParams", + options: RequestOptions = {}, + ) -> Registration: + """ + Creates a new Tax Registration object. + """ + return cast( + Registration, + self._requestor.request( + "post", + "/v1/tax/registrations", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + id: str, + params: "RegistrationService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Registration: + """ + Returns a Tax Registration object. + """ + return cast( + Registration, + self._requestor.request( + "get", + "/v1/tax/registrations/{id}".format(id=_util.sanitize_id(id)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + id: str, + params: "RegistrationService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Registration: + """ + Updates an existing Tax Registration object. + + A registration cannot be deleted after it has been created. If you wish to end a registration you may do so by setting expires_at. + """ + return cast( + Registration, + self._requestor.request( + "post", + "/v1/tax/registrations/{id}".format(id=_util.sanitize_id(id)), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/tax/_settings_service.py b/stripe/tax/_settings_service.py new file mode 100644 index 000000000..a79e14f6f --- /dev/null +++ b/stripe/tax/_settings_service.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.tax._settings import Settings +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class SettingsService(StripeService): + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + defaults: NotRequired["SettingsService.UpdateParamsDefaults"] + """ + Default configuration to be used on Stripe Tax calculations. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + head_office: NotRequired["SettingsService.UpdateParamsHeadOffice"] + """ + The place where your business is located. + """ + + class UpdateParamsDefaults(TypedDict): + tax_behavior: NotRequired[ + "Literal['exclusive', 'inclusive', 'inferred_by_currency']" + ] + """ + Specifies the default [tax behavior](https://stripe.com/docs/tax/products-prices-tax-categories-tax-behavior#tax-behavior) to be used when the item's price has unspecified tax behavior. One of inclusive, exclusive, or inferred_by_currency. Once specified, it cannot be changed back to null. + """ + tax_code: NotRequired["str"] + """ + A [tax code](https://stripe.com/docs/tax/tax-categories) ID. + """ + + class UpdateParamsHeadOffice(TypedDict): + address: "SettingsService.UpdateParamsHeadOfficeAddress" + """ + The location of the business for tax purposes. + """ + + class UpdateParamsHeadOfficeAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State/province as an [ISO 3166-2](https://en.wikipedia.org/wiki/ISO_3166-2) subdivision code, without country prefix. Example: "NY" or "TX". + """ + + def retrieve( + self, + params: "SettingsService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Settings: + """ + Retrieves Tax Settings for a merchant. + """ + return cast( + Settings, + self._requestor.request( + "get", + "/v1/tax/settings", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + params: "SettingsService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Settings: + """ + Updates Tax Settings parameters used in tax calculations. All parameters are editable but none can be removed once set. + """ + return cast( + Settings, + self._requestor.request( + "post", + "/v1/tax/settings", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/tax/_transaction.py b/stripe/tax/_transaction.py index ffe83ae6d..c69fa69ab 100644 --- a/stripe/tax/_transaction.py +++ b/stripe/tax/_transaction.py @@ -452,13 +452,7 @@ class RetrieveParams(RequestOptions): @classmethod def create_from_calculation( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transaction.CreateFromCalculationParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Transaction.CreateFromCalculationParams"] ) -> "Transaction": """ Creates a Tax Transaction from a calculation. @@ -468,22 +462,13 @@ def create_from_calculation( cls._static_request( "post", "/v1/tax/transactions/create_from_calculation", - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @classmethod def create_reversal( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transaction.CreateReversalParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Transaction.CreateReversalParams"] ) -> "Transaction": """ Partially or fully reverses a previously created Transaction. @@ -493,9 +478,6 @@ def create_reversal( cls._static_request( "post", "/v1/tax/transactions/create_reversal", - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -504,12 +486,7 @@ def create_reversal( def _cls_list_line_items( cls, transaction: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transaction.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Transaction.ListLineItemsParams"] ) -> ListObject["TransactionLineItem"]: """ Retrieves the line items of a committed standalone transaction as a collection. @@ -521,9 +498,6 @@ def _cls_list_line_items( "/v1/tax/transactions/{transaction}/line_items".format( transaction=_util.sanitize_id(transaction) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -531,13 +505,7 @@ def _cls_list_line_items( @overload @staticmethod def list_line_items( - transaction: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transaction.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + transaction: str, **params: Unpack["Transaction.ListLineItemsParams"] ) -> ListObject["TransactionLineItem"]: """ Retrieves the line items of a committed standalone transaction as a collection. @@ -546,11 +514,7 @@ def list_line_items( @overload def list_line_items( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Transaction.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Transaction.ListLineItemsParams"] ) -> ListObject["TransactionLineItem"]: """ Retrieves the line items of a committed standalone transaction as a collection. @@ -559,11 +523,7 @@ def list_line_items( @class_method_variant("_cls_list_line_items") def list_line_items( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Transaction.ListLineItemsParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Transaction.ListLineItemsParams"] ) -> ListObject["TransactionLineItem"]: """ Retrieves the line items of a committed standalone transaction as a collection. @@ -575,7 +535,6 @@ def list_line_items( # pyright: ignore[reportGeneralTypeIssues] "/v1/tax/transactions/{transaction}/line_items".format( transaction=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/tax/_transaction_line_item_service.py b/stripe/tax/_transaction_line_item_service.py new file mode 100644 index 000000000..a46c80dbf --- /dev/null +++ b/stripe/tax/_transaction_line_item_service.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.tax._transaction_line_item import TransactionLineItem +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class TransactionLineItemService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + def list( + self, + transaction: str, + params: "TransactionLineItemService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[TransactionLineItem]: + """ + Retrieves the line items of a committed standalone transaction as a collection. + """ + return cast( + ListObject[TransactionLineItem], + self._requestor.request( + "get", + "/v1/tax/transactions/{transaction}/line_items".format( + transaction=_util.sanitize_id(transaction), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/tax/_transaction_service.py b/stripe/tax/_transaction_service.py new file mode 100644 index 000000000..5ff77712f --- /dev/null +++ b/stripe/tax/_transaction_service.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.tax._transaction import Transaction +from stripe.tax._transaction_line_item_service import ( + TransactionLineItemService, +) +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class TransactionService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.line_items = TransactionLineItemService(self._requestor) + + class CreateFromCalculationParams(TypedDict): + calculation: str + """ + Tax Calculation ID to be used as input when creating the transaction. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + reference: str + """ + A custom order or sale identifier, such as 'myOrder_123'. Must be unique across all transactions, including reversals. + """ + + class CreateReversalParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + flat_amount: NotRequired["int"] + """ + A flat amount to reverse across the entire transaction, in negative integer cents. This value represents the total amount to refund from the transaction, including taxes. + """ + line_items: NotRequired[ + "List[TransactionService.CreateReversalParamsLineItem]" + ] + """ + The line item amounts to reverse. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + mode: Literal["full", "partial"] + """ + If `partial`, the provided line item or shipping cost amounts are reversed. If `full`, the original transaction is fully reversed. + """ + original_transaction: str + """ + The ID of the Transaction to partially or fully reverse. + """ + reference: str + """ + A custom identifier for this reversal, such as `myOrder_123-refund_1`, which must be unique across all transactions. The reference helps identify this reversal transaction in exported [tax reports](https://stripe.com/docs/tax/reports). + """ + shipping_cost: NotRequired[ + "TransactionService.CreateReversalParamsShippingCost" + ] + """ + The shipping cost to reverse. + """ + + class CreateReversalParamsLineItem(TypedDict): + amount: int + """ + The amount to reverse, in negative integer cents. + """ + amount_tax: int + """ + The amount of tax to reverse, in negative integer cents. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + """ + original_line_item: str + """ + The `id` of the line item to reverse in the original transaction. + """ + quantity: NotRequired["int"] + """ + The quantity reversed. Appears in [tax exports](https://stripe.com/docs/tax/reports), but does not affect the amount of tax reversed. + """ + reference: str + """ + A custom identifier for this line item in the reversal transaction, such as 'L1-refund'. + """ + + class CreateReversalParamsShippingCost(TypedDict): + amount: int + """ + The amount to reverse, in negative integer cents. + """ + amount_tax: int + """ + The amount of tax to reverse, in negative integer cents. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def retrieve( + self, + transaction: str, + params: "TransactionService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Transaction: + """ + Retrieves a Tax Transaction object. + """ + return cast( + Transaction, + self._requestor.request( + "get", + "/v1/tax/transactions/{transaction}".format( + transaction=_util.sanitize_id(transaction), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create_from_calculation( + self, + params: "TransactionService.CreateFromCalculationParams", + options: RequestOptions = {}, + ) -> Transaction: + """ + Creates a Tax Transaction from a calculation. + """ + return cast( + Transaction, + self._requestor.request( + "post", + "/v1/tax/transactions/create_from_calculation", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create_reversal( + self, + params: "TransactionService.CreateReversalParams", + options: RequestOptions = {}, + ) -> Transaction: + """ + Partially or fully reverses a previously created Transaction. + """ + return cast( + Transaction, + self._requestor.request( + "post", + "/v1/tax/transactions/create_reversal", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/terminal/__init__.py b/stripe/terminal/__init__.py index 2a22169f2..e4bff0712 100644 --- a/stripe/terminal/__init__.py +++ b/stripe/terminal/__init__.py @@ -1,8 +1,18 @@ # -*- coding: utf-8 -*- # File generated from our OpenAPI spec from stripe.terminal._configuration import Configuration as Configuration +from stripe.terminal._configuration_service import ( + ConfigurationService as ConfigurationService, +) from stripe.terminal._connection_token import ( ConnectionToken as ConnectionToken, ) +from stripe.terminal._connection_token_service import ( + ConnectionTokenService as ConnectionTokenService, +) from stripe.terminal._location import Location as Location +from stripe.terminal._location_service import ( + LocationService as LocationService, +) from stripe.terminal._reader import Reader as Reader +from stripe.terminal._reader_service import ReaderService as ReaderService diff --git a/stripe/terminal/_configuration.py b/stripe/terminal/_configuration.py index 55052211a..0dd910bfd 100644 --- a/stripe/terminal/_configuration.py +++ b/stripe/terminal/_configuration.py @@ -933,14 +933,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Configuration.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Configuration.CreateParams"] ) -> "Configuration": """ Creates a new Configuration object. @@ -950,10 +943,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -1005,13 +994,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Configuration.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Configuration.ListParams"] ) -> ListObject["Configuration"]: """ Returns a list of Configuration objects. @@ -1019,9 +1002,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/terminal/_configuration_service.py b/stripe/terminal/_configuration_service.py new file mode 100644 index 000000000..6442333c7 --- /dev/null +++ b/stripe/terminal/_configuration_service.py @@ -0,0 +1,755 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.terminal._configuration import Configuration +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ConfigurationService(StripeService): + class CreateParams(TypedDict): + bbpos_wisepos_e: NotRequired[ + "ConfigurationService.CreateParamsBbposWiseposE" + ] + """ + An object containing device type specific settings for BBPOS WisePOS E readers + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + offline: NotRequired[ + "Literal['']|ConfigurationService.CreateParamsOffline" + ] + """ + Configurations for collecting transactions offline. + """ + tipping: NotRequired[ + "Literal['']|ConfigurationService.CreateParamsTipping" + ] + """ + Tipping configurations for readers supporting on-reader tips + """ + verifone_p400: NotRequired[ + "ConfigurationService.CreateParamsVerifoneP400" + ] + """ + An object containing device type specific settings for Verifone P400 readers + """ + + class CreateParamsBbposWiseposE(TypedDict): + splashscreen: NotRequired["Literal['']|str"] + """ + A File ID representing an image you would like displayed on the reader. + """ + + class CreateParamsOffline(TypedDict): + enabled: bool + """ + Determines whether to allow transactions to be collected while reader is offline. Defaults to false. + """ + + class CreateParamsTipping(TypedDict): + aud: NotRequired["ConfigurationService.CreateParamsTippingAud"] + """ + Tipping configuration for AUD + """ + cad: NotRequired["ConfigurationService.CreateParamsTippingCad"] + """ + Tipping configuration for CAD + """ + chf: NotRequired["ConfigurationService.CreateParamsTippingChf"] + """ + Tipping configuration for CHF + """ + czk: NotRequired["ConfigurationService.CreateParamsTippingCzk"] + """ + Tipping configuration for CZK + """ + dkk: NotRequired["ConfigurationService.CreateParamsTippingDkk"] + """ + Tipping configuration for DKK + """ + eur: NotRequired["ConfigurationService.CreateParamsTippingEur"] + """ + Tipping configuration for EUR + """ + gbp: NotRequired["ConfigurationService.CreateParamsTippingGbp"] + """ + Tipping configuration for GBP + """ + hkd: NotRequired["ConfigurationService.CreateParamsTippingHkd"] + """ + Tipping configuration for HKD + """ + myr: NotRequired["ConfigurationService.CreateParamsTippingMyr"] + """ + Tipping configuration for MYR + """ + nok: NotRequired["ConfigurationService.CreateParamsTippingNok"] + """ + Tipping configuration for NOK + """ + nzd: NotRequired["ConfigurationService.CreateParamsTippingNzd"] + """ + Tipping configuration for NZD + """ + sek: NotRequired["ConfigurationService.CreateParamsTippingSek"] + """ + Tipping configuration for SEK + """ + sgd: NotRequired["ConfigurationService.CreateParamsTippingSgd"] + """ + Tipping configuration for SGD + """ + usd: NotRequired["ConfigurationService.CreateParamsTippingUsd"] + """ + Tipping configuration for USD + """ + + class CreateParamsTippingAud(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsTippingCad(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsTippingChf(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsTippingCzk(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsTippingDkk(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsTippingEur(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsTippingGbp(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsTippingHkd(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsTippingMyr(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsTippingNok(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsTippingNzd(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsTippingSek(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsTippingSgd(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsTippingUsd(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class CreateParamsVerifoneP400(TypedDict): + splashscreen: NotRequired["Literal['']|str"] + """ + A File ID representing an image you would like displayed on the reader. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + is_account_default: NotRequired["bool"] + """ + if present, only return the account default or non-default configurations. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + bbpos_wisepos_e: NotRequired[ + "Literal['']|ConfigurationService.UpdateParamsBbposWiseposE" + ] + """ + An object containing device type specific settings for BBPOS WisePOS E readers + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + offline: NotRequired[ + "Literal['']|ConfigurationService.UpdateParamsOffline" + ] + """ + Configurations for collecting transactions offline. + """ + tipping: NotRequired[ + "Literal['']|ConfigurationService.UpdateParamsTipping" + ] + """ + Tipping configurations for readers supporting on-reader tips + """ + verifone_p400: NotRequired[ + "Literal['']|ConfigurationService.UpdateParamsVerifoneP400" + ] + """ + An object containing device type specific settings for Verifone P400 readers + """ + + class UpdateParamsBbposWiseposE(TypedDict): + splashscreen: NotRequired["Literal['']|str"] + """ + A File ID representing an image you would like displayed on the reader. + """ + + class UpdateParamsOffline(TypedDict): + enabled: bool + """ + Determines whether to allow transactions to be collected while reader is offline. Defaults to false. + """ + + class UpdateParamsTipping(TypedDict): + aud: NotRequired["ConfigurationService.UpdateParamsTippingAud"] + """ + Tipping configuration for AUD + """ + cad: NotRequired["ConfigurationService.UpdateParamsTippingCad"] + """ + Tipping configuration for CAD + """ + chf: NotRequired["ConfigurationService.UpdateParamsTippingChf"] + """ + Tipping configuration for CHF + """ + czk: NotRequired["ConfigurationService.UpdateParamsTippingCzk"] + """ + Tipping configuration for CZK + """ + dkk: NotRequired["ConfigurationService.UpdateParamsTippingDkk"] + """ + Tipping configuration for DKK + """ + eur: NotRequired["ConfigurationService.UpdateParamsTippingEur"] + """ + Tipping configuration for EUR + """ + gbp: NotRequired["ConfigurationService.UpdateParamsTippingGbp"] + """ + Tipping configuration for GBP + """ + hkd: NotRequired["ConfigurationService.UpdateParamsTippingHkd"] + """ + Tipping configuration for HKD + """ + myr: NotRequired["ConfigurationService.UpdateParamsTippingMyr"] + """ + Tipping configuration for MYR + """ + nok: NotRequired["ConfigurationService.UpdateParamsTippingNok"] + """ + Tipping configuration for NOK + """ + nzd: NotRequired["ConfigurationService.UpdateParamsTippingNzd"] + """ + Tipping configuration for NZD + """ + sek: NotRequired["ConfigurationService.UpdateParamsTippingSek"] + """ + Tipping configuration for SEK + """ + sgd: NotRequired["ConfigurationService.UpdateParamsTippingSgd"] + """ + Tipping configuration for SGD + """ + usd: NotRequired["ConfigurationService.UpdateParamsTippingUsd"] + """ + Tipping configuration for USD + """ + + class UpdateParamsTippingAud(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsTippingCad(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsTippingChf(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsTippingCzk(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsTippingDkk(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsTippingEur(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsTippingGbp(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsTippingHkd(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsTippingMyr(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsTippingNok(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsTippingNzd(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsTippingSek(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsTippingSgd(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsTippingUsd(TypedDict): + fixed_amounts: NotRequired["List[int]"] + """ + Fixed amounts displayed when collecting a tip + """ + percentages: NotRequired["List[int]"] + """ + Percentages displayed when collecting a tip + """ + smart_tip_threshold: NotRequired["int"] + """ + Below this amount, fixed amounts will be displayed; above it, percentages will be displayed + """ + + class UpdateParamsVerifoneP400(TypedDict): + splashscreen: NotRequired["Literal['']|str"] + """ + A File ID representing an image you would like displayed on the reader. + """ + + def delete( + self, + configuration: str, + params: "ConfigurationService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> Configuration: + """ + Deletes a Configuration object. + """ + return cast( + Configuration, + self._requestor.request( + "delete", + "/v1/terminal/configurations/{configuration}".format( + configuration=_util.sanitize_id(configuration), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + configuration: str, + params: "ConfigurationService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Configuration: + """ + Retrieves a Configuration object. + """ + return cast( + Configuration, + self._requestor.request( + "get", + "/v1/terminal/configurations/{configuration}".format( + configuration=_util.sanitize_id(configuration), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + configuration: str, + params: "ConfigurationService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Configuration: + """ + Updates a new Configuration object. + """ + return cast( + Configuration, + self._requestor.request( + "post", + "/v1/terminal/configurations/{configuration}".format( + configuration=_util.sanitize_id(configuration), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "ConfigurationService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Configuration]: + """ + Returns a list of Configuration objects. + """ + return cast( + ListObject[Configuration], + self._requestor.request( + "get", + "/v1/terminal/configurations", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "ConfigurationService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> Configuration: + """ + Creates a new Configuration object. + """ + return cast( + Configuration, + self._requestor.request( + "post", + "/v1/terminal/configurations", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/terminal/_connection_token.py b/stripe/terminal/_connection_token.py index b6c1b52a2..c0bb03e48 100644 --- a/stripe/terminal/_connection_token.py +++ b/stripe/terminal/_connection_token.py @@ -42,14 +42,7 @@ class CreateParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ConnectionToken.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ConnectionToken.CreateParams"] ) -> "ConnectionToken": """ To connect to a reader the Stripe Terminal SDK needs to retrieve a short-lived connection token from Stripe, proxied through your server. On your backend, add an endpoint that creates and returns a connection token. @@ -59,10 +52,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) diff --git a/stripe/terminal/_connection_token_service.py b/stripe/terminal/_connection_token_service.py new file mode 100644 index 000000000..ca60c546a --- /dev/null +++ b/stripe/terminal/_connection_token_service.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.terminal._connection_token import ConnectionToken +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class ConnectionTokenService(StripeService): + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + location: NotRequired["str"] + """ + The id of the location that this connection token is scoped to. If specified the connection token will only be usable with readers assigned to that location, otherwise the connection token will be usable with all readers. Note that location scoping only applies to internet-connected readers. For more details, see [the docs on scoping connection tokens](https://stripe.com/docs/terminal/fleet/locations#connection-tokens). + """ + + def create( + self, + params: "ConnectionTokenService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> ConnectionToken: + """ + To connect to a reader the Stripe Terminal SDK needs to retrieve a short-lived connection token from Stripe, proxied through your server. On your backend, add an endpoint that creates and returns a connection token. + """ + return cast( + ConnectionToken, + self._requestor.request( + "post", + "/v1/terminal/connection_tokens", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/terminal/_location.py b/stripe/terminal/_location.py index db7e2abb8..186a53632 100644 --- a/stripe/terminal/_location.py +++ b/stripe/terminal/_location.py @@ -207,16 +207,7 @@ class RetrieveParams(RequestOptions): """ @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Location.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Location": + def create(cls, **params: Unpack["Location.CreateParams"]) -> "Location": """ Creates a new Location object. For further details, including which address fields are required in each country, see the [Manage locations](https://stripe.com/docs/terminal/fleet/locations) guide. @@ -226,10 +217,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -279,13 +266,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Location.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Location.ListParams"] ) -> ListObject["Location"]: """ Returns a list of Location objects. @@ -293,9 +274,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/terminal/_location_service.py b/stripe/terminal/_location_service.py new file mode 100644 index 000000000..2ca5e9af0 --- /dev/null +++ b/stripe/terminal/_location_service.py @@ -0,0 +1,244 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.terminal._location import Location +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class LocationService(StripeService): + class CreateParams(TypedDict): + address: "LocationService.CreateParamsAddress" + """ + The full address of the location. + """ + configuration_overrides: NotRequired["str"] + """ + The ID of a configuration that will be used to customize all readers in this location. + """ + display_name: str + """ + A name for the location. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class CreateParamsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: str + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + address: NotRequired["LocationService.UpdateParamsAddress"] + """ + The full address of the location. + """ + configuration_overrides: NotRequired["Literal['']|str"] + """ + The ID of a configuration that will be used to customize all readers in this location. + """ + display_name: NotRequired["str"] + """ + A name for the location. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + class UpdateParamsAddress(TypedDict): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + def delete( + self, + location: str, + params: "LocationService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> Location: + """ + Deletes a Location object. + """ + return cast( + Location, + self._requestor.request( + "delete", + "/v1/terminal/locations/{location}".format( + location=_util.sanitize_id(location), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + location: str, + params: "LocationService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Location: + """ + Retrieves a Location object. + """ + return cast( + Location, + self._requestor.request( + "get", + "/v1/terminal/locations/{location}".format( + location=_util.sanitize_id(location), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + location: str, + params: "LocationService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Location: + """ + Updates a Location object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + """ + return cast( + Location, + self._requestor.request( + "post", + "/v1/terminal/locations/{location}".format( + location=_util.sanitize_id(location), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "LocationService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Location]: + """ + Returns a list of Location objects. + """ + return cast( + ListObject[Location], + self._requestor.request( + "get", + "/v1/terminal/locations", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "LocationService.CreateParams", + options: RequestOptions = {}, + ) -> Location: + """ + Creates a new Location object. + For further details, including which address fields are required in each country, see the [Manage locations](https://stripe.com/docs/terminal/fleet/locations) guide. + """ + return cast( + Location, + self._requestor.request( + "post", + "/v1/terminal/locations", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/terminal/_reader.py b/stripe/terminal/_reader.py index 4802e8638..a79a524d4 100644 --- a/stripe/terminal/_reader.py +++ b/stripe/terminal/_reader.py @@ -535,14 +535,7 @@ class SetReaderDisplayParamsCartLineItem(TypedDict): @classmethod def _cls_cancel_action( - cls, - reader: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.CancelActionParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, reader: str, **params: Unpack["Reader.CancelActionParams"] ) -> "Reader": """ Cancels the current reader action. @@ -554,9 +547,6 @@ def _cls_cancel_action( "/v1/terminal/readers/{reader}/cancel_action".format( reader=_util.sanitize_id(reader) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -564,13 +554,7 @@ def _cls_cancel_action( @overload @staticmethod def cancel_action( - reader: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.CancelActionParams" - ] # pyright: ignore[reportGeneralTypeIssues] + reader: str, **params: Unpack["Reader.CancelActionParams"] ) -> "Reader": """ Cancels the current reader action. @@ -579,11 +563,7 @@ def cancel_action( @overload def cancel_action( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Reader.CancelActionParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Reader.CancelActionParams"] ) -> "Reader": """ Cancels the current reader action. @@ -592,11 +572,7 @@ def cancel_action( @class_method_variant("_cls_cancel_action") def cancel_action( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Reader.CancelActionParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Reader.CancelActionParams"] ) -> "Reader": """ Cancels the current reader action. @@ -608,22 +584,12 @@ def cancel_action( # pyright: ignore[reportGeneralTypeIssues] "/v1/terminal/readers/{reader}/cancel_action".format( reader=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "Reader": + def create(cls, **params: Unpack["Reader.CreateParams"]) -> "Reader": """ Creates a new Reader object. """ @@ -632,10 +598,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -683,13 +645,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Reader.ListParams"] ) -> ListObject["Reader"]: """ Returns a list of Reader objects. @@ -697,9 +653,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -726,14 +679,7 @@ def modify( @classmethod def _cls_process_payment_intent( - cls, - reader: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.ProcessPaymentIntentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, reader: str, **params: Unpack["Reader.ProcessPaymentIntentParams"] ) -> "Reader": """ Initiates a payment flow on a Reader. @@ -745,9 +691,6 @@ def _cls_process_payment_intent( "/v1/terminal/readers/{reader}/process_payment_intent".format( reader=_util.sanitize_id(reader) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -755,13 +698,7 @@ def _cls_process_payment_intent( @overload @staticmethod def process_payment_intent( - reader: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.ProcessPaymentIntentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + reader: str, **params: Unpack["Reader.ProcessPaymentIntentParams"] ) -> "Reader": """ Initiates a payment flow on a Reader. @@ -770,11 +707,7 @@ def process_payment_intent( @overload def process_payment_intent( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Reader.ProcessPaymentIntentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Reader.ProcessPaymentIntentParams"] ) -> "Reader": """ Initiates a payment flow on a Reader. @@ -783,11 +716,7 @@ def process_payment_intent( @class_method_variant("_cls_process_payment_intent") def process_payment_intent( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Reader.ProcessPaymentIntentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Reader.ProcessPaymentIntentParams"] ) -> "Reader": """ Initiates a payment flow on a Reader. @@ -799,21 +728,13 @@ def process_payment_intent( # pyright: ignore[reportGeneralTypeIssues] "/v1/terminal/readers/{reader}/process_payment_intent".format( reader=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_process_setup_intent( - cls, - reader: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.ProcessSetupIntentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, reader: str, **params: Unpack["Reader.ProcessSetupIntentParams"] ) -> "Reader": """ Initiates a setup intent flow on a Reader. @@ -825,9 +746,6 @@ def _cls_process_setup_intent( "/v1/terminal/readers/{reader}/process_setup_intent".format( reader=_util.sanitize_id(reader) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -835,13 +753,7 @@ def _cls_process_setup_intent( @overload @staticmethod def process_setup_intent( - reader: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.ProcessSetupIntentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + reader: str, **params: Unpack["Reader.ProcessSetupIntentParams"] ) -> "Reader": """ Initiates a setup intent flow on a Reader. @@ -850,11 +762,7 @@ def process_setup_intent( @overload def process_setup_intent( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Reader.ProcessSetupIntentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Reader.ProcessSetupIntentParams"] ) -> "Reader": """ Initiates a setup intent flow on a Reader. @@ -863,11 +771,7 @@ def process_setup_intent( @class_method_variant("_cls_process_setup_intent") def process_setup_intent( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Reader.ProcessSetupIntentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Reader.ProcessSetupIntentParams"] ) -> "Reader": """ Initiates a setup intent flow on a Reader. @@ -879,21 +783,13 @@ def process_setup_intent( # pyright: ignore[reportGeneralTypeIssues] "/v1/terminal/readers/{reader}/process_setup_intent".format( reader=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_refund_payment( - cls, - reader: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.RefundPaymentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, reader: str, **params: Unpack["Reader.RefundPaymentParams"] ) -> "Reader": """ Initiates a refund on a Reader @@ -905,9 +801,6 @@ def _cls_refund_payment( "/v1/terminal/readers/{reader}/refund_payment".format( reader=_util.sanitize_id(reader) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -915,13 +808,7 @@ def _cls_refund_payment( @overload @staticmethod def refund_payment( - reader: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.RefundPaymentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + reader: str, **params: Unpack["Reader.RefundPaymentParams"] ) -> "Reader": """ Initiates a refund on a Reader @@ -930,11 +817,7 @@ def refund_payment( @overload def refund_payment( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Reader.RefundPaymentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Reader.RefundPaymentParams"] ) -> "Reader": """ Initiates a refund on a Reader @@ -943,11 +826,7 @@ def refund_payment( @class_method_variant("_cls_refund_payment") def refund_payment( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Reader.RefundPaymentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Reader.RefundPaymentParams"] ) -> "Reader": """ Initiates a refund on a Reader @@ -959,7 +838,6 @@ def refund_payment( # pyright: ignore[reportGeneralTypeIssues] "/v1/terminal/readers/{reader}/refund_payment".format( reader=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -977,14 +855,7 @@ def retrieve( @classmethod def _cls_set_reader_display( - cls, - reader: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.SetReaderDisplayParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, reader: str, **params: Unpack["Reader.SetReaderDisplayParams"] ) -> "Reader": """ Sets reader display to show cart details. @@ -996,9 +867,6 @@ def _cls_set_reader_display( "/v1/terminal/readers/{reader}/set_reader_display".format( reader=_util.sanitize_id(reader) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1006,13 +874,7 @@ def _cls_set_reader_display( @overload @staticmethod def set_reader_display( - reader: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.SetReaderDisplayParams" - ] # pyright: ignore[reportGeneralTypeIssues] + reader: str, **params: Unpack["Reader.SetReaderDisplayParams"] ) -> "Reader": """ Sets reader display to show cart details. @@ -1021,11 +883,7 @@ def set_reader_display( @overload def set_reader_display( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Reader.SetReaderDisplayParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Reader.SetReaderDisplayParams"] ) -> "Reader": """ Sets reader display to show cart details. @@ -1034,11 +892,7 @@ def set_reader_display( @class_method_variant("_cls_set_reader_display") def set_reader_display( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Reader.SetReaderDisplayParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Reader.SetReaderDisplayParams"] ) -> "Reader": """ Sets reader display to show cart details. @@ -1050,7 +904,6 @@ def set_reader_display( # pyright: ignore[reportGeneralTypeIssues] "/v1/terminal/readers/{reader}/set_reader_display".format( reader=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -1062,12 +915,7 @@ class TestHelpers(APIResourceTestHelpers["Reader"]): def _cls_present_payment_method( cls, reader: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.PresentPaymentMethodParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["Reader.PresentPaymentMethodParams"] ) -> "Reader": """ Presents a payment method on a simulated reader. Can be used to simulate accepting a payment, saving a card or refunding a transaction. @@ -1079,9 +927,6 @@ def _cls_present_payment_method( "/v1/test_helpers/terminal/readers/{reader}/present_payment_method".format( reader=_util.sanitize_id(reader) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -1089,13 +934,7 @@ def _cls_present_payment_method( @overload @staticmethod def present_payment_method( - reader: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Reader.PresentPaymentMethodParams" - ] # pyright: ignore[reportGeneralTypeIssues] + reader: str, **params: Unpack["Reader.PresentPaymentMethodParams"] ) -> "Reader": """ Presents a payment method on a simulated reader. Can be used to simulate accepting a payment, saving a card or refunding a transaction. @@ -1104,11 +943,7 @@ def present_payment_method( @overload def present_payment_method( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Reader.PresentPaymentMethodParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Reader.PresentPaymentMethodParams"] ) -> "Reader": """ Presents a payment method on a simulated reader. Can be used to simulate accepting a payment, saving a card or refunding a transaction. @@ -1117,11 +952,7 @@ def present_payment_method( @class_method_variant("_cls_present_payment_method") def present_payment_method( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "Reader.PresentPaymentMethodParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["Reader.PresentPaymentMethodParams"] ) -> "Reader": """ Presents a payment method on a simulated reader. Can be used to simulate accepting a payment, saving a card or refunding a transaction. @@ -1133,7 +964,6 @@ def present_payment_method( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/terminal/readers/{reader}/present_payment_method".format( reader=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/terminal/_reader_service.py b/stripe/terminal/_reader_service.py new file mode 100644 index 000000000..17d937976 --- /dev/null +++ b/stripe/terminal/_reader_service.py @@ -0,0 +1,455 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.terminal._reader import Reader +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ReaderService(StripeService): + class CancelActionParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + label: NotRequired["str"] + """ + Custom label given to the reader for easier identification. If no label is specified, the registration code will be used. + """ + location: NotRequired["str"] + """ + The location to assign the reader to. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + registration_code: str + """ + A code generated by the reader used for registering to an account. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + device_type: NotRequired[ + "Literal['bbpos_chipper2x', 'bbpos_wisepad3', 'bbpos_wisepos_e', 'simulated_wisepos_e', 'stripe_m2', 'verifone_P400']" + ] + """ + Filters readers by device type + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + location: NotRequired["str"] + """ + A location ID to filter the response list to only readers at the specific location + """ + serial_number: NotRequired["str"] + """ + Filters readers by serial number + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired["Literal['offline', 'online']"] + """ + A status filter to filter readers to only offline or online readers + """ + + class ProcessPaymentIntentParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + payment_intent: str + """ + PaymentIntent ID + """ + process_config: NotRequired[ + "ReaderService.ProcessPaymentIntentParamsProcessConfig" + ] + """ + Configuration overrides + """ + + class ProcessPaymentIntentParamsProcessConfig(TypedDict): + skip_tipping: NotRequired["bool"] + """ + Override showing a tipping selection screen on this transaction. + """ + tipping: NotRequired[ + "ReaderService.ProcessPaymentIntentParamsProcessConfigTipping" + ] + """ + Tipping configuration for this transaction. + """ + + class ProcessPaymentIntentParamsProcessConfigTipping(TypedDict): + amount_eligible: NotRequired["int"] + """ + Amount used to calculate tip suggestions on tipping selection screen for this transaction. Must be a positive integer in the smallest currency unit (e.g., 100 cents to represent $1.00 or 100 to represent ¥100, a zero-decimal currency). + """ + + class ProcessSetupIntentParams(TypedDict): + customer_consent_collected: bool + """ + Customer Consent Collected + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + process_config: NotRequired[ + "ReaderService.ProcessSetupIntentParamsProcessConfig" + ] + """ + Configuration overrides + """ + setup_intent: str + """ + SetupIntent ID + """ + + class ProcessSetupIntentParamsProcessConfig(TypedDict): + pass + + class RefundPaymentParams(TypedDict): + amount: NotRequired["int"] + """ + A positive integer in __cents__ representing how much of this charge to refund. + """ + charge: NotRequired["str"] + """ + ID of the Charge to refund. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + payment_intent: NotRequired["str"] + """ + ID of the PaymentIntent to refund. + """ + refund_application_fee: NotRequired["bool"] + """ + Boolean indicating whether the application fee should be refunded when refunding this charge. If a full charge refund is given, the full application fee will be refunded. Otherwise, the application fee will be refunded in an amount proportional to the amount of the charge refunded. An application fee can be refunded only by the application that created the charge. + """ + reverse_transfer: NotRequired["bool"] + """ + Boolean indicating whether the transfer should be reversed when refunding this charge. The transfer will be reversed proportionally to the amount being refunded (either the entire or partial amount). A transfer can be reversed only by the application that created the charge. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class SetReaderDisplayParams(TypedDict): + cart: NotRequired["ReaderService.SetReaderDisplayParamsCart"] + """ + Cart + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + type: Literal["cart"] + """ + Type + """ + + class SetReaderDisplayParamsCart(TypedDict): + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + line_items: List["ReaderService.SetReaderDisplayParamsCartLineItem"] + """ + Array of line items that were purchased. + """ + tax: NotRequired["int"] + """ + The amount of tax in cents. + """ + total: int + """ + Total balance of cart due in cents. + """ + + class SetReaderDisplayParamsCartLineItem(TypedDict): + amount: int + """ + The price of the item in cents. + """ + description: str + """ + The description or name of the item. + """ + quantity: int + """ + The quantity of the line item being purchased. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + label: NotRequired["Literal['']|str"] + """ + The new label of the reader. + """ + metadata: NotRequired["Literal['']|Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + + def delete( + self, + reader: str, + params: "ReaderService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> Reader: + """ + Deletes a Reader object. + """ + return cast( + Reader, + self._requestor.request( + "delete", + "/v1/terminal/readers/{reader}".format( + reader=_util.sanitize_id(reader), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + reader: str, + params: "ReaderService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Reader: + """ + Retrieves a Reader object. + """ + return cast( + Reader, + self._requestor.request( + "get", + "/v1/terminal/readers/{reader}".format( + reader=_util.sanitize_id(reader), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + reader: str, + params: "ReaderService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> Reader: + """ + Updates a Reader object by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + """ + return cast( + Reader, + self._requestor.request( + "post", + "/v1/terminal/readers/{reader}".format( + reader=_util.sanitize_id(reader), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "ReaderService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[Reader]: + """ + Returns a list of Reader objects. + """ + return cast( + ListObject[Reader], + self._requestor.request( + "get", + "/v1/terminal/readers", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "ReaderService.CreateParams", + options: RequestOptions = {}, + ) -> Reader: + """ + Creates a new Reader object. + """ + return cast( + Reader, + self._requestor.request( + "post", + "/v1/terminal/readers", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def cancel_action( + self, + reader: str, + params: "ReaderService.CancelActionParams" = {}, + options: RequestOptions = {}, + ) -> Reader: + """ + Cancels the current reader action. + """ + return cast( + Reader, + self._requestor.request( + "post", + "/v1/terminal/readers/{reader}/cancel_action".format( + reader=_util.sanitize_id(reader), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def process_payment_intent( + self, + reader: str, + params: "ReaderService.ProcessPaymentIntentParams", + options: RequestOptions = {}, + ) -> Reader: + """ + Initiates a payment flow on a Reader. + """ + return cast( + Reader, + self._requestor.request( + "post", + "/v1/terminal/readers/{reader}/process_payment_intent".format( + reader=_util.sanitize_id(reader), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def process_setup_intent( + self, + reader: str, + params: "ReaderService.ProcessSetupIntentParams", + options: RequestOptions = {}, + ) -> Reader: + """ + Initiates a setup intent flow on a Reader. + """ + return cast( + Reader, + self._requestor.request( + "post", + "/v1/terminal/readers/{reader}/process_setup_intent".format( + reader=_util.sanitize_id(reader), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def refund_payment( + self, + reader: str, + params: "ReaderService.RefundPaymentParams" = {}, + options: RequestOptions = {}, + ) -> Reader: + """ + Initiates a refund on a Reader + """ + return cast( + Reader, + self._requestor.request( + "post", + "/v1/terminal/readers/{reader}/refund_payment".format( + reader=_util.sanitize_id(reader), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def set_reader_display( + self, + reader: str, + params: "ReaderService.SetReaderDisplayParams", + options: RequestOptions = {}, + ) -> Reader: + """ + Sets reader display to show cart details. + """ + return cast( + Reader, + self._requestor.request( + "post", + "/v1/terminal/readers/{reader}/set_reader_display".format( + reader=_util.sanitize_id(reader), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/test_helpers/__init__.py b/stripe/test_helpers/__init__.py index 9d57637d3..99f8cf0bc 100644 --- a/stripe/test_helpers/__init__.py +++ b/stripe/test_helpers/__init__.py @@ -1,3 +1,24 @@ # -*- coding: utf-8 -*- # File generated from our OpenAPI spec +from stripe.test_helpers import ( + issuing as issuing, + terminal as terminal, + treasury as treasury, +) +from stripe.test_helpers._customer_service import ( + CustomerService as CustomerService, +) +from stripe.test_helpers._issuing_service import ( + IssuingService as IssuingService, +) +from stripe.test_helpers._refund_service import RefundService as RefundService +from stripe.test_helpers._terminal_service import ( + TerminalService as TerminalService, +) from stripe.test_helpers._test_clock import TestClock as TestClock +from stripe.test_helpers._test_clock_service import ( + TestClockService as TestClockService, +) +from stripe.test_helpers._treasury_service import ( + TreasuryService as TreasuryService, +) diff --git a/stripe/test_helpers/_customer_service.py b/stripe/test_helpers/_customer_service.py new file mode 100644 index 000000000..fbf3e8e63 --- /dev/null +++ b/stripe/test_helpers/_customer_service.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._customer_cash_balance_transaction import ( + CustomerCashBalanceTransaction, +) +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class CustomerService(StripeService): + class FundCashBalanceParams(TypedDict): + amount: int + """ + Amount to be used for this test cash balance transaction. A positive integer representing how much to fund in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to fund $1.00 or 100 to fund ¥100, a zero-decimal currency). + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + reference: NotRequired["str"] + """ + A description of the test funding. This simulates free-text references supplied by customers when making bank transfers to their cash balance. You can use this to test how Stripe's [reconciliation algorithm](https://stripe.com/docs/payments/customer-balance/reconciliation) applies to different user inputs. + """ + + def fund_cash_balance( + self, + customer: str, + params: "CustomerService.FundCashBalanceParams", + options: RequestOptions = {}, + ) -> CustomerCashBalanceTransaction: + """ + Create an incoming testmode bank transfer + """ + return cast( + CustomerCashBalanceTransaction, + self._requestor.request( + "post", + "/v1/test_helpers/customers/{customer}/fund_cash_balance".format( + customer=_util.sanitize_id(customer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/test_helpers/_issuing_service.py b/stripe/test_helpers/_issuing_service.py new file mode 100644 index 000000000..59913225a --- /dev/null +++ b/stripe/test_helpers/_issuing_service.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.test_helpers.issuing._authorization_service import ( + AuthorizationService, +) +from stripe.test_helpers.issuing._card_service import CardService +from stripe.test_helpers.issuing._transaction_service import TransactionService + + +class IssuingService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.authorizations = AuthorizationService(self._requestor) + self.cards = CardService(self._requestor) + self.transactions = TransactionService(self._requestor) diff --git a/stripe/test_helpers/_refund_service.py b/stripe/test_helpers/_refund_service.py new file mode 100644 index 000000000..50ec1e28a --- /dev/null +++ b/stripe/test_helpers/_refund_service.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._refund import Refund +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class RefundService(StripeService): + class ExpireParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def expire( + self, + refund: str, + params: "RefundService.ExpireParams" = {}, + options: RequestOptions = {}, + ) -> Refund: + """ + Expire a refund with a status of requires_action. + """ + return cast( + Refund, + self._requestor.request( + "post", + "/v1/test_helpers/refunds/{refund}/expire".format( + refund=_util.sanitize_id(refund), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/test_helpers/_terminal_service.py b/stripe/test_helpers/_terminal_service.py new file mode 100644 index 000000000..d524ad3f8 --- /dev/null +++ b/stripe/test_helpers/_terminal_service.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.test_helpers.terminal._reader_service import ReaderService + + +class TerminalService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.readers = ReaderService(self._requestor) diff --git a/stripe/test_helpers/_test_clock.py b/stripe/test_helpers/_test_clock.py index 56ff6072a..c53508517 100644 --- a/stripe/test_helpers/_test_clock.py +++ b/stripe/test_helpers/_test_clock.py @@ -117,14 +117,7 @@ class RetrieveParams(RequestOptions): @classmethod def _cls_advance( - cls, - test_clock: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "TestClock.AdvanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, test_clock: str, **params: Unpack["TestClock.AdvanceParams"] ) -> "TestClock": """ Starts advancing a test clock to a specified time in the future. Advancement is done when status changes to Ready. @@ -136,9 +129,6 @@ def _cls_advance( "/v1/test_helpers/test_clocks/{test_clock}/advance".format( test_clock=_util.sanitize_id(test_clock) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -146,13 +136,7 @@ def _cls_advance( @overload @staticmethod def advance( - test_clock: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "TestClock.AdvanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + test_clock: str, **params: Unpack["TestClock.AdvanceParams"] ) -> "TestClock": """ Starts advancing a test clock to a specified time in the future. Advancement is done when status changes to Ready. @@ -161,11 +145,7 @@ def advance( @overload def advance( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "TestClock.AdvanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["TestClock.AdvanceParams"] ) -> "TestClock": """ Starts advancing a test clock to a specified time in the future. Advancement is done when status changes to Ready. @@ -174,11 +154,7 @@ def advance( @class_method_variant("_cls_advance") def advance( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "TestClock.AdvanceParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["TestClock.AdvanceParams"] ) -> "TestClock": """ Starts advancing a test clock to a specified time in the future. Advancement is done when status changes to Ready. @@ -190,22 +166,12 @@ def advance( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/test_clocks/{test_clock}/advance".format( test_clock=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod - def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "TestClock.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] - ) -> "TestClock": + def create(cls, **params: Unpack["TestClock.CreateParams"]) -> "TestClock": """ Creates a new test clock that can be attached to new customers and quotes. """ @@ -214,10 +180,6 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @@ -269,13 +231,7 @@ def delete( # pyright: ignore[reportGeneralTypeIssues] @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "TestClock.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["TestClock.ListParams"] ) -> ListObject["TestClock"]: """ Returns a list of your test clocks. @@ -283,9 +239,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/test_helpers/_test_clock_service.py b/stripe/test_helpers/_test_clock_service.py new file mode 100644 index 000000000..4cb4bc8a9 --- /dev/null +++ b/stripe/test_helpers/_test_clock_service.py @@ -0,0 +1,171 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.test_helpers._test_clock import TestClock +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class TestClockService(StripeService): + class AdvanceParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + frozen_time: int + """ + The time to advance the test clock. Must be after the test clock's current frozen time. Cannot be more than two intervals in the future from the shortest subscription in this test clock. If there are no subscriptions in this test clock, it cannot be more than two years in the future. + """ + + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + frozen_time: int + """ + The initial frozen time for this test clock. + """ + name: NotRequired["str"] + """ + The name for this test clock. + """ + + class DeleteParams(TypedDict): + pass + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def delete( + self, + test_clock: str, + params: "TestClockService.DeleteParams" = {}, + options: RequestOptions = {}, + ) -> TestClock: + """ + Deletes a test clock. + """ + return cast( + TestClock, + self._requestor.request( + "delete", + "/v1/test_helpers/test_clocks/{test_clock}".format( + test_clock=_util.sanitize_id(test_clock), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + test_clock: str, + params: "TestClockService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> TestClock: + """ + Retrieves a test clock. + """ + return cast( + TestClock, + self._requestor.request( + "get", + "/v1/test_helpers/test_clocks/{test_clock}".format( + test_clock=_util.sanitize_id(test_clock), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + params: "TestClockService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[TestClock]: + """ + Returns a list of your test clocks. + """ + return cast( + ListObject[TestClock], + self._requestor.request( + "get", + "/v1/test_helpers/test_clocks", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "TestClockService.CreateParams", + options: RequestOptions = {}, + ) -> TestClock: + """ + Creates a new test clock that can be attached to new customers and quotes. + """ + return cast( + TestClock, + self._requestor.request( + "post", + "/v1/test_helpers/test_clocks", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def advance( + self, + test_clock: str, + params: "TestClockService.AdvanceParams", + options: RequestOptions = {}, + ) -> TestClock: + """ + Starts advancing a test clock to a specified time in the future. Advancement is done when status changes to Ready. + """ + return cast( + TestClock, + self._requestor.request( + "post", + "/v1/test_helpers/test_clocks/{test_clock}/advance".format( + test_clock=_util.sanitize_id(test_clock), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/test_helpers/_treasury_service.py b/stripe/test_helpers/_treasury_service.py new file mode 100644 index 000000000..97ce82fc7 --- /dev/null +++ b/stripe/test_helpers/_treasury_service.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._stripe_service import StripeService +from stripe.test_helpers.treasury._inbound_transfer_service import ( + InboundTransferService, +) +from stripe.test_helpers.treasury._outbound_payment_service import ( + OutboundPaymentService, +) +from stripe.test_helpers.treasury._outbound_transfer_service import ( + OutboundTransferService, +) +from stripe.test_helpers.treasury._received_credit_service import ( + ReceivedCreditService, +) +from stripe.test_helpers.treasury._received_debit_service import ( + ReceivedDebitService, +) + + +class TreasuryService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.inbound_transfers = InboundTransferService(self._requestor) + self.outbound_payments = OutboundPaymentService(self._requestor) + self.outbound_transfers = OutboundTransferService(self._requestor) + self.received_credits = ReceivedCreditService(self._requestor) + self.received_debits = ReceivedDebitService(self._requestor) diff --git a/stripe/test_helpers/issuing/__init__.py b/stripe/test_helpers/issuing/__init__.py new file mode 100644 index 000000000..4d189b228 --- /dev/null +++ b/stripe/test_helpers/issuing/__init__.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe.test_helpers.issuing._authorization_service import ( + AuthorizationService as AuthorizationService, +) +from stripe.test_helpers.issuing._card_service import ( + CardService as CardService, +) +from stripe.test_helpers.issuing._transaction_service import ( + TransactionService as TransactionService, +) diff --git a/stripe/test_helpers/issuing/_authorization_service.py b/stripe/test_helpers/issuing/_authorization_service.py new file mode 100644 index 000000000..4f8c7e5b4 --- /dev/null +++ b/stripe/test_helpers/issuing/_authorization_service.py @@ -0,0 +1,458 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.issuing._authorization import Authorization +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class AuthorizationService(StripeService): + class CaptureParams(TypedDict): + capture_amount: NotRequired["int"] + """ + The amount to capture from the authorization. If not provided, the full amount of the authorization will be captured. This amount is in the authorization currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + """ + close_authorization: NotRequired["bool"] + """ + Whether to close the authorization after capture. Defaults to true. Set to false to enable multi-capture flows. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + purchase_details: NotRequired[ + "AuthorizationService.CaptureParamsPurchaseDetails" + ] + """ + Additional purchase information that is optionally provided by the merchant. + """ + + class CaptureParamsPurchaseDetails(TypedDict): + flight: NotRequired[ + "AuthorizationService.CaptureParamsPurchaseDetailsFlight" + ] + """ + Information about the flight that was purchased with this transaction. + """ + fuel: NotRequired[ + "AuthorizationService.CaptureParamsPurchaseDetailsFuel" + ] + """ + Information about fuel that was purchased with this transaction. + """ + lodging: NotRequired[ + "AuthorizationService.CaptureParamsPurchaseDetailsLodging" + ] + """ + Information about lodging that was purchased with this transaction. + """ + receipt: NotRequired[ + "List[AuthorizationService.CaptureParamsPurchaseDetailsReceipt]" + ] + """ + The line items in the purchase. + """ + reference: NotRequired["str"] + """ + A merchant-specific order number. + """ + + class CaptureParamsPurchaseDetailsFlight(TypedDict): + departure_at: NotRequired["int"] + """ + The time that the flight departed. + """ + passenger_name: NotRequired["str"] + """ + The name of the passenger. + """ + refundable: NotRequired["bool"] + """ + Whether the ticket is refundable. + """ + segments: NotRequired[ + "List[AuthorizationService.CaptureParamsPurchaseDetailsFlightSegment]" + ] + """ + The legs of the trip. + """ + travel_agency: NotRequired["str"] + """ + The travel agency that issued the ticket. + """ + + class CaptureParamsPurchaseDetailsFlightSegment(TypedDict): + arrival_airport_code: NotRequired["str"] + """ + The three-letter IATA airport code of the flight's destination. + """ + carrier: NotRequired["str"] + """ + The airline carrier code. + """ + departure_airport_code: NotRequired["str"] + """ + The three-letter IATA airport code that the flight departed from. + """ + flight_number: NotRequired["str"] + """ + The flight number. + """ + service_class: NotRequired["str"] + """ + The flight's service class. + """ + stopover_allowed: NotRequired["bool"] + """ + Whether a stopover is allowed on this flight. + """ + + class CaptureParamsPurchaseDetailsFuel(TypedDict): + type: NotRequired[ + "Literal['diesel', 'other', 'unleaded_plus', 'unleaded_regular', 'unleaded_super']" + ] + """ + The type of fuel that was purchased. One of `diesel`, `unleaded_plus`, `unleaded_regular`, `unleaded_super`, or `other`. + """ + unit: NotRequired["Literal['liter', 'us_gallon']"] + """ + The units for `volume_decimal`. One of `us_gallon` or `liter`. + """ + unit_cost_decimal: NotRequired["str"] + """ + The cost in cents per each unit of fuel, represented as a decimal string with at most 12 decimal places. + """ + volume_decimal: NotRequired["str"] + """ + The volume of the fuel that was pumped, represented as a decimal string with at most 12 decimal places. + """ + + class CaptureParamsPurchaseDetailsLodging(TypedDict): + check_in_at: NotRequired["int"] + """ + The time of checking into the lodging. + """ + nights: NotRequired["int"] + """ + The number of nights stayed at the lodging. + """ + + class CaptureParamsPurchaseDetailsReceipt(TypedDict): + description: NotRequired["str"] + quantity: NotRequired["str"] + total: NotRequired["int"] + unit_cost: NotRequired["int"] + + class CreateParams(TypedDict): + amount: int + """ + The total amount to attempt to authorize. This amount is in the provided currency, or defaults to the card's currency, and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + """ + amount_details: NotRequired[ + "AuthorizationService.CreateParamsAmountDetails" + ] + """ + Detailed breakdown of amount components. These amounts are denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + """ + authorization_method: NotRequired[ + "Literal['chip', 'contactless', 'keyed_in', 'online', 'swipe']" + ] + """ + How the card details were provided. Defaults to online. + """ + card: str + """ + Card associated with this authorization. + """ + currency: NotRequired["str"] + """ + The currency of the authorization. If not provided, defaults to the currency of the card. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + is_amount_controllable: NotRequired["bool"] + """ + If set `true`, you may provide [amount](https://stripe.com/docs/api/issuing/authorizations/approve#approve_issuing_authorization-amount) to control how much to hold for the authorization. + """ + merchant_data: NotRequired[ + "AuthorizationService.CreateParamsMerchantData" + ] + """ + Details about the seller (grocery store, e-commerce website, etc.) where the card authorization happened. + """ + network_data: NotRequired[ + "AuthorizationService.CreateParamsNetworkData" + ] + """ + Details about the authorization, such as identifiers, set by the card network. + """ + verification_data: NotRequired[ + "AuthorizationService.CreateParamsVerificationData" + ] + """ + Verifications that Stripe performed on information that the cardholder provided to the merchant. + """ + wallet: NotRequired[ + "Literal['apple_pay', 'google_pay', 'samsung_pay']" + ] + """ + The digital wallet used for this transaction. One of `apple_pay`, `google_pay`, or `samsung_pay`. Will populate as `null` when no digital wallet was utilized. + """ + + class CreateParamsAmountDetails(TypedDict): + atm_fee: NotRequired["int"] + """ + The ATM withdrawal fee. + """ + cashback_amount: NotRequired["int"] + """ + The amount of cash requested by the cardholder. + """ + + class CreateParamsMerchantData(TypedDict): + category: NotRequired[ + "Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']" + ] + """ + A categorization of the seller's type of business. See our [merchant categories guide](https://stripe.com/docs/issuing/merchant-categories) for a list of possible values. + """ + city: NotRequired["str"] + """ + City where the seller is located + """ + country: NotRequired["str"] + """ + Country where the seller is located + """ + name: NotRequired["str"] + """ + Name of the seller + """ + network_id: NotRequired["str"] + """ + Identifier assigned to the seller by the card network. Different card networks may assign different network_id fields to the same merchant. + """ + postal_code: NotRequired["str"] + """ + Postal code where the seller is located + """ + state: NotRequired["str"] + """ + State where the seller is located + """ + terminal_id: NotRequired["str"] + """ + An ID assigned by the seller to the location of the sale. + """ + url: NotRequired["str"] + """ + URL provided by the merchant on a 3DS request + """ + + class CreateParamsNetworkData(TypedDict): + acquiring_institution_id: NotRequired["str"] + """ + Identifier assigned to the acquirer by the card network. + """ + + class CreateParamsVerificationData(TypedDict): + address_line1_check: NotRequired[ + "Literal['match', 'mismatch', 'not_provided']" + ] + """ + Whether the cardholder provided an address first line and if it matched the cardholder's `billing.address.line1`. + """ + address_postal_code_check: NotRequired[ + "Literal['match', 'mismatch', 'not_provided']" + ] + """ + Whether the cardholder provided a postal code and if it matched the cardholder's `billing.address.postal_code`. + """ + authentication_exemption: NotRequired[ + "AuthorizationService.CreateParamsVerificationDataAuthenticationExemption" + ] + """ + The exemption applied to this authorization. + """ + cvc_check: NotRequired["Literal['match', 'mismatch', 'not_provided']"] + """ + Whether the cardholder provided a CVC and if it matched Stripe's record. + """ + expiry_check: NotRequired[ + "Literal['match', 'mismatch', 'not_provided']" + ] + """ + Whether the cardholder provided an expiry date and if it matched Stripe's record. + """ + three_d_secure: NotRequired[ + "AuthorizationService.CreateParamsVerificationDataThreeDSecure" + ] + """ + 3D Secure details. + """ + + class CreateParamsVerificationDataAuthenticationExemption(TypedDict): + claimed_by: Literal["acquirer", "issuer"] + """ + The entity that requested the exemption, either the acquiring merchant or the Issuing user. + """ + type: Literal[ + "low_value_transaction", "transaction_risk_analysis", "unknown" + ] + """ + The specific exemption claimed for this authorization. + """ + + class CreateParamsVerificationDataThreeDSecure(TypedDict): + result: Literal[ + "attempt_acknowledged", "authenticated", "failed", "required" + ] + """ + The outcome of the 3D Secure authentication request. + """ + + class ExpireParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class IncrementParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + increment_amount: int + """ + The amount to increment the authorization by. This amount is in the authorization currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + """ + is_amount_controllable: NotRequired["bool"] + """ + If set `true`, you may provide [amount](https://stripe.com/docs/api/issuing/authorizations/approve#approve_issuing_authorization-amount) to control how much to hold for the authorization. + """ + + class ReverseParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + reverse_amount: NotRequired["int"] + """ + The amount to reverse from the authorization. If not provided, the full amount of the authorization will be reversed. This amount is in the authorization currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + """ + + def create( + self, + params: "AuthorizationService.CreateParams", + options: RequestOptions = {}, + ) -> Authorization: + """ + Create a test-mode authorization. + """ + return cast( + Authorization, + self._requestor.request( + "post", + "/v1/test_helpers/issuing/authorizations", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def capture( + self, + authorization: str, + params: "AuthorizationService.CaptureParams" = {}, + options: RequestOptions = {}, + ) -> Authorization: + """ + Capture a test-mode authorization. + """ + return cast( + Authorization, + self._requestor.request( + "post", + "/v1/test_helpers/issuing/authorizations/{authorization}/capture".format( + authorization=_util.sanitize_id(authorization), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def expire( + self, + authorization: str, + params: "AuthorizationService.ExpireParams" = {}, + options: RequestOptions = {}, + ) -> Authorization: + """ + Expire a test-mode Authorization. + """ + return cast( + Authorization, + self._requestor.request( + "post", + "/v1/test_helpers/issuing/authorizations/{authorization}/expire".format( + authorization=_util.sanitize_id(authorization), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def increment( + self, + authorization: str, + params: "AuthorizationService.IncrementParams", + options: RequestOptions = {}, + ) -> Authorization: + """ + Increment a test-mode Authorization. + """ + return cast( + Authorization, + self._requestor.request( + "post", + "/v1/test_helpers/issuing/authorizations/{authorization}/increment".format( + authorization=_util.sanitize_id(authorization), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def reverse( + self, + authorization: str, + params: "AuthorizationService.ReverseParams" = {}, + options: RequestOptions = {}, + ) -> Authorization: + """ + Reverse a test-mode Authorization. + """ + return cast( + Authorization, + self._requestor.request( + "post", + "/v1/test_helpers/issuing/authorizations/{authorization}/reverse".format( + authorization=_util.sanitize_id(authorization), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/test_helpers/issuing/_card_service.py b/stripe/test_helpers/issuing/_card_service.py new file mode 100644 index 000000000..60015be02 --- /dev/null +++ b/stripe/test_helpers/issuing/_card_service.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.issuing._card import Card +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class CardService(StripeService): + class DeliverCardParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class FailCardParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ReturnCardParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ShipCardParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def deliver_card( + self, + card: str, + params: "CardService.DeliverCardParams" = {}, + options: RequestOptions = {}, + ) -> Card: + """ + Updates the shipping status of the specified Issuing Card object to delivered. + """ + return cast( + Card, + self._requestor.request( + "post", + "/v1/test_helpers/issuing/cards/{card}/shipping/deliver".format( + card=_util.sanitize_id(card), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def fail_card( + self, + card: str, + params: "CardService.FailCardParams" = {}, + options: RequestOptions = {}, + ) -> Card: + """ + Updates the shipping status of the specified Issuing Card object to failure. + """ + return cast( + Card, + self._requestor.request( + "post", + "/v1/test_helpers/issuing/cards/{card}/shipping/fail".format( + card=_util.sanitize_id(card), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def return_card( + self, + card: str, + params: "CardService.ReturnCardParams" = {}, + options: RequestOptions = {}, + ) -> Card: + """ + Updates the shipping status of the specified Issuing Card object to returned. + """ + return cast( + Card, + self._requestor.request( + "post", + "/v1/test_helpers/issuing/cards/{card}/shipping/return".format( + card=_util.sanitize_id(card), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def ship_card( + self, + card: str, + params: "CardService.ShipCardParams" = {}, + options: RequestOptions = {}, + ) -> Card: + """ + Updates the shipping status of the specified Issuing Card object to shipped. + """ + return cast( + Card, + self._requestor.request( + "post", + "/v1/test_helpers/issuing/cards/{card}/shipping/ship".format( + card=_util.sanitize_id(card), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/test_helpers/issuing/_transaction_service.py b/stripe/test_helpers/issuing/_transaction_service.py new file mode 100644 index 000000000..1aed037c9 --- /dev/null +++ b/stripe/test_helpers/issuing/_transaction_service.py @@ -0,0 +1,455 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.issuing._transaction import Transaction +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class TransactionService(StripeService): + class CreateForceCaptureParams(TypedDict): + amount: int + """ + The total amount to attempt to capture. This amount is in the provided currency, or defaults to the cards currency, and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + """ + card: str + """ + Card associated with this transaction. + """ + currency: NotRequired["str"] + """ + The currency of the capture. If not provided, defaults to the currency of the card. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + merchant_data: NotRequired[ + "TransactionService.CreateForceCaptureParamsMerchantData" + ] + """ + Details about the seller (grocery store, e-commerce website, etc.) where the card authorization happened. + """ + purchase_details: NotRequired[ + "TransactionService.CreateForceCaptureParamsPurchaseDetails" + ] + """ + Additional purchase information that is optionally provided by the merchant. + """ + + class CreateForceCaptureParamsMerchantData(TypedDict): + category: NotRequired[ + "Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']" + ] + """ + A categorization of the seller's type of business. See our [merchant categories guide](https://stripe.com/docs/issuing/merchant-categories) for a list of possible values. + """ + city: NotRequired["str"] + """ + City where the seller is located + """ + country: NotRequired["str"] + """ + Country where the seller is located + """ + name: NotRequired["str"] + """ + Name of the seller + """ + network_id: NotRequired["str"] + """ + Identifier assigned to the seller by the card network. Different card networks may assign different network_id fields to the same merchant. + """ + postal_code: NotRequired["str"] + """ + Postal code where the seller is located + """ + state: NotRequired["str"] + """ + State where the seller is located + """ + terminal_id: NotRequired["str"] + """ + An ID assigned by the seller to the location of the sale. + """ + url: NotRequired["str"] + """ + URL provided by the merchant on a 3DS request + """ + + class CreateForceCaptureParamsPurchaseDetails(TypedDict): + flight: NotRequired[ + "TransactionService.CreateForceCaptureParamsPurchaseDetailsFlight" + ] + """ + Information about the flight that was purchased with this transaction. + """ + fuel: NotRequired[ + "TransactionService.CreateForceCaptureParamsPurchaseDetailsFuel" + ] + """ + Information about fuel that was purchased with this transaction. + """ + lodging: NotRequired[ + "TransactionService.CreateForceCaptureParamsPurchaseDetailsLodging" + ] + """ + Information about lodging that was purchased with this transaction. + """ + receipt: NotRequired[ + "List[TransactionService.CreateForceCaptureParamsPurchaseDetailsReceipt]" + ] + """ + The line items in the purchase. + """ + reference: NotRequired["str"] + """ + A merchant-specific order number. + """ + + class CreateForceCaptureParamsPurchaseDetailsFlight(TypedDict): + departure_at: NotRequired["int"] + """ + The time that the flight departed. + """ + passenger_name: NotRequired["str"] + """ + The name of the passenger. + """ + refundable: NotRequired["bool"] + """ + Whether the ticket is refundable. + """ + segments: NotRequired[ + "List[TransactionService.CreateForceCaptureParamsPurchaseDetailsFlightSegment]" + ] + """ + The legs of the trip. + """ + travel_agency: NotRequired["str"] + """ + The travel agency that issued the ticket. + """ + + class CreateForceCaptureParamsPurchaseDetailsFlightSegment(TypedDict): + arrival_airport_code: NotRequired["str"] + """ + The three-letter IATA airport code of the flight's destination. + """ + carrier: NotRequired["str"] + """ + The airline carrier code. + """ + departure_airport_code: NotRequired["str"] + """ + The three-letter IATA airport code that the flight departed from. + """ + flight_number: NotRequired["str"] + """ + The flight number. + """ + service_class: NotRequired["str"] + """ + The flight's service class. + """ + stopover_allowed: NotRequired["bool"] + """ + Whether a stopover is allowed on this flight. + """ + + class CreateForceCaptureParamsPurchaseDetailsFuel(TypedDict): + type: NotRequired[ + "Literal['diesel', 'other', 'unleaded_plus', 'unleaded_regular', 'unleaded_super']" + ] + """ + The type of fuel that was purchased. One of `diesel`, `unleaded_plus`, `unleaded_regular`, `unleaded_super`, or `other`. + """ + unit: NotRequired["Literal['liter', 'us_gallon']"] + """ + The units for `volume_decimal`. One of `us_gallon` or `liter`. + """ + unit_cost_decimal: NotRequired["str"] + """ + The cost in cents per each unit of fuel, represented as a decimal string with at most 12 decimal places. + """ + volume_decimal: NotRequired["str"] + """ + The volume of the fuel that was pumped, represented as a decimal string with at most 12 decimal places. + """ + + class CreateForceCaptureParamsPurchaseDetailsLodging(TypedDict): + check_in_at: NotRequired["int"] + """ + The time of checking into the lodging. + """ + nights: NotRequired["int"] + """ + The number of nights stayed at the lodging. + """ + + class CreateForceCaptureParamsPurchaseDetailsReceipt(TypedDict): + description: NotRequired["str"] + quantity: NotRequired["str"] + total: NotRequired["int"] + unit_cost: NotRequired["int"] + + class CreateUnlinkedRefundParams(TypedDict): + amount: int + """ + The total amount to attempt to refund. This amount is in the provided currency, or defaults to the cards currency, and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + """ + card: str + """ + Card associated with this unlinked refund transaction. + """ + currency: NotRequired["str"] + """ + The currency of the unlinked refund. If not provided, defaults to the currency of the card. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + merchant_data: NotRequired[ + "TransactionService.CreateUnlinkedRefundParamsMerchantData" + ] + """ + Details about the seller (grocery store, e-commerce website, etc.) where the card authorization happened. + """ + purchase_details: NotRequired[ + "TransactionService.CreateUnlinkedRefundParamsPurchaseDetails" + ] + """ + Additional purchase information that is optionally provided by the merchant. + """ + + class CreateUnlinkedRefundParamsMerchantData(TypedDict): + category: NotRequired[ + "Literal['ac_refrigeration_repair', 'accounting_bookkeeping_services', 'advertising_services', 'agricultural_cooperative', 'airlines_air_carriers', 'airports_flying_fields', 'ambulance_services', 'amusement_parks_carnivals', 'antique_reproductions', 'antique_shops', 'aquariums', 'architectural_surveying_services', 'art_dealers_and_galleries', 'artists_supply_and_craft_shops', 'auto_and_home_supply_stores', 'auto_body_repair_shops', 'auto_paint_shops', 'auto_service_shops', 'automated_cash_disburse', 'automated_fuel_dispensers', 'automobile_associations', 'automotive_parts_and_accessories_stores', 'automotive_tire_stores', 'bail_and_bond_payments', 'bakeries', 'bands_orchestras', 'barber_and_beauty_shops', 'betting_casino_gambling', 'bicycle_shops', 'billiard_pool_establishments', 'boat_dealers', 'boat_rentals_and_leases', 'book_stores', 'books_periodicals_and_newspapers', 'bowling_alleys', 'bus_lines', 'business_secretarial_schools', 'buying_shopping_services', 'cable_satellite_and_other_pay_television_and_radio', 'camera_and_photographic_supply_stores', 'candy_nut_and_confectionery_stores', 'car_and_truck_dealers_new_used', 'car_and_truck_dealers_used_only', 'car_rental_agencies', 'car_washes', 'carpentry_services', 'carpet_upholstery_cleaning', 'caterers', 'charitable_and_social_service_organizations_fundraising', 'chemicals_and_allied_products', 'child_care_services', 'childrens_and_infants_wear_stores', 'chiropodists_podiatrists', 'chiropractors', 'cigar_stores_and_stands', 'civic_social_fraternal_associations', 'cleaning_and_maintenance', 'clothing_rental', 'colleges_universities', 'commercial_equipment', 'commercial_footwear', 'commercial_photography_art_and_graphics', 'commuter_transport_and_ferries', 'computer_network_services', 'computer_programming', 'computer_repair', 'computer_software_stores', 'computers_peripherals_and_software', 'concrete_work_services', 'construction_materials', 'consulting_public_relations', 'correspondence_schools', 'cosmetic_stores', 'counseling_services', 'country_clubs', 'courier_services', 'court_costs', 'credit_reporting_agencies', 'cruise_lines', 'dairy_products_stores', 'dance_hall_studios_schools', 'dating_escort_services', 'dentists_orthodontists', 'department_stores', 'detective_agencies', 'digital_goods_applications', 'digital_goods_games', 'digital_goods_large_volume', 'digital_goods_media', 'direct_marketing_catalog_merchant', 'direct_marketing_combination_catalog_and_retail_merchant', 'direct_marketing_inbound_telemarketing', 'direct_marketing_insurance_services', 'direct_marketing_other', 'direct_marketing_outbound_telemarketing', 'direct_marketing_subscription', 'direct_marketing_travel', 'discount_stores', 'doctors', 'door_to_door_sales', 'drapery_window_covering_and_upholstery_stores', 'drinking_places', 'drug_stores_and_pharmacies', 'drugs_drug_proprietaries_and_druggist_sundries', 'dry_cleaners', 'durable_goods', 'duty_free_stores', 'eating_places_restaurants', 'educational_services', 'electric_razor_stores', 'electric_vehicle_charging', 'electrical_parts_and_equipment', 'electrical_services', 'electronics_repair_shops', 'electronics_stores', 'elementary_secondary_schools', 'emergency_services_gcas_visa_use_only', 'employment_temp_agencies', 'equipment_rental', 'exterminating_services', 'family_clothing_stores', 'fast_food_restaurants', 'financial_institutions', 'fines_government_administrative_entities', 'fireplace_fireplace_screens_and_accessories_stores', 'floor_covering_stores', 'florists', 'florists_supplies_nursery_stock_and_flowers', 'freezer_and_locker_meat_provisioners', 'fuel_dealers_non_automotive', 'funeral_services_crematories', 'furniture_home_furnishings_and_equipment_stores_except_appliances', 'furniture_repair_refinishing', 'furriers_and_fur_shops', 'general_services', 'gift_card_novelty_and_souvenir_shops', 'glass_paint_and_wallpaper_stores', 'glassware_crystal_stores', 'golf_courses_public', 'government_licensed_horse_dog_racing_us_region_only', 'government_licensed_online_casions_online_gambling_us_region_only', 'government_owned_lotteries_non_us_region', 'government_owned_lotteries_us_region_only', 'government_services', 'grocery_stores_supermarkets', 'hardware_equipment_and_supplies', 'hardware_stores', 'health_and_beauty_spas', 'hearing_aids_sales_and_supplies', 'heating_plumbing_a_c', 'hobby_toy_and_game_shops', 'home_supply_warehouse_stores', 'hospitals', 'hotels_motels_and_resorts', 'household_appliance_stores', 'industrial_supplies', 'information_retrieval_services', 'insurance_default', 'insurance_underwriting_premiums', 'intra_company_purchases', 'jewelry_stores_watches_clocks_and_silverware_stores', 'landscaping_services', 'laundries', 'laundry_cleaning_services', 'legal_services_attorneys', 'luggage_and_leather_goods_stores', 'lumber_building_materials_stores', 'manual_cash_disburse', 'marinas_service_and_supplies', 'marketplaces', 'masonry_stonework_and_plaster', 'massage_parlors', 'medical_and_dental_labs', 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies', 'medical_services', 'membership_organizations', 'mens_and_boys_clothing_and_accessories_stores', 'mens_womens_clothing_stores', 'metal_service_centers', 'miscellaneous_apparel_and_accessory_shops', 'miscellaneous_auto_dealers', 'miscellaneous_business_services', 'miscellaneous_food_stores', 'miscellaneous_general_merchandise', 'miscellaneous_general_services', 'miscellaneous_home_furnishing_specialty_stores', 'miscellaneous_publishing_and_printing', 'miscellaneous_recreation_services', 'miscellaneous_repair_shops', 'miscellaneous_specialty_retail', 'mobile_home_dealers', 'motion_picture_theaters', 'motor_freight_carriers_and_trucking', 'motor_homes_dealers', 'motor_vehicle_supplies_and_new_parts', 'motorcycle_shops_and_dealers', 'motorcycle_shops_dealers', 'music_stores_musical_instruments_pianos_and_sheet_music', 'news_dealers_and_newsstands', 'non_fi_money_orders', 'non_fi_stored_value_card_purchase_load', 'nondurable_goods', 'nurseries_lawn_and_garden_supply_stores', 'nursing_personal_care', 'office_and_commercial_furniture', 'opticians_eyeglasses', 'optometrists_ophthalmologist', 'orthopedic_goods_prosthetic_devices', 'osteopaths', 'package_stores_beer_wine_and_liquor', 'paints_varnishes_and_supplies', 'parking_lots_garages', 'passenger_railways', 'pawn_shops', 'pet_shops_pet_food_and_supplies', 'petroleum_and_petroleum_products', 'photo_developing', 'photographic_photocopy_microfilm_equipment_and_supplies', 'photographic_studios', 'picture_video_production', 'piece_goods_notions_and_other_dry_goods', 'plumbing_heating_equipment_and_supplies', 'political_organizations', 'postal_services_government_only', 'precious_stones_and_metals_watches_and_jewelry', 'professional_services', 'public_warehousing_and_storage', 'quick_copy_repro_and_blueprint', 'railroads', 'real_estate_agents_and_managers_rentals', 'record_stores', 'recreational_vehicle_rentals', 'religious_goods_stores', 'religious_organizations', 'roofing_siding_sheet_metal', 'secretarial_support_services', 'security_brokers_dealers', 'service_stations', 'sewing_needlework_fabric_and_piece_goods_stores', 'shoe_repair_hat_cleaning', 'shoe_stores', 'small_appliance_repair', 'snowmobile_dealers', 'special_trade_services', 'specialty_cleaning', 'sporting_goods_stores', 'sporting_recreation_camps', 'sports_and_riding_apparel_stores', 'sports_clubs_fields', 'stamp_and_coin_stores', 'stationary_office_supplies_printing_and_writing_paper', 'stationery_stores_office_and_school_supply_stores', 'swimming_pools_sales', 't_ui_travel_germany', 'tailors_alterations', 'tax_payments_government_agencies', 'tax_preparation_services', 'taxicabs_limousines', 'telecommunication_equipment_and_telephone_sales', 'telecommunication_services', 'telegraph_services', 'tent_and_awning_shops', 'testing_laboratories', 'theatrical_ticket_agencies', 'timeshares', 'tire_retreading_and_repair', 'tolls_bridge_fees', 'tourist_attractions_and_exhibits', 'towing_services', 'trailer_parks_campgrounds', 'transportation_services', 'travel_agencies_tour_operators', 'truck_stop_iteration', 'truck_utility_trailer_rentals', 'typesetting_plate_making_and_related_services', 'typewriter_stores', 'u_s_federal_government_agencies_or_departments', 'uniforms_commercial_clothing', 'used_merchandise_and_secondhand_stores', 'utilities', 'variety_stores', 'veterinary_services', 'video_amusement_game_supplies', 'video_game_arcades', 'video_tape_rental_stores', 'vocational_trade_schools', 'watch_jewelry_repair', 'welding_repair', 'wholesale_clubs', 'wig_and_toupee_stores', 'wires_money_orders', 'womens_accessory_and_specialty_shops', 'womens_ready_to_wear_stores', 'wrecking_and_salvage_yards']" + ] + """ + A categorization of the seller's type of business. See our [merchant categories guide](https://stripe.com/docs/issuing/merchant-categories) for a list of possible values. + """ + city: NotRequired["str"] + """ + City where the seller is located + """ + country: NotRequired["str"] + """ + Country where the seller is located + """ + name: NotRequired["str"] + """ + Name of the seller + """ + network_id: NotRequired["str"] + """ + Identifier assigned to the seller by the card network. Different card networks may assign different network_id fields to the same merchant. + """ + postal_code: NotRequired["str"] + """ + Postal code where the seller is located + """ + state: NotRequired["str"] + """ + State where the seller is located + """ + terminal_id: NotRequired["str"] + """ + An ID assigned by the seller to the location of the sale. + """ + url: NotRequired["str"] + """ + URL provided by the merchant on a 3DS request + """ + + class CreateUnlinkedRefundParamsPurchaseDetails(TypedDict): + flight: NotRequired[ + "TransactionService.CreateUnlinkedRefundParamsPurchaseDetailsFlight" + ] + """ + Information about the flight that was purchased with this transaction. + """ + fuel: NotRequired[ + "TransactionService.CreateUnlinkedRefundParamsPurchaseDetailsFuel" + ] + """ + Information about fuel that was purchased with this transaction. + """ + lodging: NotRequired[ + "TransactionService.CreateUnlinkedRefundParamsPurchaseDetailsLodging" + ] + """ + Information about lodging that was purchased with this transaction. + """ + receipt: NotRequired[ + "List[TransactionService.CreateUnlinkedRefundParamsPurchaseDetailsReceipt]" + ] + """ + The line items in the purchase. + """ + reference: NotRequired["str"] + """ + A merchant-specific order number. + """ + + class CreateUnlinkedRefundParamsPurchaseDetailsFlight(TypedDict): + departure_at: NotRequired["int"] + """ + The time that the flight departed. + """ + passenger_name: NotRequired["str"] + """ + The name of the passenger. + """ + refundable: NotRequired["bool"] + """ + Whether the ticket is refundable. + """ + segments: NotRequired[ + "List[TransactionService.CreateUnlinkedRefundParamsPurchaseDetailsFlightSegment]" + ] + """ + The legs of the trip. + """ + travel_agency: NotRequired["str"] + """ + The travel agency that issued the ticket. + """ + + class CreateUnlinkedRefundParamsPurchaseDetailsFlightSegment(TypedDict): + arrival_airport_code: NotRequired["str"] + """ + The three-letter IATA airport code of the flight's destination. + """ + carrier: NotRequired["str"] + """ + The airline carrier code. + """ + departure_airport_code: NotRequired["str"] + """ + The three-letter IATA airport code that the flight departed from. + """ + flight_number: NotRequired["str"] + """ + The flight number. + """ + service_class: NotRequired["str"] + """ + The flight's service class. + """ + stopover_allowed: NotRequired["bool"] + """ + Whether a stopover is allowed on this flight. + """ + + class CreateUnlinkedRefundParamsPurchaseDetailsFuel(TypedDict): + type: NotRequired[ + "Literal['diesel', 'other', 'unleaded_plus', 'unleaded_regular', 'unleaded_super']" + ] + """ + The type of fuel that was purchased. One of `diesel`, `unleaded_plus`, `unleaded_regular`, `unleaded_super`, or `other`. + """ + unit: NotRequired["Literal['liter', 'us_gallon']"] + """ + The units for `volume_decimal`. One of `us_gallon` or `liter`. + """ + unit_cost_decimal: NotRequired["str"] + """ + The cost in cents per each unit of fuel, represented as a decimal string with at most 12 decimal places. + """ + volume_decimal: NotRequired["str"] + """ + The volume of the fuel that was pumped, represented as a decimal string with at most 12 decimal places. + """ + + class CreateUnlinkedRefundParamsPurchaseDetailsLodging(TypedDict): + check_in_at: NotRequired["int"] + """ + The time of checking into the lodging. + """ + nights: NotRequired["int"] + """ + The number of nights stayed at the lodging. + """ + + class CreateUnlinkedRefundParamsPurchaseDetailsReceipt(TypedDict): + description: NotRequired["str"] + quantity: NotRequired["str"] + total: NotRequired["int"] + unit_cost: NotRequired["int"] + + class RefundParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + refund_amount: NotRequired["int"] + """ + The total amount to attempt to refund. This amount is in the provided currency, or defaults to the cards currency, and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + """ + + def refund( + self, + transaction: str, + params: "TransactionService.RefundParams" = {}, + options: RequestOptions = {}, + ) -> Transaction: + """ + Refund a test-mode Transaction. + """ + return cast( + Transaction, + self._requestor.request( + "post", + "/v1/test_helpers/issuing/transactions/{transaction}/refund".format( + transaction=_util.sanitize_id(transaction), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create_force_capture( + self, + params: "TransactionService.CreateForceCaptureParams", + options: RequestOptions = {}, + ) -> Transaction: + """ + Allows the user to capture an arbitrary amount, also known as a forced capture. + """ + return cast( + Transaction, + self._requestor.request( + "post", + "/v1/test_helpers/issuing/transactions/create_force_capture", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create_unlinked_refund( + self, + params: "TransactionService.CreateUnlinkedRefundParams", + options: RequestOptions = {}, + ) -> Transaction: + """ + Allows the user to refund an arbitrary amount, also known as a unlinked refund. + """ + return cast( + Transaction, + self._requestor.request( + "post", + "/v1/test_helpers/issuing/transactions/create_unlinked_refund", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/test_helpers/terminal/__init__.py b/stripe/test_helpers/terminal/__init__.py new file mode 100644 index 000000000..847049bfb --- /dev/null +++ b/stripe/test_helpers/terminal/__init__.py @@ -0,0 +1,5 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe.test_helpers.terminal._reader_service import ( + ReaderService as ReaderService, +) diff --git a/stripe/test_helpers/terminal/_reader_service.py b/stripe/test_helpers/terminal/_reader_service.py new file mode 100644 index 000000000..e7ab02b47 --- /dev/null +++ b/stripe/test_helpers/terminal/_reader_service.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.terminal._reader import Reader +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ReaderService(StripeService): + class PresentPaymentMethodParams(TypedDict): + amount_tip: NotRequired["int"] + """ + Simulated on-reader tip amount. + """ + card_present: NotRequired[ + "ReaderService.PresentPaymentMethodParamsCardPresent" + ] + """ + Simulated data for the card_present payment method. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + interac_present: NotRequired[ + "ReaderService.PresentPaymentMethodParamsInteracPresent" + ] + """ + Simulated data for the interac_present payment method. + """ + type: NotRequired["Literal['card_present', 'interac_present']"] + """ + Simulated payment type. + """ + + class PresentPaymentMethodParamsCardPresent(TypedDict): + number: NotRequired["str"] + """ + The card number, as a string without any separators. + """ + + class PresentPaymentMethodParamsInteracPresent(TypedDict): + number: NotRequired["str"] + """ + Card Number + """ + + def present_payment_method( + self, + reader: str, + params: "ReaderService.PresentPaymentMethodParams" = {}, + options: RequestOptions = {}, + ) -> Reader: + """ + Presents a payment method on a simulated reader. Can be used to simulate accepting a payment, saving a card or refunding a transaction. + """ + return cast( + Reader, + self._requestor.request( + "post", + "/v1/test_helpers/terminal/readers/{reader}/present_payment_method".format( + reader=_util.sanitize_id(reader), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/test_helpers/treasury/__init__.py b/stripe/test_helpers/treasury/__init__.py new file mode 100644 index 000000000..f1f68c28f --- /dev/null +++ b/stripe/test_helpers/treasury/__init__.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe.test_helpers.treasury._inbound_transfer_service import ( + InboundTransferService as InboundTransferService, +) +from stripe.test_helpers.treasury._outbound_payment_service import ( + OutboundPaymentService as OutboundPaymentService, +) +from stripe.test_helpers.treasury._outbound_transfer_service import ( + OutboundTransferService as OutboundTransferService, +) +from stripe.test_helpers.treasury._received_credit_service import ( + ReceivedCreditService as ReceivedCreditService, +) +from stripe.test_helpers.treasury._received_debit_service import ( + ReceivedDebitService as ReceivedDebitService, +) diff --git a/stripe/test_helpers/treasury/_inbound_transfer_service.py b/stripe/test_helpers/treasury/_inbound_transfer_service.py new file mode 100644 index 000000000..606b6bec9 --- /dev/null +++ b/stripe/test_helpers/treasury/_inbound_transfer_service.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._inbound_transfer import InboundTransfer +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class InboundTransferService(StripeService): + class FailParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + failure_details: NotRequired[ + "InboundTransferService.FailParamsFailureDetails" + ] + """ + Details about a failed InboundTransfer. + """ + + class FailParamsFailureDetails(TypedDict): + code: NotRequired[ + "Literal['account_closed', 'account_frozen', 'bank_account_restricted', 'bank_ownership_changed', 'debit_not_authorized', 'incorrect_account_holder_address', 'incorrect_account_holder_name', 'incorrect_account_holder_tax_id', 'insufficient_funds', 'invalid_account_number', 'invalid_currency', 'no_account', 'other']" + ] + """ + Reason for the failure. + """ + + class ReturnInboundTransferParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class SucceedParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def fail( + self, + id: str, + params: "InboundTransferService.FailParams" = {}, + options: RequestOptions = {}, + ) -> InboundTransfer: + """ + Transitions a test mode created InboundTransfer to the failed status. The InboundTransfer must already be in the processing state. + """ + return cast( + InboundTransfer, + self._requestor.request( + "post", + "/v1/test_helpers/treasury/inbound_transfers/{id}/fail".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def return_inbound_transfer( + self, + id: str, + params: "InboundTransferService.ReturnInboundTransferParams" = {}, + options: RequestOptions = {}, + ) -> InboundTransfer: + """ + Marks the test mode InboundTransfer object as returned and links the InboundTransfer to a ReceivedDebit. The InboundTransfer must already be in the succeeded state. + """ + return cast( + InboundTransfer, + self._requestor.request( + "post", + "/v1/test_helpers/treasury/inbound_transfers/{id}/return".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def succeed( + self, + id: str, + params: "InboundTransferService.SucceedParams" = {}, + options: RequestOptions = {}, + ) -> InboundTransfer: + """ + Transitions a test mode created InboundTransfer to the succeeded status. The InboundTransfer must already be in the processing state. + """ + return cast( + InboundTransfer, + self._requestor.request( + "post", + "/v1/test_helpers/treasury/inbound_transfers/{id}/succeed".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/test_helpers/treasury/_outbound_payment_service.py b/stripe/test_helpers/treasury/_outbound_payment_service.py new file mode 100644 index 000000000..372441623 --- /dev/null +++ b/stripe/test_helpers/treasury/_outbound_payment_service.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._outbound_payment import OutboundPayment +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class OutboundPaymentService(StripeService): + class FailParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class PostParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ReturnOutboundPaymentParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + returned_details: NotRequired[ + "OutboundPaymentService.ReturnOutboundPaymentParamsReturnedDetails" + ] + """ + Optional hash to set the the return code. + """ + + class ReturnOutboundPaymentParamsReturnedDetails(TypedDict): + code: NotRequired[ + "Literal['account_closed', 'account_frozen', 'bank_account_restricted', 'bank_ownership_changed', 'declined', 'incorrect_account_holder_name', 'invalid_account_number', 'invalid_currency', 'no_account', 'other']" + ] + """ + The return code to be set on the OutboundPayment object. + """ + + def fail( + self, + id: str, + params: "OutboundPaymentService.FailParams" = {}, + options: RequestOptions = {}, + ) -> OutboundPayment: + """ + Transitions a test mode created OutboundPayment to the failed status. The OutboundPayment must already be in the processing state. + """ + return cast( + OutboundPayment, + self._requestor.request( + "post", + "/v1/test_helpers/treasury/outbound_payments/{id}/fail".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def post( + self, + id: str, + params: "OutboundPaymentService.PostParams" = {}, + options: RequestOptions = {}, + ) -> OutboundPayment: + """ + Transitions a test mode created OutboundPayment to the posted status. The OutboundPayment must already be in the processing state. + """ + return cast( + OutboundPayment, + self._requestor.request( + "post", + "/v1/test_helpers/treasury/outbound_payments/{id}/post".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def return_outbound_payment( + self, + id: str, + params: "OutboundPaymentService.ReturnOutboundPaymentParams" = {}, + options: RequestOptions = {}, + ) -> OutboundPayment: + """ + Transitions a test mode created OutboundPayment to the returned status. The OutboundPayment must already be in the processing state. + """ + return cast( + OutboundPayment, + self._requestor.request( + "post", + "/v1/test_helpers/treasury/outbound_payments/{id}/return".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/test_helpers/treasury/_outbound_transfer_service.py b/stripe/test_helpers/treasury/_outbound_transfer_service.py new file mode 100644 index 000000000..bd7e07319 --- /dev/null +++ b/stripe/test_helpers/treasury/_outbound_transfer_service.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._outbound_transfer import OutboundTransfer +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class OutboundTransferService(StripeService): + class FailParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class PostParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class ReturnOutboundTransferParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + returned_details: NotRequired[ + "OutboundTransferService.ReturnOutboundTransferParamsReturnedDetails" + ] + """ + Details about a returned OutboundTransfer. + """ + + class ReturnOutboundTransferParamsReturnedDetails(TypedDict): + code: NotRequired[ + "Literal['account_closed', 'account_frozen', 'bank_account_restricted', 'bank_ownership_changed', 'declined', 'incorrect_account_holder_name', 'invalid_account_number', 'invalid_currency', 'no_account', 'other']" + ] + """ + Reason for the return. + """ + + def fail( + self, + outbound_transfer: str, + params: "OutboundTransferService.FailParams" = {}, + options: RequestOptions = {}, + ) -> OutboundTransfer: + """ + Transitions a test mode created OutboundTransfer to the failed status. The OutboundTransfer must already be in the processing state. + """ + return cast( + OutboundTransfer, + self._requestor.request( + "post", + "/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/fail".format( + outbound_transfer=_util.sanitize_id(outbound_transfer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def post( + self, + outbound_transfer: str, + params: "OutboundTransferService.PostParams" = {}, + options: RequestOptions = {}, + ) -> OutboundTransfer: + """ + Transitions a test mode created OutboundTransfer to the posted status. The OutboundTransfer must already be in the processing state. + """ + return cast( + OutboundTransfer, + self._requestor.request( + "post", + "/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/post".format( + outbound_transfer=_util.sanitize_id(outbound_transfer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def return_outbound_transfer( + self, + outbound_transfer: str, + params: "OutboundTransferService.ReturnOutboundTransferParams" = {}, + options: RequestOptions = {}, + ) -> OutboundTransfer: + """ + Transitions a test mode created OutboundTransfer to the returned status. The OutboundTransfer must already be in the processing state. + """ + return cast( + OutboundTransfer, + self._requestor.request( + "post", + "/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/return".format( + outbound_transfer=_util.sanitize_id(outbound_transfer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/test_helpers/treasury/_received_credit_service.py b/stripe/test_helpers/treasury/_received_credit_service.py new file mode 100644 index 000000000..7cec7958d --- /dev/null +++ b/stripe/test_helpers/treasury/_received_credit_service.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._received_credit import ReceivedCredit +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ReceivedCreditService(StripeService): + class CreateParams(TypedDict): + amount: int + """ + Amount (in cents) to be transferred. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + The FinancialAccount to send funds to. + """ + initiating_payment_method_details: NotRequired[ + "ReceivedCreditService.CreateParamsInitiatingPaymentMethodDetails" + ] + """ + Initiating payment method details for the object. + """ + network: Literal["ach", "us_domestic_wire"] + """ + The rails used for the object. + """ + + class CreateParamsInitiatingPaymentMethodDetails(TypedDict): + type: Literal["us_bank_account"] + """ + The source type. + """ + us_bank_account: NotRequired[ + "ReceivedCreditService.CreateParamsInitiatingPaymentMethodDetailsUsBankAccount" + ] + """ + Optional fields for `us_bank_account`. + """ + + class CreateParamsInitiatingPaymentMethodDetailsUsBankAccount(TypedDict): + account_holder_name: NotRequired["str"] + """ + The bank account holder's name. + """ + account_number: NotRequired["str"] + """ + The bank account number. + """ + routing_number: NotRequired["str"] + """ + The bank account's routing number. + """ + + def create( + self, + params: "ReceivedCreditService.CreateParams", + options: RequestOptions = {}, + ) -> ReceivedCredit: + """ + Use this endpoint to simulate a test mode ReceivedCredit initiated by a third party. In live mode, you can't directly create ReceivedCredits initiated by third parties. + """ + return cast( + ReceivedCredit, + self._requestor.request( + "post", + "/v1/test_helpers/treasury/received_credits", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/test_helpers/treasury/_received_debit_service.py b/stripe/test_helpers/treasury/_received_debit_service.py new file mode 100644 index 000000000..7b35c298d --- /dev/null +++ b/stripe/test_helpers/treasury/_received_debit_service.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._received_debit import ReceivedDebit +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ReceivedDebitService(StripeService): + class CreateParams(TypedDict): + amount: int + """ + Amount (in cents) to be transferred. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + The FinancialAccount to pull funds from. + """ + initiating_payment_method_details: NotRequired[ + "ReceivedDebitService.CreateParamsInitiatingPaymentMethodDetails" + ] + """ + Initiating payment method details for the object. + """ + network: Literal["ach"] + """ + The rails used for the object. + """ + + class CreateParamsInitiatingPaymentMethodDetails(TypedDict): + type: Literal["us_bank_account"] + """ + The source type. + """ + us_bank_account: NotRequired[ + "ReceivedDebitService.CreateParamsInitiatingPaymentMethodDetailsUsBankAccount" + ] + """ + Optional fields for `us_bank_account`. + """ + + class CreateParamsInitiatingPaymentMethodDetailsUsBankAccount(TypedDict): + account_holder_name: NotRequired["str"] + """ + The bank account holder's name. + """ + account_number: NotRequired["str"] + """ + The bank account number. + """ + routing_number: NotRequired["str"] + """ + The bank account's routing number. + """ + + def create( + self, + params: "ReceivedDebitService.CreateParams", + options: RequestOptions = {}, + ) -> ReceivedDebit: + """ + Use this endpoint to simulate a test mode ReceivedDebit initiated by a third party. In live mode, you can't directly create ReceivedDebits initiated by third parties. + """ + return cast( + ReceivedDebit, + self._requestor.request( + "post", + "/v1/test_helpers/treasury/received_debits", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/treasury/__init__.py b/stripe/treasury/__init__.py index fb2e12e52..bc0bc6268 100644 --- a/stripe/treasury/__init__.py +++ b/stripe/treasury/__init__.py @@ -1,25 +1,58 @@ # -*- coding: utf-8 -*- # File generated from our OpenAPI spec from stripe.treasury._credit_reversal import CreditReversal as CreditReversal +from stripe.treasury._credit_reversal_service import ( + CreditReversalService as CreditReversalService, +) from stripe.treasury._debit_reversal import DebitReversal as DebitReversal +from stripe.treasury._debit_reversal_service import ( + DebitReversalService as DebitReversalService, +) from stripe.treasury._financial_account import ( FinancialAccount as FinancialAccount, ) from stripe.treasury._financial_account_features import ( FinancialAccountFeatures as FinancialAccountFeatures, ) +from stripe.treasury._financial_account_features_service import ( + FinancialAccountFeaturesService as FinancialAccountFeaturesService, +) +from stripe.treasury._financial_account_service import ( + FinancialAccountService as FinancialAccountService, +) from stripe.treasury._inbound_transfer import ( InboundTransfer as InboundTransfer, ) +from stripe.treasury._inbound_transfer_service import ( + InboundTransferService as InboundTransferService, +) from stripe.treasury._outbound_payment import ( OutboundPayment as OutboundPayment, ) +from stripe.treasury._outbound_payment_service import ( + OutboundPaymentService as OutboundPaymentService, +) from stripe.treasury._outbound_transfer import ( OutboundTransfer as OutboundTransfer, ) +from stripe.treasury._outbound_transfer_service import ( + OutboundTransferService as OutboundTransferService, +) from stripe.treasury._received_credit import ReceivedCredit as ReceivedCredit +from stripe.treasury._received_credit_service import ( + ReceivedCreditService as ReceivedCreditService, +) from stripe.treasury._received_debit import ReceivedDebit as ReceivedDebit +from stripe.treasury._received_debit_service import ( + ReceivedDebitService as ReceivedDebitService, +) from stripe.treasury._transaction import Transaction as Transaction from stripe.treasury._transaction_entry import ( TransactionEntry as TransactionEntry, ) +from stripe.treasury._transaction_entry_service import ( + TransactionEntryService as TransactionEntryService, +) +from stripe.treasury._transaction_service import ( + TransactionService as TransactionService, +) diff --git a/stripe/treasury/_credit_reversal.py b/stripe/treasury/_credit_reversal.py index a3fc8473d..82aca7854 100644 --- a/stripe/treasury/_credit_reversal.py +++ b/stripe/treasury/_credit_reversal.py @@ -137,14 +137,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "CreditReversal.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["CreditReversal.CreateParams"] ) -> "CreditReversal": """ Reverses a ReceivedCredit and creates a CreditReversal object. @@ -154,23 +147,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "CreditReversal.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["CreditReversal.ListParams"] ) -> ListObject["CreditReversal"]: """ Returns a list of CreditReversals. @@ -178,9 +161,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/treasury/_credit_reversal_service.py b/stripe/treasury/_credit_reversal_service.py new file mode 100644 index 000000000..4601cd09e --- /dev/null +++ b/stripe/treasury/_credit_reversal_service.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._credit_reversal import CreditReversal +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class CreditReversalService(StripeService): + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + received_credit: str + """ + The ReceivedCredit to reverse. + """ + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + Returns objects associated with this FinancialAccount. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + received_credit: NotRequired["str"] + """ + Only return CreditReversals for the ReceivedCredit ID. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired["Literal['canceled', 'posted', 'processing']"] + """ + Only return CreditReversals for a given status. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "CreditReversalService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[CreditReversal]: + """ + Returns a list of CreditReversals. + """ + return cast( + ListObject[CreditReversal], + self._requestor.request( + "get", + "/v1/treasury/credit_reversals", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "CreditReversalService.CreateParams", + options: RequestOptions = {}, + ) -> CreditReversal: + """ + Reverses a ReceivedCredit and creates a CreditReversal object. + """ + return cast( + CreditReversal, + self._requestor.request( + "post", + "/v1/treasury/credit_reversals", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + credit_reversal: str, + params: "CreditReversalService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> CreditReversal: + """ + Retrieves the details of an existing CreditReversal by passing the unique CreditReversal ID from either the CreditReversal creation request or CreditReversal list + """ + return cast( + CreditReversal, + self._requestor.request( + "get", + "/v1/treasury/credit_reversals/{credit_reversal}".format( + credit_reversal=_util.sanitize_id(credit_reversal), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/treasury/_debit_reversal.py b/stripe/treasury/_debit_reversal.py index 1651ddf1e..4fad59850 100644 --- a/stripe/treasury/_debit_reversal.py +++ b/stripe/treasury/_debit_reversal.py @@ -151,14 +151,7 @@ class RetrieveParams(RequestOptions): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "DebitReversal.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["DebitReversal.CreateParams"] ) -> "DebitReversal": """ Reverses a ReceivedDebit and creates a DebitReversal object. @@ -168,23 +161,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "DebitReversal.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["DebitReversal.ListParams"] ) -> ListObject["DebitReversal"]: """ Returns a list of DebitReversals. @@ -192,9 +175,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/treasury/_debit_reversal_service.py b/stripe/treasury/_debit_reversal_service.py new file mode 100644 index 000000000..6e6d81763 --- /dev/null +++ b/stripe/treasury/_debit_reversal_service.py @@ -0,0 +1,128 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._debit_reversal import DebitReversal +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class DebitReversalService(StripeService): + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + received_debit: str + """ + The ReceivedDebit to reverse. + """ + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + Returns objects associated with this FinancialAccount. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + received_debit: NotRequired["str"] + """ + Only return DebitReversals for the ReceivedDebit ID. + """ + resolution: NotRequired["Literal['lost', 'won']"] + """ + Only return DebitReversals for a given resolution. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired["Literal['canceled', 'completed', 'processing']"] + """ + Only return DebitReversals for a given status. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "DebitReversalService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[DebitReversal]: + """ + Returns a list of DebitReversals. + """ + return cast( + ListObject[DebitReversal], + self._requestor.request( + "get", + "/v1/treasury/debit_reversals", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "DebitReversalService.CreateParams", + options: RequestOptions = {}, + ) -> DebitReversal: + """ + Reverses a ReceivedDebit and creates a DebitReversal object. + """ + return cast( + DebitReversal, + self._requestor.request( + "post", + "/v1/treasury/debit_reversals", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + debit_reversal: str, + params: "DebitReversalService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> DebitReversal: + """ + Retrieves a DebitReversal object. + """ + return cast( + DebitReversal, + self._requestor.request( + "get", + "/v1/treasury/debit_reversals/{debit_reversal}".format( + debit_reversal=_util.sanitize_id(debit_reversal), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/treasury/_financial_account.py b/stripe/treasury/_financial_account.py index bbcbd64a4..2bef0f742 100644 --- a/stripe/treasury/_financial_account.py +++ b/stripe/treasury/_financial_account.py @@ -767,14 +767,7 @@ class UpdateFeaturesParamsOutboundTransfersUsDomesticWire(TypedDict): @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "FinancialAccount.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["FinancialAccount.CreateParams"] ) -> "FinancialAccount": """ Creates a new FinancialAccount. For now, each connected account can only have one FinancialAccount. @@ -784,23 +777,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "FinancialAccount.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["FinancialAccount.ListParams"] ) -> ListObject["FinancialAccount"]: """ Returns a list of FinancialAccounts. @@ -808,9 +791,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -850,12 +830,7 @@ def retrieve( def _cls_retrieve_features( cls, financial_account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "FinancialAccount.RetrieveFeaturesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["FinancialAccount.RetrieveFeaturesParams"] ) -> "FinancialAccountFeatures": """ Retrieves Features information associated with the FinancialAccount. @@ -867,9 +842,6 @@ def _cls_retrieve_features( "/v1/treasury/financial_accounts/{financial_account}/features".format( financial_account=_util.sanitize_id(financial_account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -878,12 +850,7 @@ def _cls_retrieve_features( @staticmethod def retrieve_features( financial_account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "FinancialAccount.RetrieveFeaturesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["FinancialAccount.RetrieveFeaturesParams"] ) -> "FinancialAccountFeatures": """ Retrieves Features information associated with the FinancialAccount. @@ -892,11 +859,7 @@ def retrieve_features( @overload def retrieve_features( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "FinancialAccount.RetrieveFeaturesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["FinancialAccount.RetrieveFeaturesParams"] ) -> "FinancialAccountFeatures": """ Retrieves Features information associated with the FinancialAccount. @@ -905,11 +868,7 @@ def retrieve_features( @class_method_variant("_cls_retrieve_features") def retrieve_features( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "FinancialAccount.RetrieveFeaturesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["FinancialAccount.RetrieveFeaturesParams"] ) -> "FinancialAccountFeatures": """ Retrieves Features information associated with the FinancialAccount. @@ -921,7 +880,6 @@ def retrieve_features( # pyright: ignore[reportGeneralTypeIssues] "/v1/treasury/financial_accounts/{financial_account}/features".format( financial_account=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -930,12 +888,7 @@ def retrieve_features( # pyright: ignore[reportGeneralTypeIssues] def _cls_update_features( cls, financial_account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "FinancialAccount.UpdateFeaturesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["FinancialAccount.UpdateFeaturesParams"] ) -> "FinancialAccountFeatures": """ Updates the Features associated with a FinancialAccount. @@ -947,9 +900,6 @@ def _cls_update_features( "/v1/treasury/financial_accounts/{financial_account}/features".format( financial_account=_util.sanitize_id(financial_account) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -958,12 +908,7 @@ def _cls_update_features( @staticmethod def update_features( financial_account: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "FinancialAccount.UpdateFeaturesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["FinancialAccount.UpdateFeaturesParams"] ) -> "FinancialAccountFeatures": """ Updates the Features associated with a FinancialAccount. @@ -972,11 +917,7 @@ def update_features( @overload def update_features( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "FinancialAccount.UpdateFeaturesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["FinancialAccount.UpdateFeaturesParams"] ) -> "FinancialAccountFeatures": """ Updates the Features associated with a FinancialAccount. @@ -985,11 +926,7 @@ def update_features( @class_method_variant("_cls_update_features") def update_features( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "FinancialAccount.UpdateFeaturesParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["FinancialAccount.UpdateFeaturesParams"] ) -> "FinancialAccountFeatures": """ Updates the Features associated with a FinancialAccount. @@ -1001,7 +938,6 @@ def update_features( # pyright: ignore[reportGeneralTypeIssues] "/v1/treasury/financial_accounts/{financial_account}/features".format( financial_account=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/treasury/_financial_account_features_service.py b/stripe/treasury/_financial_account_features_service.py new file mode 100644 index 000000000..3a0ec8c3d --- /dev/null +++ b/stripe/treasury/_financial_account_features_service.py @@ -0,0 +1,210 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._financial_account_features import ( + FinancialAccountFeatures, +) +from typing import List, cast +from typing_extensions import NotRequired, TypedDict + + +class FinancialAccountFeaturesService(StripeService): + class CreateParams(TypedDict): + card_issuing: NotRequired[ + "FinancialAccountFeaturesService.CreateParamsCardIssuing" + ] + """ + Encodes the FinancialAccount's ability to be used with the Issuing product, including attaching cards to and drawing funds from the FinancialAccount. + """ + deposit_insurance: NotRequired[ + "FinancialAccountFeaturesService.CreateParamsDepositInsurance" + ] + """ + Represents whether this FinancialAccount is eligible for deposit insurance. Various factors determine the insurance amount. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_addresses: NotRequired[ + "FinancialAccountFeaturesService.CreateParamsFinancialAddresses" + ] + """ + Contains Features that add FinancialAddresses to the FinancialAccount. + """ + inbound_transfers: NotRequired[ + "FinancialAccountFeaturesService.CreateParamsInboundTransfers" + ] + """ + Contains settings related to adding funds to a FinancialAccount from another Account with the same owner. + """ + intra_stripe_flows: NotRequired[ + "FinancialAccountFeaturesService.CreateParamsIntraStripeFlows" + ] + """ + Represents the ability for the FinancialAccount to send money to, or receive money from other FinancialAccounts (for example, via OutboundPayment). + """ + outbound_payments: NotRequired[ + "FinancialAccountFeaturesService.CreateParamsOutboundPayments" + ] + """ + Includes Features related to initiating money movement out of the FinancialAccount to someone else's bucket of money. + """ + outbound_transfers: NotRequired[ + "FinancialAccountFeaturesService.CreateParamsOutboundTransfers" + ] + """ + Contains a Feature and settings related to moving money out of the FinancialAccount into another Account with the same owner. + """ + + class CreateParamsCardIssuing(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsDepositInsurance(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsFinancialAddresses(TypedDict): + aba: NotRequired[ + "FinancialAccountFeaturesService.CreateParamsFinancialAddressesAba" + ] + """ + Adds an ABA FinancialAddress to the FinancialAccount. + """ + + class CreateParamsFinancialAddressesAba(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsInboundTransfers(TypedDict): + ach: NotRequired[ + "FinancialAccountFeaturesService.CreateParamsInboundTransfersAch" + ] + """ + Enables ACH Debits via the InboundTransfers API. + """ + + class CreateParamsInboundTransfersAch(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsIntraStripeFlows(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsOutboundPayments(TypedDict): + ach: NotRequired[ + "FinancialAccountFeaturesService.CreateParamsOutboundPaymentsAch" + ] + """ + Enables ACH transfers via the OutboundPayments API. + """ + us_domestic_wire: NotRequired[ + "FinancialAccountFeaturesService.CreateParamsOutboundPaymentsUsDomesticWire" + ] + """ + Enables US domestic wire transfers via the OutboundPayments API. + """ + + class CreateParamsOutboundPaymentsAch(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsOutboundPaymentsUsDomesticWire(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsOutboundTransfers(TypedDict): + ach: NotRequired[ + "FinancialAccountFeaturesService.CreateParamsOutboundTransfersAch" + ] + """ + Enables ACH transfers via the OutboundTransfers API. + """ + us_domestic_wire: NotRequired[ + "FinancialAccountFeaturesService.CreateParamsOutboundTransfersUsDomesticWire" + ] + """ + Enables US domestic wire transfers via the OutboundTransfers API. + """ + + class CreateParamsOutboundTransfersAch(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsOutboundTransfersUsDomesticWire(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class ListParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def create( + self, + financial_account: str, + params: "FinancialAccountFeaturesService.CreateParams" = {}, + options: RequestOptions = {}, + ) -> FinancialAccountFeatures: + """ + Updates the Features associated with a FinancialAccount. + """ + return cast( + FinancialAccountFeatures, + self._requestor.request( + "post", + "/v1/treasury/financial_accounts/{financial_account}/features".format( + financial_account=_util.sanitize_id(financial_account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def list( + self, + financial_account: str, + params: "FinancialAccountFeaturesService.ListParams" = {}, + options: RequestOptions = {}, + ) -> FinancialAccountFeatures: + """ + Retrieves Features information associated with the FinancialAccount. + """ + return cast( + FinancialAccountFeatures, + self._requestor.request( + "get", + "/v1/treasury/financial_accounts/{financial_account}/features".format( + financial_account=_util.sanitize_id(financial_account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/treasury/_financial_account_service.py b/stripe/treasury/_financial_account_service.py new file mode 100644 index 000000000..60ec8e7d3 --- /dev/null +++ b/stripe/treasury/_financial_account_service.py @@ -0,0 +1,495 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._financial_account import FinancialAccount +from stripe.treasury._financial_account_features_service import ( + FinancialAccountFeaturesService, +) +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class FinancialAccountService(StripeService): + def __init__(self, requestor): + super().__init__(requestor) + self.features = FinancialAccountFeaturesService(self._requestor) + + class CreateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + features: NotRequired["FinancialAccountService.CreateParamsFeatures"] + """ + Encodes whether a FinancialAccount has access to a particular feature. Stripe or the platform can control features via the requested field. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + platform_restrictions: NotRequired[ + "FinancialAccountService.CreateParamsPlatformRestrictions" + ] + """ + The set of functionalities that the platform can restrict on the FinancialAccount. + """ + supported_currencies: List[str] + """ + The currencies the FinancialAccount can hold a balance in. + """ + + class CreateParamsFeatures(TypedDict): + card_issuing: NotRequired[ + "FinancialAccountService.CreateParamsFeaturesCardIssuing" + ] + """ + Encodes the FinancialAccount's ability to be used with the Issuing product, including attaching cards to and drawing funds from the FinancialAccount. + """ + deposit_insurance: NotRequired[ + "FinancialAccountService.CreateParamsFeaturesDepositInsurance" + ] + """ + Represents whether this FinancialAccount is eligible for deposit insurance. Various factors determine the insurance amount. + """ + financial_addresses: NotRequired[ + "FinancialAccountService.CreateParamsFeaturesFinancialAddresses" + ] + """ + Contains Features that add FinancialAddresses to the FinancialAccount. + """ + inbound_transfers: NotRequired[ + "FinancialAccountService.CreateParamsFeaturesInboundTransfers" + ] + """ + Contains settings related to adding funds to a FinancialAccount from another Account with the same owner. + """ + intra_stripe_flows: NotRequired[ + "FinancialAccountService.CreateParamsFeaturesIntraStripeFlows" + ] + """ + Represents the ability for the FinancialAccount to send money to, or receive money from other FinancialAccounts (for example, via OutboundPayment). + """ + outbound_payments: NotRequired[ + "FinancialAccountService.CreateParamsFeaturesOutboundPayments" + ] + """ + Includes Features related to initiating money movement out of the FinancialAccount to someone else's bucket of money. + """ + outbound_transfers: NotRequired[ + "FinancialAccountService.CreateParamsFeaturesOutboundTransfers" + ] + """ + Contains a Feature and settings related to moving money out of the FinancialAccount into another Account with the same owner. + """ + + class CreateParamsFeaturesCardIssuing(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsFeaturesDepositInsurance(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsFeaturesFinancialAddresses(TypedDict): + aba: NotRequired[ + "FinancialAccountService.CreateParamsFeaturesFinancialAddressesAba" + ] + """ + Adds an ABA FinancialAddress to the FinancialAccount. + """ + + class CreateParamsFeaturesFinancialAddressesAba(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsFeaturesInboundTransfers(TypedDict): + ach: NotRequired[ + "FinancialAccountService.CreateParamsFeaturesInboundTransfersAch" + ] + """ + Enables ACH Debits via the InboundTransfers API. + """ + + class CreateParamsFeaturesInboundTransfersAch(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsFeaturesIntraStripeFlows(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsFeaturesOutboundPayments(TypedDict): + ach: NotRequired[ + "FinancialAccountService.CreateParamsFeaturesOutboundPaymentsAch" + ] + """ + Enables ACH transfers via the OutboundPayments API. + """ + us_domestic_wire: NotRequired[ + "FinancialAccountService.CreateParamsFeaturesOutboundPaymentsUsDomesticWire" + ] + """ + Enables US domestic wire transfers via the OutboundPayments API. + """ + + class CreateParamsFeaturesOutboundPaymentsAch(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsFeaturesOutboundPaymentsUsDomesticWire(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsFeaturesOutboundTransfers(TypedDict): + ach: NotRequired[ + "FinancialAccountService.CreateParamsFeaturesOutboundTransfersAch" + ] + """ + Enables ACH transfers via the OutboundTransfers API. + """ + us_domestic_wire: NotRequired[ + "FinancialAccountService.CreateParamsFeaturesOutboundTransfersUsDomesticWire" + ] + """ + Enables US domestic wire transfers via the OutboundTransfers API. + """ + + class CreateParamsFeaturesOutboundTransfersAch(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsFeaturesOutboundTransfersUsDomesticWire(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class CreateParamsPlatformRestrictions(TypedDict): + inbound_flows: NotRequired["Literal['restricted', 'unrestricted']"] + """ + Restricts all inbound money movement. + """ + outbound_flows: NotRequired["Literal['restricted', 'unrestricted']"] + """ + Restricts all outbound money movement. + """ + + class ListParams(TypedDict): + created: NotRequired["FinancialAccountService.ListParamsCreated|int"] + ending_before: NotRequired["str"] + """ + An object ID cursor for use in pagination. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + limit: NotRequired["int"] + """ + A limit ranging from 1 to 100 (defaults to 10). + """ + starting_after: NotRequired["str"] + """ + An object ID cursor for use in pagination. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class UpdateParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + features: NotRequired["FinancialAccountService.UpdateParamsFeatures"] + """ + Encodes whether a FinancialAccount has access to a particular feature, with a status enum and associated `status_details`. Stripe or the platform may control features via the requested field. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + platform_restrictions: NotRequired[ + "FinancialAccountService.UpdateParamsPlatformRestrictions" + ] + """ + The set of functionalities that the platform can restrict on the FinancialAccount. + """ + + class UpdateParamsFeatures(TypedDict): + card_issuing: NotRequired[ + "FinancialAccountService.UpdateParamsFeaturesCardIssuing" + ] + """ + Encodes the FinancialAccount's ability to be used with the Issuing product, including attaching cards to and drawing funds from the FinancialAccount. + """ + deposit_insurance: NotRequired[ + "FinancialAccountService.UpdateParamsFeaturesDepositInsurance" + ] + """ + Represents whether this FinancialAccount is eligible for deposit insurance. Various factors determine the insurance amount. + """ + financial_addresses: NotRequired[ + "FinancialAccountService.UpdateParamsFeaturesFinancialAddresses" + ] + """ + Contains Features that add FinancialAddresses to the FinancialAccount. + """ + inbound_transfers: NotRequired[ + "FinancialAccountService.UpdateParamsFeaturesInboundTransfers" + ] + """ + Contains settings related to adding funds to a FinancialAccount from another Account with the same owner. + """ + intra_stripe_flows: NotRequired[ + "FinancialAccountService.UpdateParamsFeaturesIntraStripeFlows" + ] + """ + Represents the ability for the FinancialAccount to send money to, or receive money from other FinancialAccounts (for example, via OutboundPayment). + """ + outbound_payments: NotRequired[ + "FinancialAccountService.UpdateParamsFeaturesOutboundPayments" + ] + """ + Includes Features related to initiating money movement out of the FinancialAccount to someone else's bucket of money. + """ + outbound_transfers: NotRequired[ + "FinancialAccountService.UpdateParamsFeaturesOutboundTransfers" + ] + """ + Contains a Feature and settings related to moving money out of the FinancialAccount into another Account with the same owner. + """ + + class UpdateParamsFeaturesCardIssuing(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class UpdateParamsFeaturesDepositInsurance(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class UpdateParamsFeaturesFinancialAddresses(TypedDict): + aba: NotRequired[ + "FinancialAccountService.UpdateParamsFeaturesFinancialAddressesAba" + ] + """ + Adds an ABA FinancialAddress to the FinancialAccount. + """ + + class UpdateParamsFeaturesFinancialAddressesAba(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class UpdateParamsFeaturesInboundTransfers(TypedDict): + ach: NotRequired[ + "FinancialAccountService.UpdateParamsFeaturesInboundTransfersAch" + ] + """ + Enables ACH Debits via the InboundTransfers API. + """ + + class UpdateParamsFeaturesInboundTransfersAch(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class UpdateParamsFeaturesIntraStripeFlows(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class UpdateParamsFeaturesOutboundPayments(TypedDict): + ach: NotRequired[ + "FinancialAccountService.UpdateParamsFeaturesOutboundPaymentsAch" + ] + """ + Enables ACH transfers via the OutboundPayments API. + """ + us_domestic_wire: NotRequired[ + "FinancialAccountService.UpdateParamsFeaturesOutboundPaymentsUsDomesticWire" + ] + """ + Enables US domestic wire transfers via the OutboundPayments API. + """ + + class UpdateParamsFeaturesOutboundPaymentsAch(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class UpdateParamsFeaturesOutboundPaymentsUsDomesticWire(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class UpdateParamsFeaturesOutboundTransfers(TypedDict): + ach: NotRequired[ + "FinancialAccountService.UpdateParamsFeaturesOutboundTransfersAch" + ] + """ + Enables ACH transfers via the OutboundTransfers API. + """ + us_domestic_wire: NotRequired[ + "FinancialAccountService.UpdateParamsFeaturesOutboundTransfersUsDomesticWire" + ] + """ + Enables US domestic wire transfers via the OutboundTransfers API. + """ + + class UpdateParamsFeaturesOutboundTransfersAch(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class UpdateParamsFeaturesOutboundTransfersUsDomesticWire(TypedDict): + requested: bool + """ + Whether the FinancialAccount should have the Feature. + """ + + class UpdateParamsPlatformRestrictions(TypedDict): + inbound_flows: NotRequired["Literal['restricted', 'unrestricted']"] + """ + Restricts all inbound money movement. + """ + outbound_flows: NotRequired["Literal['restricted', 'unrestricted']"] + """ + Restricts all outbound money movement. + """ + + def list( + self, + params: "FinancialAccountService.ListParams" = {}, + options: RequestOptions = {}, + ) -> ListObject[FinancialAccount]: + """ + Returns a list of FinancialAccounts. + """ + return cast( + ListObject[FinancialAccount], + self._requestor.request( + "get", + "/v1/treasury/financial_accounts", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "FinancialAccountService.CreateParams", + options: RequestOptions = {}, + ) -> FinancialAccount: + """ + Creates a new FinancialAccount. For now, each connected account can only have one FinancialAccount. + """ + return cast( + FinancialAccount, + self._requestor.request( + "post", + "/v1/treasury/financial_accounts", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + financial_account: str, + params: "FinancialAccountService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> FinancialAccount: + """ + Retrieves the details of a FinancialAccount. + """ + return cast( + FinancialAccount, + self._requestor.request( + "get", + "/v1/treasury/financial_accounts/{financial_account}".format( + financial_account=_util.sanitize_id(financial_account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def update( + self, + financial_account: str, + params: "FinancialAccountService.UpdateParams" = {}, + options: RequestOptions = {}, + ) -> FinancialAccount: + """ + Updates the details of a FinancialAccount. + """ + return cast( + FinancialAccount, + self._requestor.request( + "post", + "/v1/treasury/financial_accounts/{financial_account}".format( + financial_account=_util.sanitize_id(financial_account), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/treasury/_inbound_transfer.py b/stripe/treasury/_inbound_transfer.py index f8ba3f1c1..033bfb999 100644 --- a/stripe/treasury/_inbound_transfer.py +++ b/stripe/treasury/_inbound_transfer.py @@ -340,12 +340,7 @@ class SucceedParams(RequestOptions): def _cls_cancel( cls, inbound_transfer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["InboundTransfer.CancelParams"] ) -> "InboundTransfer": """ Cancels an InboundTransfer. @@ -357,9 +352,6 @@ def _cls_cancel( "/v1/treasury/inbound_transfers/{inbound_transfer}/cancel".format( inbound_transfer=_util.sanitize_id(inbound_transfer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -367,13 +359,7 @@ def _cls_cancel( @overload @staticmethod def cancel( - inbound_transfer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + inbound_transfer: str, **params: Unpack["InboundTransfer.CancelParams"] ) -> "InboundTransfer": """ Cancels an InboundTransfer. @@ -382,11 +368,7 @@ def cancel( @overload def cancel( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["InboundTransfer.CancelParams"] ) -> "InboundTransfer": """ Cancels an InboundTransfer. @@ -395,11 +377,7 @@ def cancel( @class_method_variant("_cls_cancel") def cancel( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["InboundTransfer.CancelParams"] ) -> "InboundTransfer": """ Cancels an InboundTransfer. @@ -411,21 +389,13 @@ def cancel( # pyright: ignore[reportGeneralTypeIssues] "/v1/treasury/inbound_transfers/{inbound_transfer}/cancel".format( inbound_transfer=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["InboundTransfer.CreateParams"] ) -> "InboundTransfer": """ Creates an InboundTransfer. @@ -435,23 +405,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["InboundTransfer.ListParams"] ) -> ListObject["InboundTransfer"]: """ Returns a list of InboundTransfers sent from the specified FinancialAccount. @@ -459,9 +419,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -489,14 +446,7 @@ class TestHelpers(APIResourceTestHelpers["InboundTransfer"]): @classmethod def _cls_fail( - cls, - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.FailParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, id: str, **params: Unpack["InboundTransfer.FailParams"] ) -> "InboundTransfer": """ Transitions a test mode created InboundTransfer to the failed status. The InboundTransfer must already be in the processing state. @@ -508,9 +458,6 @@ def _cls_fail( "/v1/test_helpers/treasury/inbound_transfers/{id}/fail".format( id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -518,13 +465,7 @@ def _cls_fail( @overload @staticmethod def fail( - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.FailParams" - ] # pyright: ignore[reportGeneralTypeIssues] + id: str, **params: Unpack["InboundTransfer.FailParams"] ) -> "InboundTransfer": """ Transitions a test mode created InboundTransfer to the failed status. The InboundTransfer must already be in the processing state. @@ -533,11 +474,7 @@ def fail( @overload def fail( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.FailParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["InboundTransfer.FailParams"] ) -> "InboundTransfer": """ Transitions a test mode created InboundTransfer to the failed status. The InboundTransfer must already be in the processing state. @@ -546,11 +483,7 @@ def fail( @class_method_variant("_cls_fail") def fail( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.FailParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["InboundTransfer.FailParams"] ) -> "InboundTransfer": """ Transitions a test mode created InboundTransfer to the failed status. The InboundTransfer must already be in the processing state. @@ -562,7 +495,6 @@ def fail( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/treasury/inbound_transfers/{id}/fail".format( id=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -571,12 +503,7 @@ def fail( # pyright: ignore[reportGeneralTypeIssues] def _cls_return_inbound_transfer( cls, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.ReturnInboundTransferParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["InboundTransfer.ReturnInboundTransferParams"] ) -> "InboundTransfer": """ Marks the test mode InboundTransfer object as returned and links the InboundTransfer to a ReceivedDebit. The InboundTransfer must already be in the succeeded state. @@ -588,9 +515,6 @@ def _cls_return_inbound_transfer( "/v1/test_helpers/treasury/inbound_transfers/{id}/return".format( id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -599,12 +523,7 @@ def _cls_return_inbound_transfer( @staticmethod def return_inbound_transfer( id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.ReturnInboundTransferParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["InboundTransfer.ReturnInboundTransferParams"] ) -> "InboundTransfer": """ Marks the test mode InboundTransfer object as returned and links the InboundTransfer to a ReceivedDebit. The InboundTransfer must already be in the succeeded state. @@ -614,10 +533,7 @@ def return_inbound_transfer( @overload def return_inbound_transfer( self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.ReturnInboundTransferParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["InboundTransfer.ReturnInboundTransferParams"] ) -> "InboundTransfer": """ Marks the test mode InboundTransfer object as returned and links the InboundTransfer to a ReceivedDebit. The InboundTransfer must already be in the succeeded state. @@ -627,10 +543,7 @@ def return_inbound_transfer( @class_method_variant("_cls_return_inbound_transfer") def return_inbound_transfer( # pyright: ignore[reportGeneralTypeIssues] self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.ReturnInboundTransferParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["InboundTransfer.ReturnInboundTransferParams"] ) -> "InboundTransfer": """ Marks the test mode InboundTransfer object as returned and links the InboundTransfer to a ReceivedDebit. The InboundTransfer must already be in the succeeded state. @@ -642,21 +555,13 @@ def return_inbound_transfer( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/treasury/inbound_transfers/{id}/return".format( id=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_succeed( - cls, - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.SucceedParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, id: str, **params: Unpack["InboundTransfer.SucceedParams"] ) -> "InboundTransfer": """ Transitions a test mode created InboundTransfer to the succeeded status. The InboundTransfer must already be in the processing state. @@ -668,9 +573,6 @@ def _cls_succeed( "/v1/test_helpers/treasury/inbound_transfers/{id}/succeed".format( id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -678,13 +580,7 @@ def _cls_succeed( @overload @staticmethod def succeed( - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.SucceedParams" - ] # pyright: ignore[reportGeneralTypeIssues] + id: str, **params: Unpack["InboundTransfer.SucceedParams"] ) -> "InboundTransfer": """ Transitions a test mode created InboundTransfer to the succeeded status. The InboundTransfer must already be in the processing state. @@ -693,11 +589,7 @@ def succeed( @overload def succeed( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.SucceedParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["InboundTransfer.SucceedParams"] ) -> "InboundTransfer": """ Transitions a test mode created InboundTransfer to the succeeded status. The InboundTransfer must already be in the processing state. @@ -706,11 +598,7 @@ def succeed( @class_method_variant("_cls_succeed") def succeed( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "InboundTransfer.SucceedParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["InboundTransfer.SucceedParams"] ) -> "InboundTransfer": """ Transitions a test mode created InboundTransfer to the succeeded status. The InboundTransfer must already be in the processing state. @@ -722,7 +610,6 @@ def succeed( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/treasury/inbound_transfers/{id}/succeed".format( id=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/treasury/_inbound_transfer_service.py b/stripe/treasury/_inbound_transfer_service.py new file mode 100644 index 000000000..9b3459006 --- /dev/null +++ b/stripe/treasury/_inbound_transfer_service.py @@ -0,0 +1,171 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._inbound_transfer import InboundTransfer +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class InboundTransferService(StripeService): + class CancelParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CreateParams(TypedDict): + amount: int + """ + Amount (in cents) to be transferred. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + The FinancialAccount to send funds to. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + origin_payment_method: str + """ + The origin payment method to be debited for the InboundTransfer. + """ + statement_descriptor: NotRequired["str"] + """ + The complete description that appears on your customers' statements. Maximum 10 characters. + """ + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + Returns objects associated with this FinancialAccount. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired[ + "Literal['canceled', 'failed', 'processing', 'succeeded']" + ] + """ + Only return InboundTransfers that have the given status: `processing`, `succeeded`, `failed` or `canceled`. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "InboundTransferService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[InboundTransfer]: + """ + Returns a list of InboundTransfers sent from the specified FinancialAccount. + """ + return cast( + ListObject[InboundTransfer], + self._requestor.request( + "get", + "/v1/treasury/inbound_transfers", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "InboundTransferService.CreateParams", + options: RequestOptions = {}, + ) -> InboundTransfer: + """ + Creates an InboundTransfer. + """ + return cast( + InboundTransfer, + self._requestor.request( + "post", + "/v1/treasury/inbound_transfers", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + id: str, + params: "InboundTransferService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> InboundTransfer: + """ + Retrieves the details of an existing InboundTransfer. + """ + return cast( + InboundTransfer, + self._requestor.request( + "get", + "/v1/treasury/inbound_transfers/{id}".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def cancel( + self, + inbound_transfer: str, + params: "InboundTransferService.CancelParams" = {}, + options: RequestOptions = {}, + ) -> InboundTransfer: + """ + Cancels an InboundTransfer. + """ + return cast( + InboundTransfer, + self._requestor.request( + "post", + "/v1/treasury/inbound_transfers/{inbound_transfer}/cancel".format( + inbound_transfer=_util.sanitize_id(inbound_transfer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/treasury/_outbound_payment.py b/stripe/treasury/_outbound_payment.py index 388fb357c..8ee13ed5a 100644 --- a/stripe/treasury/_outbound_payment.py +++ b/stripe/treasury/_outbound_payment.py @@ -516,14 +516,7 @@ class ReturnOutboundPaymentParamsReturnedDetails(TypedDict): @classmethod def _cls_cancel( - cls, - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, id: str, **params: Unpack["OutboundPayment.CancelParams"] ) -> "OutboundPayment": """ Cancel an OutboundPayment. @@ -535,9 +528,6 @@ def _cls_cancel( "/v1/treasury/outbound_payments/{id}/cancel".format( id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -545,13 +535,7 @@ def _cls_cancel( @overload @staticmethod def cancel( - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + id: str, **params: Unpack["OutboundPayment.CancelParams"] ) -> "OutboundPayment": """ Cancel an OutboundPayment. @@ -560,11 +544,7 @@ def cancel( @overload def cancel( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["OutboundPayment.CancelParams"] ) -> "OutboundPayment": """ Cancel an OutboundPayment. @@ -573,11 +553,7 @@ def cancel( @class_method_variant("_cls_cancel") def cancel( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["OutboundPayment.CancelParams"] ) -> "OutboundPayment": """ Cancel an OutboundPayment. @@ -589,21 +565,13 @@ def cancel( # pyright: ignore[reportGeneralTypeIssues] "/v1/treasury/outbound_payments/{id}/cancel".format( id=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["OutboundPayment.CreateParams"] ) -> "OutboundPayment": """ Creates an OutboundPayment. @@ -613,23 +581,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["OutboundPayment.ListParams"] ) -> ListObject["OutboundPayment"]: """ Returns a list of OutboundPayments sent from the specified FinancialAccount. @@ -637,9 +595,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -667,14 +622,7 @@ class TestHelpers(APIResourceTestHelpers["OutboundPayment"]): @classmethod def _cls_fail( - cls, - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.FailParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, id: str, **params: Unpack["OutboundPayment.FailParams"] ) -> "OutboundPayment": """ Transitions a test mode created OutboundPayment to the failed status. The OutboundPayment must already be in the processing state. @@ -686,9 +634,6 @@ def _cls_fail( "/v1/test_helpers/treasury/outbound_payments/{id}/fail".format( id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -696,13 +641,7 @@ def _cls_fail( @overload @staticmethod def fail( - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.FailParams" - ] # pyright: ignore[reportGeneralTypeIssues] + id: str, **params: Unpack["OutboundPayment.FailParams"] ) -> "OutboundPayment": """ Transitions a test mode created OutboundPayment to the failed status. The OutboundPayment must already be in the processing state. @@ -711,11 +650,7 @@ def fail( @overload def fail( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.FailParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["OutboundPayment.FailParams"] ) -> "OutboundPayment": """ Transitions a test mode created OutboundPayment to the failed status. The OutboundPayment must already be in the processing state. @@ -724,11 +659,7 @@ def fail( @class_method_variant("_cls_fail") def fail( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.FailParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["OutboundPayment.FailParams"] ) -> "OutboundPayment": """ Transitions a test mode created OutboundPayment to the failed status. The OutboundPayment must already be in the processing state. @@ -740,21 +671,13 @@ def fail( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/treasury/outbound_payments/{id}/fail".format( id=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def _cls_post( - cls, - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.PostParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, id: str, **params: Unpack["OutboundPayment.PostParams"] ) -> "OutboundPayment": """ Transitions a test mode created OutboundPayment to the posted status. The OutboundPayment must already be in the processing state. @@ -766,9 +689,6 @@ def _cls_post( "/v1/test_helpers/treasury/outbound_payments/{id}/post".format( id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -776,13 +696,7 @@ def _cls_post( @overload @staticmethod def post( - id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.PostParams" - ] # pyright: ignore[reportGeneralTypeIssues] + id: str, **params: Unpack["OutboundPayment.PostParams"] ) -> "OutboundPayment": """ Transitions a test mode created OutboundPayment to the posted status. The OutboundPayment must already be in the processing state. @@ -791,11 +705,7 @@ def post( @overload def post( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.PostParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["OutboundPayment.PostParams"] ) -> "OutboundPayment": """ Transitions a test mode created OutboundPayment to the posted status. The OutboundPayment must already be in the processing state. @@ -804,11 +714,7 @@ def post( @class_method_variant("_cls_post") def post( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.PostParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["OutboundPayment.PostParams"] ) -> "OutboundPayment": """ Transitions a test mode created OutboundPayment to the posted status. The OutboundPayment must already be in the processing state. @@ -820,7 +726,6 @@ def post( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/treasury/outbound_payments/{id}/post".format( id=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -829,12 +734,7 @@ def post( # pyright: ignore[reportGeneralTypeIssues] def _cls_return_outbound_payment( cls, id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.ReturnOutboundPaymentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundPayment.ReturnOutboundPaymentParams"] ) -> "OutboundPayment": """ Transitions a test mode created OutboundPayment to the returned status. The OutboundPayment must already be in the processing state. @@ -846,9 +746,6 @@ def _cls_return_outbound_payment( "/v1/test_helpers/treasury/outbound_payments/{id}/return".format( id=_util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -857,12 +754,7 @@ def _cls_return_outbound_payment( @staticmethod def return_outbound_payment( id: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.ReturnOutboundPaymentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundPayment.ReturnOutboundPaymentParams"] ) -> "OutboundPayment": """ Transitions a test mode created OutboundPayment to the returned status. The OutboundPayment must already be in the processing state. @@ -872,10 +764,7 @@ def return_outbound_payment( @overload def return_outbound_payment( self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.ReturnOutboundPaymentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundPayment.ReturnOutboundPaymentParams"] ) -> "OutboundPayment": """ Transitions a test mode created OutboundPayment to the returned status. The OutboundPayment must already be in the processing state. @@ -885,10 +774,7 @@ def return_outbound_payment( @class_method_variant("_cls_return_outbound_payment") def return_outbound_payment( # pyright: ignore[reportGeneralTypeIssues] self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundPayment.ReturnOutboundPaymentParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundPayment.ReturnOutboundPaymentParams"] ) -> "OutboundPayment": """ Transitions a test mode created OutboundPayment to the returned status. The OutboundPayment must already be in the processing state. @@ -900,7 +786,6 @@ def return_outbound_payment( # pyright: ignore[reportGeneralTypeIssues] "/v1/test_helpers/treasury/outbound_payments/{id}/return".format( id=_util.sanitize_id(self.resource.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/treasury/_outbound_payment_service.py b/stripe/treasury/_outbound_payment_service.py new file mode 100644 index 000000000..4a0610d44 --- /dev/null +++ b/stripe/treasury/_outbound_payment_service.py @@ -0,0 +1,317 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._outbound_payment import OutboundPayment +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class OutboundPaymentService(StripeService): + class CancelParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CreateParams(TypedDict): + amount: int + """ + Amount (in cents) to be transferred. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + customer: NotRequired["str"] + """ + ID of the customer to whom the OutboundPayment is sent. Must match the Customer attached to the `destination_payment_method` passed in. + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + destination_payment_method: NotRequired["str"] + """ + The PaymentMethod to use as the payment instrument for the OutboundPayment. Exclusive with `destination_payment_method_data`. + """ + destination_payment_method_data: NotRequired[ + "OutboundPaymentService.CreateParamsDestinationPaymentMethodData" + ] + """ + Hash used to generate the PaymentMethod to be used for this OutboundPayment. Exclusive with `destination_payment_method`. + """ + destination_payment_method_options: NotRequired[ + "OutboundPaymentService.CreateParamsDestinationPaymentMethodOptions" + ] + """ + Payment method-specific configuration for this OutboundPayment. + """ + end_user_details: NotRequired[ + "OutboundPaymentService.CreateParamsEndUserDetails" + ] + """ + End user details. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + The FinancialAccount to pull funds from. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + statement_descriptor: NotRequired["str"] + """ + The description that appears on the receiving end for this OutboundPayment (for example, bank statement for external bank transfer). Maximum 10 characters for `ach` payments, 140 characters for `us_domestic_wire` payments, or 500 characters for `stripe` network transfers. The default value is "payment". + """ + + class CreateParamsDestinationPaymentMethodData(TypedDict): + billing_details: NotRequired[ + "OutboundPaymentService.CreateParamsDestinationPaymentMethodDataBillingDetails" + ] + """ + Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + """ + financial_account: NotRequired["str"] + """ + Required if type is set to `financial_account`. The FinancialAccount ID to send funds to. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + type: Literal["financial_account", "us_bank_account"] + """ + The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type. + """ + us_bank_account: NotRequired[ + "OutboundPaymentService.CreateParamsDestinationPaymentMethodDataUsBankAccount" + ] + """ + Required hash if type is set to `us_bank_account`. + """ + + class CreateParamsDestinationPaymentMethodDataBillingDetails(TypedDict): + address: NotRequired[ + "Literal['']|OutboundPaymentService.CreateParamsDestinationPaymentMethodDataBillingDetailsAddress" + ] + """ + Billing address. + """ + email: NotRequired["Literal['']|str"] + """ + Email address. + """ + name: NotRequired["Literal['']|str"] + """ + Full name. + """ + phone: NotRequired["Literal['']|str"] + """ + Billing phone number (including extension). + """ + + class CreateParamsDestinationPaymentMethodDataBillingDetailsAddress( + TypedDict, + ): + city: NotRequired["str"] + """ + City, district, suburb, town, or village. + """ + country: NotRequired["str"] + """ + Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + """ + line1: NotRequired["str"] + """ + Address line 1 (e.g., street, PO Box, or company name). + """ + line2: NotRequired["str"] + """ + Address line 2 (e.g., apartment, suite, unit, or building). + """ + postal_code: NotRequired["str"] + """ + ZIP or postal code. + """ + state: NotRequired["str"] + """ + State, county, province, or region. + """ + + class CreateParamsDestinationPaymentMethodDataUsBankAccount(TypedDict): + account_holder_type: NotRequired["Literal['company', 'individual']"] + """ + Account holder type: individual or company. + """ + account_number: NotRequired["str"] + """ + Account number of the bank account. + """ + account_type: NotRequired["Literal['checking', 'savings']"] + """ + Account type: checkings or savings. Defaults to checking if omitted. + """ + financial_connections_account: NotRequired["str"] + """ + The ID of a Financial Connections Account to use as a payment method. + """ + routing_number: NotRequired["str"] + """ + Routing number of the bank account. + """ + + class CreateParamsDestinationPaymentMethodOptions(TypedDict): + us_bank_account: NotRequired[ + "Literal['']|OutboundPaymentService.CreateParamsDestinationPaymentMethodOptionsUsBankAccount" + ] + """ + Optional fields for `us_bank_account`. + """ + + class CreateParamsDestinationPaymentMethodOptionsUsBankAccount(TypedDict): + network: NotRequired["Literal['ach', 'us_domestic_wire']"] + """ + The US bank account network that must be used for this OutboundPayment. If not set, we will default to the PaymentMethod's preferred network. + """ + + class CreateParamsEndUserDetails(TypedDict): + ip_address: NotRequired["str"] + """ + IP address of the user initiating the OutboundPayment. Must be supplied if `present` is set to `true`. + """ + present: bool + """ + `True` if the OutboundPayment creation request is being made on behalf of an end user by a platform. Otherwise, `false`. + """ + + class ListParams(TypedDict): + customer: NotRequired["str"] + """ + Only return OutboundPayments sent to this customer. + """ + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + Returns objects associated with this FinancialAccount. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired[ + "Literal['canceled', 'failed', 'posted', 'processing', 'returned']" + ] + """ + Only return OutboundPayments that have the given status: `processing`, `failed`, `posted`, `returned`, or `canceled`. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "OutboundPaymentService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[OutboundPayment]: + """ + Returns a list of OutboundPayments sent from the specified FinancialAccount. + """ + return cast( + ListObject[OutboundPayment], + self._requestor.request( + "get", + "/v1/treasury/outbound_payments", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "OutboundPaymentService.CreateParams", + options: RequestOptions = {}, + ) -> OutboundPayment: + """ + Creates an OutboundPayment. + """ + return cast( + OutboundPayment, + self._requestor.request( + "post", + "/v1/treasury/outbound_payments", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + id: str, + params: "OutboundPaymentService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> OutboundPayment: + """ + Retrieves the details of an existing OutboundPayment by passing the unique OutboundPayment ID from either the OutboundPayment creation request or OutboundPayment list. + """ + return cast( + OutboundPayment, + self._requestor.request( + "get", + "/v1/treasury/outbound_payments/{id}".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def cancel( + self, + id: str, + params: "OutboundPaymentService.CancelParams" = {}, + options: RequestOptions = {}, + ) -> OutboundPayment: + """ + Cancel an OutboundPayment. + """ + return cast( + OutboundPayment, + self._requestor.request( + "post", + "/v1/treasury/outbound_payments/{id}/cancel".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/treasury/_outbound_transfer.py b/stripe/treasury/_outbound_transfer.py index cbc3a3f71..24c31838e 100644 --- a/stripe/treasury/_outbound_transfer.py +++ b/stripe/treasury/_outbound_transfer.py @@ -357,12 +357,7 @@ class ReturnOutboundTransferParamsReturnedDetails(TypedDict): def _cls_cancel( cls, outbound_transfer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundTransfer.CancelParams"] ) -> "OutboundTransfer": """ An OutboundTransfer can be canceled if the funds have not yet been paid out. @@ -374,9 +369,6 @@ def _cls_cancel( "/v1/treasury/outbound_transfers/{outbound_transfer}/cancel".format( outbound_transfer=_util.sanitize_id(outbound_transfer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -385,12 +377,7 @@ def _cls_cancel( @staticmethod def cancel( outbound_transfer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundTransfer.CancelParams"] ) -> "OutboundTransfer": """ An OutboundTransfer can be canceled if the funds have not yet been paid out. @@ -399,11 +386,7 @@ def cancel( @overload def cancel( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["OutboundTransfer.CancelParams"] ) -> "OutboundTransfer": """ An OutboundTransfer can be canceled if the funds have not yet been paid out. @@ -412,11 +395,7 @@ def cancel( @class_method_variant("_cls_cancel") def cancel( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.CancelParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["OutboundTransfer.CancelParams"] ) -> "OutboundTransfer": """ An OutboundTransfer can be canceled if the funds have not yet been paid out. @@ -428,21 +407,13 @@ def cancel( # pyright: ignore[reportGeneralTypeIssues] "/v1/treasury/outbound_transfers/{outbound_transfer}/cancel".format( outbound_transfer=_util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ), ) @classmethod def create( - cls, - api_key: Optional[str] = None, - idempotency_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["OutboundTransfer.CreateParams"] ) -> "OutboundTransfer": """ Creates an OutboundTransfer. @@ -452,23 +423,13 @@ def create( cls._static_request( "post", cls.class_url(), - api_key, - idempotency_key, - stripe_version, - stripe_account, params, ), ) @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["OutboundTransfer.ListParams"] ) -> ListObject["OutboundTransfer"]: """ Returns a list of OutboundTransfers sent from the specified FinancialAccount. @@ -476,9 +437,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -508,12 +466,7 @@ class TestHelpers(APIResourceTestHelpers["OutboundTransfer"]): def _cls_fail( cls, outbound_transfer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.FailParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundTransfer.FailParams"] ) -> "OutboundTransfer": """ Transitions a test mode created OutboundTransfer to the failed status. The OutboundTransfer must already be in the processing state. @@ -525,9 +478,6 @@ def _cls_fail( "/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/fail".format( outbound_transfer=_util.sanitize_id(outbound_transfer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -536,12 +486,7 @@ def _cls_fail( @staticmethod def fail( outbound_transfer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.FailParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundTransfer.FailParams"] ) -> "OutboundTransfer": """ Transitions a test mode created OutboundTransfer to the failed status. The OutboundTransfer must already be in the processing state. @@ -550,11 +495,7 @@ def fail( @overload def fail( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.FailParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["OutboundTransfer.FailParams"] ) -> "OutboundTransfer": """ Transitions a test mode created OutboundTransfer to the failed status. The OutboundTransfer must already be in the processing state. @@ -563,11 +504,7 @@ def fail( @class_method_variant("_cls_fail") def fail( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.FailParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["OutboundTransfer.FailParams"] ) -> "OutboundTransfer": """ Transitions a test mode created OutboundTransfer to the failed status. The OutboundTransfer must already be in the processing state. @@ -581,7 +518,6 @@ def fail( # pyright: ignore[reportGeneralTypeIssues] self.resource.get("id") ) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -590,12 +526,7 @@ def fail( # pyright: ignore[reportGeneralTypeIssues] def _cls_post( cls, outbound_transfer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.PostParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundTransfer.PostParams"] ) -> "OutboundTransfer": """ Transitions a test mode created OutboundTransfer to the posted status. The OutboundTransfer must already be in the processing state. @@ -607,9 +538,6 @@ def _cls_post( "/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/post".format( outbound_transfer=_util.sanitize_id(outbound_transfer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -618,12 +546,7 @@ def _cls_post( @staticmethod def post( outbound_transfer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.PostParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundTransfer.PostParams"] ) -> "OutboundTransfer": """ Transitions a test mode created OutboundTransfer to the posted status. The OutboundTransfer must already be in the processing state. @@ -632,11 +555,7 @@ def post( @overload def post( - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.PostParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["OutboundTransfer.PostParams"] ) -> "OutboundTransfer": """ Transitions a test mode created OutboundTransfer to the posted status. The OutboundTransfer must already be in the processing state. @@ -645,11 +564,7 @@ def post( @class_method_variant("_cls_post") def post( # pyright: ignore[reportGeneralTypeIssues] - self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.PostParams" - ] # pyright: ignore[reportGeneralTypeIssues] + self, **params: Unpack["OutboundTransfer.PostParams"] ) -> "OutboundTransfer": """ Transitions a test mode created OutboundTransfer to the posted status. The OutboundTransfer must already be in the processing state. @@ -663,7 +578,6 @@ def post( # pyright: ignore[reportGeneralTypeIssues] self.resource.get("id") ) ), - idempotency_key=idempotency_key, params=params, ), ) @@ -672,12 +586,7 @@ def post( # pyright: ignore[reportGeneralTypeIssues] def _cls_return_outbound_transfer( cls, outbound_transfer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.ReturnOutboundTransferParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundTransfer.ReturnOutboundTransferParams"] ) -> "OutboundTransfer": """ Transitions a test mode created OutboundTransfer to the returned status. The OutboundTransfer must already be in the processing state. @@ -689,9 +598,6 @@ def _cls_return_outbound_transfer( "/v1/test_helpers/treasury/outbound_transfers/{outbound_transfer}/return".format( outbound_transfer=_util.sanitize_id(outbound_transfer) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) @@ -700,12 +606,7 @@ def _cls_return_outbound_transfer( @staticmethod def return_outbound_transfer( outbound_transfer: str, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.ReturnOutboundTransferParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundTransfer.ReturnOutboundTransferParams"] ) -> "OutboundTransfer": """ Transitions a test mode created OutboundTransfer to the returned status. The OutboundTransfer must already be in the processing state. @@ -715,10 +616,7 @@ def return_outbound_transfer( @overload def return_outbound_transfer( self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.ReturnOutboundTransferParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundTransfer.ReturnOutboundTransferParams"] ) -> "OutboundTransfer": """ Transitions a test mode created OutboundTransfer to the returned status. The OutboundTransfer must already be in the processing state. @@ -728,10 +626,7 @@ def return_outbound_transfer( @class_method_variant("_cls_return_outbound_transfer") def return_outbound_transfer( # pyright: ignore[reportGeneralTypeIssues] self, - idempotency_key: Optional[str] = None, - **params: Unpack[ - "OutboundTransfer.ReturnOutboundTransferParams" - ] # pyright: ignore[reportGeneralTypeIssues] + **params: Unpack["OutboundTransfer.ReturnOutboundTransferParams"] ) -> "OutboundTransfer": """ Transitions a test mode created OutboundTransfer to the returned status. The OutboundTransfer must already be in the processing state. @@ -745,7 +640,6 @@ def return_outbound_transfer( # pyright: ignore[reportGeneralTypeIssues] self.resource.get("id") ) ), - idempotency_key=idempotency_key, params=params, ), ) diff --git a/stripe/treasury/_outbound_transfer_service.py b/stripe/treasury/_outbound_transfer_service.py new file mode 100644 index 000000000..d59014daa --- /dev/null +++ b/stripe/treasury/_outbound_transfer_service.py @@ -0,0 +1,191 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._outbound_transfer import OutboundTransfer +from typing import Dict, List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class OutboundTransferService(StripeService): + class CancelParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + class CreateParams(TypedDict): + amount: int + """ + Amount (in cents) to be transferred. + """ + currency: str + """ + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + """ + description: NotRequired["str"] + """ + An arbitrary string attached to the object. Often useful for displaying to users. + """ + destination_payment_method: NotRequired["str"] + """ + The PaymentMethod to use as the payment instrument for the OutboundTransfer. + """ + destination_payment_method_options: NotRequired[ + "OutboundTransferService.CreateParamsDestinationPaymentMethodOptions" + ] + """ + Hash describing payment method configuration details. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + The FinancialAccount to pull funds from. + """ + metadata: NotRequired["Dict[str, str]"] + """ + Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + """ + statement_descriptor: NotRequired["str"] + """ + Statement descriptor to be shown on the receiving end of an OutboundTransfer. Maximum 10 characters for `ach` transfers or 140 characters for `us_domestic_wire` transfers. The default value is "transfer". + """ + + class CreateParamsDestinationPaymentMethodOptions(TypedDict): + us_bank_account: NotRequired[ + "Literal['']|OutboundTransferService.CreateParamsDestinationPaymentMethodOptionsUsBankAccount" + ] + """ + Optional fields for `us_bank_account`. + """ + + class CreateParamsDestinationPaymentMethodOptionsUsBankAccount(TypedDict): + network: NotRequired["Literal['ach', 'us_domestic_wire']"] + """ + Designate the OutboundTransfer as using a US bank account network configuration. + """ + + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + Returns objects associated with this FinancialAccount. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired[ + "Literal['canceled', 'failed', 'posted', 'processing', 'returned']" + ] + """ + Only return OutboundTransfers that have the given status: `processing`, `canceled`, `failed`, `posted`, or `returned`. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "OutboundTransferService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[OutboundTransfer]: + """ + Returns a list of OutboundTransfers sent from the specified FinancialAccount. + """ + return cast( + ListObject[OutboundTransfer], + self._requestor.request( + "get", + "/v1/treasury/outbound_transfers", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def create( + self, + params: "OutboundTransferService.CreateParams", + options: RequestOptions = {}, + ) -> OutboundTransfer: + """ + Creates an OutboundTransfer. + """ + return cast( + OutboundTransfer, + self._requestor.request( + "post", + "/v1/treasury/outbound_transfers", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + outbound_transfer: str, + params: "OutboundTransferService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> OutboundTransfer: + """ + Retrieves the details of an existing OutboundTransfer by passing the unique OutboundTransfer ID from either the OutboundTransfer creation request or OutboundTransfer list. + """ + return cast( + OutboundTransfer, + self._requestor.request( + "get", + "/v1/treasury/outbound_transfers/{outbound_transfer}".format( + outbound_transfer=_util.sanitize_id(outbound_transfer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def cancel( + self, + outbound_transfer: str, + params: "OutboundTransferService.CancelParams" = {}, + options: RequestOptions = {}, + ) -> OutboundTransfer: + """ + An OutboundTransfer can be canceled if the funds have not yet been paid out. + """ + return cast( + OutboundTransfer, + self._requestor.request( + "post", + "/v1/treasury/outbound_transfers/{outbound_transfer}/cancel".format( + outbound_transfer=_util.sanitize_id(outbound_transfer), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/treasury/_received_credit.py b/stripe/treasury/_received_credit.py index 618d9f0b9..49db0ccef 100644 --- a/stripe/treasury/_received_credit.py +++ b/stripe/treasury/_received_credit.py @@ -361,13 +361,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ReceivedCredit.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ReceivedCredit.ListParams"] ) -> ListObject["ReceivedCredit"]: """ Returns a list of ReceivedCredits. @@ -375,9 +369,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -405,13 +396,7 @@ class TestHelpers(APIResourceTestHelpers["ReceivedCredit"]): @classmethod def create( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ReceivedCredit.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ReceivedCredit.CreateParams"] ) -> "ReceivedCredit": """ Use this endpoint to simulate a test mode ReceivedCredit initiated by a third party. In live mode, you can't directly create ReceivedCredits initiated by third parties. @@ -421,9 +406,6 @@ def create( cls._static_request( "post", "/v1/test_helpers/treasury/received_credits", - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) diff --git a/stripe/treasury/_received_credit_service.py b/stripe/treasury/_received_credit_service.py new file mode 100644 index 000000000..f1668b350 --- /dev/null +++ b/stripe/treasury/_received_credit_service.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._received_credit import ReceivedCredit +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ReceivedCreditService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + The FinancialAccount that received the funds. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + linked_flows: NotRequired[ + "ReceivedCreditService.ListParamsLinkedFlows" + ] + """ + Only return ReceivedCredits described by the flow. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired["Literal['failed', 'succeeded']"] + """ + Only return ReceivedCredits that have the given status: `succeeded` or `failed`. + """ + + class ListParamsLinkedFlows(TypedDict): + source_flow_type: Literal[ + "credit_reversal", "other", "outbound_payment", "payout" + ] + """ + The source flow type. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "ReceivedCreditService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[ReceivedCredit]: + """ + Returns a list of ReceivedCredits. + """ + return cast( + ListObject[ReceivedCredit], + self._requestor.request( + "get", + "/v1/treasury/received_credits", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + id: str, + params: "ReceivedCreditService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> ReceivedCredit: + """ + Retrieves the details of an existing ReceivedCredit by passing the unique ReceivedCredit ID from the ReceivedCredit list. + """ + return cast( + ReceivedCredit, + self._requestor.request( + "get", + "/v1/treasury/received_credits/{id}".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/treasury/_received_debit.py b/stripe/treasury/_received_debit.py index 61108023c..d5541bb6a 100644 --- a/stripe/treasury/_received_debit.py +++ b/stripe/treasury/_received_debit.py @@ -310,13 +310,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ReceivedDebit.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ReceivedDebit.ListParams"] ) -> ListObject["ReceivedDebit"]: """ Returns a list of ReceivedDebits. @@ -324,9 +318,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): @@ -354,13 +345,7 @@ class TestHelpers(APIResourceTestHelpers["ReceivedDebit"]): @classmethod def create( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "ReceivedDebit.CreateParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["ReceivedDebit.CreateParams"] ) -> "ReceivedDebit": """ Use this endpoint to simulate a test mode ReceivedDebit initiated by a third party. In live mode, you can't directly create ReceivedDebits initiated by third parties. @@ -370,9 +355,6 @@ def create( cls._static_request( "post", "/v1/test_helpers/treasury/received_debits", - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ), ) diff --git a/stripe/treasury/_received_debit_service.py b/stripe/treasury/_received_debit_service.py new file mode 100644 index 000000000..d62cb6088 --- /dev/null +++ b/stripe/treasury/_received_debit_service.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._received_debit import ReceivedDebit +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class ReceivedDebitService(StripeService): + class ListParams(TypedDict): + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + The FinancialAccount that funds were pulled from. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired["Literal['failed', 'succeeded']"] + """ + Only return ReceivedDebits that have the given status: `succeeded` or `failed`. + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "ReceivedDebitService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[ReceivedDebit]: + """ + Returns a list of ReceivedDebits. + """ + return cast( + ListObject[ReceivedDebit], + self._requestor.request( + "get", + "/v1/treasury/received_debits", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + id: str, + params: "ReceivedDebitService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> ReceivedDebit: + """ + Retrieves the details of an existing ReceivedDebit by passing the unique ReceivedDebit ID from the ReceivedDebit list + """ + return cast( + ReceivedDebit, + self._requestor.request( + "get", + "/v1/treasury/received_debits/{id}".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/treasury/_transaction.py b/stripe/treasury/_transaction.py index 8e5cd4328..f98ab5c36 100644 --- a/stripe/treasury/_transaction.py +++ b/stripe/treasury/_transaction.py @@ -271,13 +271,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "Transaction.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["Transaction.ListParams"] ) -> ListObject["Transaction"]: """ Retrieves a list of Transaction objects. @@ -285,9 +279,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/treasury/_transaction_entry.py b/stripe/treasury/_transaction_entry.py index 49b436681..317a5318b 100644 --- a/stripe/treasury/_transaction_entry.py +++ b/stripe/treasury/_transaction_entry.py @@ -265,13 +265,7 @@ class RetrieveParams(RequestOptions): @classmethod def list( - cls, - api_key: Optional[str] = None, - stripe_version: Optional[str] = None, - stripe_account: Optional[str] = None, - **params: Unpack[ - "TransactionEntry.ListParams" - ] # pyright: ignore[reportGeneralTypeIssues] + cls, **params: Unpack["TransactionEntry.ListParams"] ) -> ListObject["TransactionEntry"]: """ Retrieves a list of TransactionEntry objects. @@ -279,9 +273,6 @@ def list( result = cls._static_request( "get", cls.class_url(), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) if not isinstance(result, ListObject): diff --git a/stripe/treasury/_transaction_entry_service.py b/stripe/treasury/_transaction_entry_service.py new file mode 100644 index 000000000..5caf0f927 --- /dev/null +++ b/stripe/treasury/_transaction_entry_service.py @@ -0,0 +1,130 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._transaction_entry import TransactionEntry +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class TransactionEntryService(StripeService): + class ListParams(TypedDict): + created: NotRequired["TransactionEntryService.ListParamsCreated|int"] + effective_at: NotRequired[ + "TransactionEntryService.ListParamsEffectiveAt|int" + ] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + Returns objects associated with this FinancialAccount. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + order_by: NotRequired["Literal['created', 'effective_at']"] + """ + The results are in reverse chronological order by `created` or `effective_at`. The default is `created`. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + transaction: NotRequired["str"] + """ + Only return TransactionEntries associated with this Transaction. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ListParamsEffectiveAt(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "TransactionEntryService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[TransactionEntry]: + """ + Retrieves a list of TransactionEntry objects. + """ + return cast( + ListObject[TransactionEntry], + self._requestor.request( + "get", + "/v1/treasury/transaction_entries", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + id: str, + params: "TransactionEntryService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> TransactionEntry: + """ + Retrieves a TransactionEntry object. + """ + return cast( + TransactionEntry, + self._requestor.request( + "get", + "/v1/treasury/transaction_entries/{id}".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/stripe/treasury/_transaction_service.py b/stripe/treasury/_transaction_service.py new file mode 100644 index 000000000..226d1c06d --- /dev/null +++ b/stripe/treasury/_transaction_service.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# File generated from our OpenAPI spec +from stripe import _util +from stripe._list_object import ListObject +from stripe._request_options import RequestOptions +from stripe._stripe_service import StripeService +from stripe.treasury._transaction import Transaction +from typing import List, cast +from typing_extensions import Literal, NotRequired, TypedDict + + +class TransactionService(StripeService): + class ListParams(TypedDict): + created: NotRequired["TransactionService.ListParamsCreated|int"] + ending_before: NotRequired["str"] + """ + A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + """ + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + financial_account: str + """ + Returns objects associated with this FinancialAccount. + """ + limit: NotRequired["int"] + """ + A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + """ + order_by: NotRequired["Literal['created', 'posted_at']"] + """ + The results are in reverse chronological order by `created` or `posted_at`. The default is `created`. + """ + starting_after: NotRequired["str"] + """ + A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + """ + status: NotRequired["Literal['open', 'posted', 'void']"] + """ + Only return Transactions that have the given status: `open`, `posted`, or `void`. + """ + status_transitions: NotRequired[ + "TransactionService.ListParamsStatusTransitions" + ] + """ + A filter for the `status_transitions.posted_at` timestamp. When using this filter, `status=posted` and `order_by=posted_at` must also be specified. + """ + + class ListParamsCreated(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class ListParamsStatusTransitions(TypedDict): + posted_at: NotRequired[ + "TransactionService.ListParamsStatusTransitionsPostedAt|int" + ] + """ + Returns Transactions with `posted_at` within the specified range. + """ + + class ListParamsStatusTransitionsPostedAt(TypedDict): + gt: NotRequired["int"] + """ + Minimum value to filter by (exclusive) + """ + gte: NotRequired["int"] + """ + Minimum value to filter by (inclusive) + """ + lt: NotRequired["int"] + """ + Maximum value to filter by (exclusive) + """ + lte: NotRequired["int"] + """ + Maximum value to filter by (inclusive) + """ + + class RetrieveParams(TypedDict): + expand: NotRequired["List[str]"] + """ + Specifies which fields in the response should be expanded. + """ + + def list( + self, + params: "TransactionService.ListParams", + options: RequestOptions = {}, + ) -> ListObject[Transaction]: + """ + Retrieves a list of Transaction objects. + """ + return cast( + ListObject[Transaction], + self._requestor.request( + "get", + "/v1/treasury/transactions", + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) + + def retrieve( + self, + id: str, + params: "TransactionService.RetrieveParams" = {}, + options: RequestOptions = {}, + ) -> Transaction: + """ + Retrieves the details of an existing Transaction. + """ + return cast( + Transaction, + self._requestor.request( + "get", + "/v1/treasury/transactions/{id}".format( + id=_util.sanitize_id(id), + ), + api_mode="V1", + base_address="api", + params=params, + options=options, + ), + ) diff --git a/tests/api_resources/abstract/test_api_resource.py b/tests/api_resources/abstract/test_api_resource.py index 623f03811..4c3a0c96b 100644 --- a/tests/api_resources/abstract/test_api_resource.py +++ b/tests/api_resources/abstract/test_api_resource.py @@ -76,32 +76,6 @@ def test_retrieve_and_refresh(self, http_client_mock): with pytest.raises(KeyError): res["bobble"] - def test_request_with_special_fields_prefers_explicit( - self, http_client_mock - ): - path = "/v1/myresources/foo" - query_string = "bobble=scrobble" - http_client_mock.stub_request( - "get", - path, - query_string, - '{"id": "foo2", "bobble": "scrobble"}', - ) - - self.MyResource._static_request( - "get", - path, - idempotency_key="explicit", - params={"idempotency_key": "params", "bobble": "scrobble"}, - ) - - http_client_mock.assert_requested( - "get", - path=path, - query_string=query_string, - idempotency_key="explicit", - ) - def test_convert_to_stripe_object(self): sample = { "foo": "bar", diff --git a/tests/api_resources/abstract/test_custom_method.py b/tests/api_resources/abstract/test_custom_method.py index 213d99533..12142473f 100644 --- a/tests/api_resources/abstract/test_custom_method.py +++ b/tests/api_resources/abstract/test_custom_method.py @@ -20,43 +20,34 @@ class MyResource(stripe.api_resources.abstract.APIResource): def do_stuff(self, idempotency_key=None, **params): url = self.instance_url() + "/do_the_thing" - headers = util.populate_headers(idempotency_key) - self.refresh_from(self.request("post", url, params, headers)) + self._request_and_refresh( + "post", url, {**params, "idempotency_key": idempotency_key} + ) return self def do_stream_stuff(self, idempotency_key=None, **params): url = self.instance_url() + "/do_the_stream_thing" - headers = util.populate_headers(idempotency_key) - return self.request_stream("post", url, params, headers) + return self._request_stream( + "post", url, {**params, "idempotency_key": idempotency_key} + ) @classmethod - def _cls_do_stuff_new_codegen( - cls, - id, - api_key=None, - stripe_version=None, - stripe_account=None, - **params - ): + def _cls_do_stuff_new_codegen(cls, id, **params): return cls._static_request( "post", "/v1/myresources/{id}/do_the_thing".format( id=util.sanitize_id(id) ), - api_key=api_key, - stripe_version=stripe_version, - stripe_account=stripe_account, params=params, ) @util.class_method_variant("_cls_do_stuff_new_codegen") - def do_stuff_new_codegen(self, idempotency_key=None, **params): + def do_stuff_new_codegen(self, **params): return self._request( "post", "/v1/myresources/{id}/do_the_thing".format( id=util.sanitize_id(self.get("id")) ), - idempotency_key=idempotency_key, params=params, ) diff --git a/tests/api_resources/abstract/test_test_helpers_api_resource.py b/tests/api_resources/abstract/test_test_helpers_api_resource.py index 347a21e7a..f0c6d6466 100644 --- a/tests/api_resources/abstract/test_test_helpers_api_resource.py +++ b/tests/api_resources/abstract/test_test_helpers_api_resource.py @@ -1,5 +1,4 @@ import stripe -from stripe import util from stripe._test_helpers import APIResourceTestHelpers @@ -16,9 +15,8 @@ def __init__(self, resource): def do_stuff(self, idempotency_key=None, **params): url = self.instance_url() + "/do_the_thing" - headers = util.populate_headers(idempotency_key) - self.resource.refresh_from( - self.resource.request("post", url, params, headers) + self.resource._request_and_refresh( + "post", url, {**params, "idempotency_key": idempotency_key} ) return self.resource diff --git a/tests/api_resources/test_customer.py b/tests/api_resources/test_customer.py index eabf21f0a..e1f69573d 100644 --- a/tests/api_resources/test_customer.py +++ b/tests/api_resources/test_customer.py @@ -197,7 +197,7 @@ def test_is_listable(self, http_client_mock): def test_is_listable_on_object(self, http_client_mock): resource = stripe.Customer.retrieve( TEST_RESOURCE_ID - ).list_payment_methods(TEST_RESOURCE_ID, type="card") + ).list_payment_methods(type="card") http_client_mock.assert_requested( "get", path="/v1/customers/%s/payment_methods" % TEST_RESOURCE_ID ) @@ -212,7 +212,7 @@ class TestCustomerCashBalanceMethods(object): def test_customer_cashbalance_retrieve_legacy_call_pattern( self, http_client_mock ): - stripe.Customer.retrieve_cash_balance("cus_123", None) + stripe.Customer.retrieve_cash_balance("cus_123") http_client_mock.assert_requested( "get", path="/v1/customers/cus_123/cash_balance" ) @@ -222,7 +222,6 @@ def test_customer_cashbalance_modify_legacy_call_pattern( ): stripe.Customer.modify_cash_balance( "cus_123", - None, settings={"reconciliation_mode": "manual"}, ) http_client_mock.assert_requested( diff --git a/tests/api_resources/test_file.py b/tests/api_resources/test_file.py index 949e5d7ab..4e43655f0 100644 --- a/tests/api_resources/test_file.py +++ b/tests/api_resources/test_file.py @@ -69,7 +69,7 @@ def test_create_respects_api_version( ): test_file = tempfile.TemporaryFile() stripe.File.create( - purpose="dispute_evidence", file=test_file, api_version="foo" + purpose="dispute_evidence", file=test_file, stripe_version="foo" ) http_client_mock.assert_requested( "post", @@ -79,9 +79,13 @@ def test_create_respects_api_version( ) def test_deserializes_from_file(self): - obj = stripe.util.convert_to_stripe_object({"object": "file"}) + obj = stripe.util.convert_to_stripe_object( + {"object": "file"}, api_mode="V1" + ) assert isinstance(obj, stripe.File) def test_deserializes_from_file_upload(self): - obj = stripe.util.convert_to_stripe_object({"object": "file_upload"}) + obj = stripe.util.convert_to_stripe_object( + {"object": "file_upload"}, api_mode="V1" + ) assert isinstance(obj, stripe.File) diff --git a/tests/api_resources/test_file_upload.py b/tests/api_resources/test_file_upload.py index a72b94e76..fb696d636 100644 --- a/tests/api_resources/test_file_upload.py +++ b/tests/api_resources/test_file_upload.py @@ -49,9 +49,13 @@ def test_is_creatable(self, setup_upload_api_base, http_client_mock): assert isinstance(resource, stripe.FileUpload) def test_deserializes_from_file(self): - obj = stripe.util.convert_to_stripe_object({"object": "file"}) + obj = stripe.util.convert_to_stripe_object( + {"object": "file"}, api_mode="V1" + ) assert isinstance(obj, stripe.FileUpload) def test_deserializes_from_file_upload(self): - obj = stripe.util.convert_to_stripe_object({"object": "file_upload"}) + obj = stripe.util.convert_to_stripe_object( + {"object": "file_upload"}, api_mode="V1" + ) assert isinstance(obj, stripe.FileUpload) diff --git a/tests/api_resources/test_list_object.py b/tests/api_resources/test_list_object.py index 3fdcc3392..72aa8dc11 100644 --- a/tests/api_resources/test_list_object.py +++ b/tests/api_resources/test_list_object.py @@ -90,7 +90,7 @@ def test_is_empty(self): assert lo.is_empty is True def test_empty_list(self): - lo = stripe.ListObject.empty_list() + lo = stripe.ListObject._empty_list() assert lo.is_empty def test_iter(self): @@ -176,7 +176,7 @@ def test_next_page_empty_list(self): ) next_lo = lo.next_page() - assert next_lo == stripe.ListObject.empty_list() + assert next_lo == stripe.ListObject._empty_list() def test_prev_page(self, http_client_mock): lo = stripe.ListObject.construct_from( @@ -339,7 +339,7 @@ def test_class_method_two_pages(self, http_client_mock): ) assert seen == ["ch_001"] - def test_iter_forwards_api_key(self, http_client_mock): + def test_iter_forwards_api_key_resource(self, http_client_mock): http_client_mock.stub_request( "get", path="/v1/charges", @@ -371,6 +371,44 @@ def test_iter_forwards_api_key(self, http_client_mock): ) assert seen == ["ch_001", "ch_002"] + def test_iter_forwards_api_key_client(self, http_client_mock): + client = stripe.StripeClient( + http_client=http_client_mock.get_mock_http_client(), + api_key="sk_test_xyz", + ) + + http_client_mock.stub_request( + "get", + path="/v1/charges", + rbody='{"object": "list", "data": [{"id": "x"}], "url": "/v1/charges", "has_more": true}', + ) + + http_client_mock.stub_request( + "get", + path="/v1/charges", + query_string="starting_after=x", + rbody='{"object": "list", "data": [{"id": "y"}, {"id": "z"}], "url": "/v1/charges", "has_more": false}', + ) + + lo = client.charges.list( + options={"api_key": "sk_test_iter_forwards_options"} + ) + + seen = [item["id"] for item in lo.auto_paging_iter()] + + assert seen == ["x", "y", "z"] + http_client_mock.assert_requested( + "get", + path="/v1/charges", + api_key="sk_test_iter_forwards_options", + ) + http_client_mock.assert_requested( + "get", + path="/v1/charges", + query_string="starting_after=x", + api_key="sk_test_iter_forwards_options", + ) + def test_forwards_api_key_to_nested_resources(self, http_client_mock): http_client_mock.stub_request( "get", diff --git a/tests/api_resources/test_quote.py b/tests/api_resources/test_quote.py index 24dd9c3bb..20d04cffc 100644 --- a/tests/api_resources/test_quote.py +++ b/tests/api_resources/test_quote.py @@ -142,7 +142,7 @@ def test_can_list_computed_upfront_line_items_classmethod( def test_can_pdf(self, setup_upload_api_base, http_client_mock_streaming): resource = stripe.Quote.retrieve(TEST_RESOURCE_ID) - stream, _ = resource.pdf() + stream = resource.pdf() http_client_mock_streaming.assert_requested( "get", api_base=stripe.upload_api_base, diff --git a/tests/api_resources/test_search_result_object.py b/tests/api_resources/test_search_result_object.py index c61c3305e..c77abf467 100644 --- a/tests/api_resources/test_search_result_object.py +++ b/tests/api_resources/test_search_result_object.py @@ -47,7 +47,7 @@ def test_is_empty(self): assert sro.is_empty is True def test_empty_search_result(self): - sro = stripe.SearchResultObject.empty_search_result() + sro = stripe.SearchResultObject._empty_search_result() assert sro.is_empty def test_iter(self): @@ -149,7 +149,7 @@ def test_next_search_result_page_empty_search_result(self): ) next_sro = sro.next_search_result_page() - assert next_sro == stripe.SearchResultObject.empty_search_result() + assert next_sro == stripe.SearchResultObject._empty_search_result() def test_serialize_empty_search_result(self): empty = stripe.SearchResultObject.construct_from( diff --git a/tests/conftest.py b/tests/conftest.py index 643f51c3b..1dd6b7e3e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,6 +4,7 @@ import pytest import stripe +from stripe import StripeClient import requests from tests.stripe_mock import StripeMock @@ -96,3 +97,39 @@ def http_client_mock_streaming(mocker): stripe.default_http_client = mock_client.get_mock_http_client() yield mock_client stripe.default_http_client = old_client + + +@pytest.fixture +def stripe_mock_stripe_client(http_client_mock): + return StripeClient( + MOCK_API_KEY, + base_addresses={"api": MOCK_API_BASE}, + http_client=http_client_mock.get_mock_http_client(), + ) + + +@pytest.fixture +def file_stripe_mock_stripe_client(http_client_mock): + return StripeClient( + MOCK_API_KEY, + base_addresses={"files": MOCK_API_BASE}, + http_client=http_client_mock.get_mock_http_client(), + ) + + +@pytest.fixture +def stripe_mock_stripe_client_streaming(http_client_mock_streaming): + return StripeClient( + MOCK_API_KEY, + base_addresses={"api": MOCK_API_BASE}, + http_client=http_client_mock_streaming.get_mock_http_client(), + ) + + +@pytest.fixture +def file_stripe_mock_stripe_client_streaming(http_client_mock_streaming): + return StripeClient( + MOCK_API_KEY, + base_addresses={"files": MOCK_API_BASE}, + http_client=http_client_mock_streaming.get_mock_http_client(), + ) diff --git a/tests/fixtures/card.json b/tests/fixtures/card.json new file mode 100644 index 000000000..97a40a318 --- /dev/null +++ b/tests/fixtures/card.json @@ -0,0 +1,26 @@ +{ + "id": "card_123", + "object": "payment_methods.card", + "address_city": null, + "address_country": null, + "address_line1": null, + "address_line1_check": null, + "address_line2": null, + "address_state": null, + "address_zip": null, + "address_zip_check": null, + "brand": "Visa", + "country": "US", + "customer": "cus_123", + "cvc_check": null, + "dynamic_last4": null, + "exp_month": 8, + "exp_year": 2019, + "fingerprint": "Xt5EWLLDS7FJjR1c", + "funding": "credit", + "last4": "4242", + "metadata": { + }, + "name": null, + "tokenization_method": null +} diff --git a/tests/http_client_mock.py b/tests/http_client_mock.py index 25aa05e14..8e3745819 100644 --- a/tests/http_client_mock.py +++ b/tests/http_client_mock.py @@ -25,12 +25,18 @@ def extract_api_base(abs_url): class StripeRequestCall(object): def __init__( - self, method=None, abs_url=None, headers=None, post_data=None + self, + method=None, + abs_url=None, + headers=None, + post_data=None, + max_network_retries=None, ): self.method = method self.abs_url = abs_url self.headers = headers self.post_data = post_data + self.max_network_retries = max_network_retries @classmethod def from_mock_call(cls, mock_call): @@ -39,6 +45,7 @@ def from_mock_call(cls, mock_call): abs_url=mock_call[0][1], headers=mock_call[0][2], post_data=mock_call[0][3], + max_network_retries=mock_call[1]["max_network_retries"], ) def __repr__(self): @@ -64,13 +71,13 @@ def check( api_key=None, stripe_version=None, stripe_account=None, - stripe_context=None, content_type=None, idempotency_key=None, user_agent=None, extra_headers=None, post_data=None, is_json=False, + max_network_retries=None, ): # METHOD if method is not None: @@ -93,8 +100,6 @@ def check( self.assert_header("Stripe-Version", stripe_version) if stripe_account is not None: self.assert_header("Stripe-Account", stripe_account) - if stripe_context is not None: - self.assert_header("Stripe-Context", stripe_context) if content_type is not None: self.assert_header("Content-Type", content_type) if idempotency_key is not None: @@ -108,8 +113,20 @@ def check( if post_data is not None: self.assert_post_data(post_data, is_json=is_json) + # OPTIONS + if max_network_retries is not None: + self.assert_max_network_retries(max_network_retries) + return True + def assert_max_network_retries(self, expected): + actual = self.max_network_retries + if actual != expected: + raise AssertionError( + "Expected max_network_retries to be %s, got %s" + % (expected, actual) + ) + def assert_method(self, expected): if self.method != expected: raise AssertionError( @@ -282,13 +299,13 @@ def assert_requested( api_key=None, stripe_version=None, stripe_account=None, - stripe_context=None, content_type=None, idempotency_key=None, user_agent=None, extra_headers=None, post_data=None, is_json=False, + max_network_retries=None, ) -> None: if abs_url and (api_base or path or query_string): raise ValueError( @@ -311,13 +328,13 @@ def assert_requested( api_key=api_key, stripe_version=stripe_version, stripe_account=stripe_account, - stripe_context=stripe_context, content_type=content_type, idempotency_key=idempotency_key, user_agent=user_agent, extra_headers=extra_headers, post_data=post_data, is_json=is_json, + max_network_retries=max_network_retries, ) def assert_no_request(self): diff --git a/tests/services/test_file_upload.py b/tests/services/test_file_upload.py new file mode 100644 index 000000000..b1088ed80 --- /dev/null +++ b/tests/services/test_file_upload.py @@ -0,0 +1,51 @@ +from __future__ import absolute_import, division, print_function + +import tempfile + +import stripe + + +TEST_RESOURCE_ID = "file_123" + + +class TestFileUpload(object): + def test_is_listable(self, http_client_mock, stripe_mock_stripe_client): + resources = stripe_mock_stripe_client.files.list() + http_client_mock.assert_requested("get", path="/v1/files") + assert isinstance(resources.data, list) + assert isinstance(resources.data[0], stripe.FileUpload) + + def test_is_retrievable(self, http_client_mock, stripe_mock_stripe_client): + resource = stripe_mock_stripe_client.files.retrieve(TEST_RESOURCE_ID) + http_client_mock.assert_requested( + "get", path="/v1/files/%s" % TEST_RESOURCE_ID + ) + assert isinstance(resource, stripe.FileUpload) + + def test_is_creatable( + self, + file_stripe_mock_stripe_client, + http_client_mock, + ): + stripe.multipart_data_generator.MultipartDataGenerator._initialize_boundary = ( + lambda self: 1234567890 + ) + test_file = tempfile.TemporaryFile() + + # We create a new client here instead of re-using the stripe_mock_stripe_client fixture + # because stripe_mock_stripe_client overrides the "api" base address, which we want to + # be empty for this test. + resource = file_stripe_mock_stripe_client.files.create( + params={ + "purpose": "dispute_evidence", + "file": test_file, + "file_link_data": {"create": True}, + } + ) + http_client_mock.assert_requested( + "post", + api_base=stripe.upload_api_base, + path="/v1/files", + content_type="multipart/form-data; boundary=1234567890", + ) + assert isinstance(resource, stripe.FileUpload) diff --git a/tests/services/test_oauth.py b/tests/services/test_oauth.py new file mode 100644 index 000000000..3eba38927 --- /dev/null +++ b/tests/services/test_oauth.py @@ -0,0 +1,117 @@ +import pytest + +from urllib.parse import parse_qs, urlparse + +import stripe +from stripe._stripe_client import StripeClient + + +class TestOAuth(object): + @pytest.fixture + def stripe_client(self, http_client_mock) -> StripeClient: + return StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + client_id="ca_123", + ) + + def test_authorize_url(self, stripe_client: StripeClient): + url = stripe_client.oauth.authorize_url( + { + "scope": "read_write", + "state": "csrf_token", + "stripe_user": { + "email": "test@example.com", + "url": "https://example.com/profile/test", + "country": "US", + }, + } + ) + o = urlparse(url) + params = parse_qs(o.query) + + url_express = stripe_client.oauth.authorize_url( + {"scope": "read_write", "state": "csrf_token"}, {"express": True} + ) + o_express = urlparse(url_express) + + assert o.scheme == "https" + assert o.netloc == "connect.stripe.com" + assert o.path == "/oauth/authorize" + assert o_express.path == "/express/oauth/authorize" + + assert params["client_id"] == ["ca_123"] + assert params["scope"] == ["read_write"] + assert params["stripe_user[email]"] == ["test@example.com"] + assert params["stripe_user[url]"] == [ + "https://example.com/profile/test" + ] + assert params["stripe_user[country]"] == ["US"] + + def test_token(self, stripe_client: StripeClient, http_client_mock): + http_client_mock.stub_request( + "post", + path="/oauth/token", + rbody='{"access_token":"sk_access_token","scope":"read_only","livemode":"false","token_type":"bearer","refresh_token":"sk_refresh_token","stripe_user_id":"acct_test","stripe_publishable_key":"pk_test"}', + ) + + resp = stripe_client.oauth.token( + { + "grant_type": "authorization_code", + "code": "this_is_an_authorization_code", + } + ) + http_client_mock.assert_requested( + "post", + api_base=stripe.connect_api_base, + path="/oauth/token", + post_data="grant_type=authorization_code&code=this_is_an_authorization_code", + ) + assert resp["access_token"] == "sk_access_token" + + def test_deauthorize(self, stripe_client: StripeClient, http_client_mock): + http_client_mock.stub_request( + "post", + path="/oauth/deauthorize", + rbody='{"stripe_user_id":"acct_test_deauth"}', + ) + + resp = stripe_client.oauth.deauthorize( + { + "stripe_user_id": "acct_test_deauth", + } + ) + http_client_mock.assert_requested( + "post", + api_base=stripe.connect_api_base, + path="/oauth/deauthorize", + post_data="client_id=ca_123&stripe_user_id=acct_test_deauth", + ) + assert resp["stripe_user_id"] == "acct_test_deauth" + + def test_uses_client_connect_api_base(self, http_client_mock): + http_client_mock.stub_request( + "post", + path="/oauth/token", + rbody='{"access_token":"sk_access_token","scope":"read_only","livemode":"false","token_type":"bearer","refresh_token":"sk_refresh_token","stripe_user_id":"acct_test","stripe_publishable_key":"pk_test"}', + ) + + expected_api_base = "https://connect.example.com" + client = stripe.StripeClient( + "sk_test_123", + base_addresses={"connect": expected_api_base}, + http_client=http_client_mock.get_mock_http_client(), + ) + + resp = client.oauth.token( + { + "grant_type": "authorization_code", + "code": "ac_123456789", + } + ) + http_client_mock.assert_requested( + "post", + api_base=expected_api_base, + path="/oauth/token", + ) + assert resp["access_token"] == "sk_access_token" diff --git a/tests/services/test_quote.py b/tests/services/test_quote.py new file mode 100644 index 000000000..555b7ef51 --- /dev/null +++ b/tests/services/test_quote.py @@ -0,0 +1,120 @@ +from __future__ import absolute_import, division, print_function + +import stripe + + +TEST_RESOURCE_ID = "qt_123" + + +class TestQuote(object): + def test_is_listable(self, http_client_mock, stripe_mock_stripe_client): + resources = stripe_mock_stripe_client.quotes.list() + http_client_mock.assert_requested("get", path="/v1/quotes") + assert isinstance(resources.data, list) + assert isinstance(resources.data[0], stripe.Quote) + + def test_is_retrievable(self, http_client_mock, stripe_mock_stripe_client): + resource = stripe_mock_stripe_client.quotes.retrieve(TEST_RESOURCE_ID) + http_client_mock.assert_requested( + "get", path="/v1/quotes/%s" % TEST_RESOURCE_ID + ) + assert isinstance(resource, stripe.Quote) + + def test_is_creatable(self, http_client_mock, stripe_mock_stripe_client): + resource = stripe_mock_stripe_client.quotes.create( + params={"customer": "cus_123"} + ) + http_client_mock.assert_requested( + "post", path="/v1/quotes", post_data="customer=cus_123" + ) + assert isinstance(resource, stripe.Quote) + + def test_is_updateable(self, http_client_mock, stripe_mock_stripe_client): + resource = stripe_mock_stripe_client.quotes.update( + TEST_RESOURCE_ID, params={"metadata": {"key": "value"}} + ) + http_client_mock.assert_requested( + "post", + path="/v1/quotes/%s" % TEST_RESOURCE_ID, + post_data="metadata[key]=value", + ) + assert isinstance(resource, stripe.Quote) + + def test_can_finalize_quote( + self, http_client_mock, stripe_mock_stripe_client + ): + resource = stripe_mock_stripe_client.quotes.retrieve(TEST_RESOURCE_ID) + resource = resource.finalize_quote() + http_client_mock.assert_requested( + "post", path="/v1/quotes/%s/finalize" % TEST_RESOURCE_ID + ) + assert isinstance(resource, stripe.Quote) + + def test_can_finalize_quote_classmethod( + self, http_client_mock, stripe_mock_stripe_client + ): + resource = stripe_mock_stripe_client.quotes.finalize_quote( + TEST_RESOURCE_ID + ) + http_client_mock.assert_requested( + "post", path="/v1/quotes/%s/finalize" % TEST_RESOURCE_ID + ) + assert isinstance(resource, stripe.Quote) + + def test_can_cancel(self, http_client_mock, stripe_mock_stripe_client): + resource = stripe_mock_stripe_client.quotes.cancel(TEST_RESOURCE_ID) + http_client_mock.assert_requested( + "post", path="/v1/quotes/%s/cancel" % TEST_RESOURCE_ID + ) + assert isinstance(resource, stripe.Quote) + + def test_can_accept(self, http_client_mock, stripe_mock_stripe_client): + resource = stripe_mock_stripe_client.quotes.accept(TEST_RESOURCE_ID) + http_client_mock.assert_requested( + "post", path="/v1/quotes/%s/accept" % TEST_RESOURCE_ID + ) + assert isinstance(resource, stripe.Quote) + + def test_can_list_line_items( + self, http_client_mock, stripe_mock_stripe_client + ): + resources = stripe_mock_stripe_client.quotes.line_items.list( + TEST_RESOURCE_ID + ) + http_client_mock.assert_requested( + "get", path="/v1/quotes/%s/line_items" % TEST_RESOURCE_ID + ) + assert isinstance(resources.data, list) + assert isinstance(resources.data[0], stripe.LineItem) + + def test_can_list_computed_upfront_line_items( + self, http_client_mock, stripe_mock_stripe_client + ): + resources = ( + stripe_mock_stripe_client.quotes.computed_upfront_line_items.list( + TEST_RESOURCE_ID + ) + ) + http_client_mock.assert_requested( + "get", + path="/v1/quotes/%s/computed_upfront_line_items" + % TEST_RESOURCE_ID, + ) + assert isinstance(resources.data, list) + assert isinstance(resources.data[0], stripe.LineItem) + + def test_can_pdf( + self, + file_stripe_mock_stripe_client_streaming, + http_client_mock_streaming, + ): + stream = file_stripe_mock_stripe_client_streaming.quotes.pdf( + TEST_RESOURCE_ID + ) + http_client_mock_streaming.assert_requested( + "get", + api_base=stripe.upload_api_base, + path="/v1/quotes/%s/pdf" % TEST_RESOURCE_ID, + ) + content = stream.io.read() + assert content == b"Stripe binary response" diff --git a/tests/test_api_requestor.py b/tests/test_api_requestor.py index 2360da8e6..8401b68d9 100644 --- a/tests/test_api_requestor.py +++ b/tests/test_api_requestor.py @@ -8,10 +8,15 @@ import stripe from stripe import util -from stripe._stripe_response import StripeResponse, StripeStreamResponse -from stripe._encode import _api_encode +from stripe._api_requestor import _APIRequestor, _api_encode +from stripe._stripe_object import StripeObject +from stripe._stripe_response import StripeStreamResponse +from stripe._requestor_options import ( + _GlobalRequestorOptions, +) +from stripe._request_options import RequestOptions -from urllib.parse import urlsplit, parse_qsl +from urllib.parse import urlencode, urlsplit import urllib3 @@ -29,142 +34,6 @@ def tzname(self, dt): return "Europe/Prague" -class APIHeaderMatcher(object): - EXP_KEYS = [ - "Authorization", - "Stripe-Version", - "User-Agent", - "X-Stripe-Client-User-Agent", - ] - METHOD_EXTRA_KEYS = {"post": ["Content-Type", "Idempotency-Key"]} - - def __init__( - self, - api_key=None, - extra={}, - request_method=None, - user_agent=None, - app_info=None, - idempotency_key=None, - fail_platform_call=False, - ): - self.request_method = request_method - self.api_key = api_key or stripe.api_key - self.extra = extra - self.user_agent = user_agent - self.app_info = app_info - self.idempotency_key = idempotency_key - self.fail_platform_call = fail_platform_call - - def __eq__(self, other): - return ( - self._keys_match(other) - and self._auth_match(other) - and self._user_agent_match(other) - and self._x_stripe_ua_contains_app_info(other) - and self._x_stripe_ua_handles_failed_platform_function(other) - and self._idempotency_key_match(other) - and self._extra_match(other) - ) - - def __repr__(self): - return ( - "APIHeaderMatcher(request_method=%s, api_key=%s, extra=%s, " - "user_agent=%s, app_info=%s, idempotency_key=%s, fail_platform_call=%s)" - % ( - repr(self.request_method), - repr(self.api_key), - repr(self.extra), - repr(self.user_agent), - repr(self.app_info), - repr(self.idempotency_key), - repr(self.fail_platform_call), - ) - ) - - def _keys_match(self, other): - expected_keys = list(set(self.EXP_KEYS + list(self.extra.keys()))) - if ( - self.request_method is not None - and self.request_method in self.METHOD_EXTRA_KEYS - ): - expected_keys.extend(self.METHOD_EXTRA_KEYS[self.request_method]) - return sorted(other.keys()) == sorted(expected_keys) - - def _auth_match(self, other): - return other["Authorization"] == "Bearer %s" % (self.api_key,) - - def _user_agent_match(self, other): - if self.user_agent is not None: - return other["User-Agent"] == self.user_agent - - return True - - def _idempotency_key_match(self, other): - if self.idempotency_key is not None: - return other["Idempotency-Key"] == self.idempotency_key - return True - - def _x_stripe_ua_contains_app_info(self, other): - if self.app_info: - ua = json.loads(other["X-Stripe-Client-User-Agent"]) - if "application" not in ua: - return False - return ua["application"] == self.app_info - - return True - - def _x_stripe_ua_handles_failed_platform_function(self, other): - if self.fail_platform_call: - ua = json.loads(other["X-Stripe-Client-User-Agent"]) - return ua["platform"] == "(disabled)" - return True - - def _extra_match(self, other): - for k, v in self.extra.items(): - if other[k] != v: - return False - - return True - - -class QueryMatcher(object): - def __init__(self, expected): - self.expected = sorted(expected) - - def __eq__(self, other): - query = urlsplit(other).query or other - - parsed = parse_qsl(query) - return self.expected == sorted(parsed) - - def __repr__(self): - return "QueryMatcher(expected=%s)" % (repr(self.expected)) - - -class UrlMatcher(object): - def __init__(self, expected): - self.exp_parts = urlsplit(expected) - - def __eq__(self, other): - other_parts = urlsplit(other) - - for part in ("scheme", "netloc", "path", "fragment"): - expected = getattr(self.exp_parts, part) - actual = getattr(other_parts, part) - if expected != actual: - print( - 'Expected %s "%s" but got "%s"' % (part, expected, actual) - ) - return False - - q_matcher = QueryMatcher(parse_qsl(self.exp_parts.query)) - return q_matcher == other - - def __repr__(self): - return "UrlMatcher(exp_parts=%s)" % (repr(self.exp_parts)) - - class AnyUUID4Matcher(object): def __eq__(self, other): try: @@ -233,59 +102,20 @@ def setup_stripe(self): stripe.enable_telemetry = orig_attrs["enable_telemetry"] @pytest.fixture - def http_client(self, mocker): - http_client = mocker.Mock(stripe.http_client.HTTPClient) - http_client._verify_ssl_certs = True - http_client.name = "mockclient" - return http_client - - @pytest.fixture - def requestor(self, http_client): - requestor = stripe.api_requestor.APIRequestor(client=http_client) + def requestor(self, http_client_mock): + requestor = _APIRequestor( + client=http_client_mock.get_mock_http_client(), + options=_GlobalRequestorOptions(), + ) return requestor @pytest.fixture - def mock_response(self, mocker, http_client): - def mock_response(return_body, return_code, headers=None): - http_client.request_with_retries = mocker.Mock( - return_value=(return_body, return_code, headers or {}) - ) - - return mock_response - - @pytest.fixture - def mock_streaming_response(self, mocker, http_client): - def mock_streaming_response(return_body, return_code, headers=None): - http_client.request_stream_with_retries = mocker.Mock( - return_value=(return_body, return_code, headers or {}) - ) - - return mock_streaming_response - - @pytest.fixture - def check_call(self, http_client): - def check_call( - method, - abs_url=None, - headers=None, - post_data=None, - is_streaming=False, - ): - if not abs_url: - abs_url = "%s%s" % (stripe.api_base, self.valid_path) - if not headers: - headers = APIHeaderMatcher(request_method=method) - - if is_streaming: - http_client.request_stream_with_retries.assert_called_with( - method, abs_url, headers, post_data, _usage=None - ) - else: - http_client.request_with_retries.assert_called_with( - method, abs_url, headers, post_data, _usage=None - ) - - return check_call + def requestor_streaming(self, http_client_mock_streaming): + requestor_streaming = _APIRequestor( + client=http_client_mock_streaming.get_mock_http_client(), + options=_GlobalRequestorOptions(), + ) + return requestor_streaming @property def valid_path(self): @@ -300,7 +130,7 @@ def encoder_check(self, key): ] stk = [] - fn = getattr(stripe.api_requestor.APIRequestor, "encode_%s" % (key,)) + fn = getattr(_APIRequestor, "encode_%s" % (key,)) fn(stk, stk_key, value) if isinstance(value, dict): @@ -312,7 +142,7 @@ def encoder_check(self, key): def _test_encode_naive_datetime(self): stk = [] - stripe.api_requestor.APIRequestor.encode_datetime( + _APIRequestor.encode_datetime( stk, "test", datetime.datetime(2013, 1, 1) ) @@ -321,16 +151,23 @@ def _test_encode_naive_datetime(self): # we just check that naive encodings are within 24 hours of correct. assert abs(stk[0][1] - 1356994800) <= 60 * 60 * 24 - def test_param_encoding(self, requestor, mock_response, check_call): - mock_response("{}", 200) - - requestor.request("get", "", self.ENCODE_INPUTS) - + def test_param_encoding(self, requestor, http_client_mock): expectation = [] - for type_, values in self.ENCODE_EXPECTATIONS.items(): + for type_, values in iter(self.ENCODE_EXPECTATIONS.items()): expectation.extend([(k % (type_,), str(v)) for k, v in values]) - check_call("get", QueryMatcher(expectation)) + query_string = ( + urlencode(expectation).replace("%5B", "[").replace("%5D", "]") + ) + http_client_mock.stub_request( + "get", query_string=query_string, rbody="{}", rcode=200 + ) + + requestor.request( + "get", "", self.ENCODE_INPUTS, base_address="api", api_mode="V1" + ) + + http_client_mock.assert_requested("get", query_string=query_string) def test_dictionary_list_encoding(self): params = {"foo": {"0": {"bar": "bat"}}} @@ -359,7 +196,7 @@ def test_ordereddict_encoding(self): assert encoded[3][0] == "ordered[nested][a]" assert encoded[4][0] == "ordered[nested][b]" - def test_url_construction(self, requestor, mock_response, check_call): + def test_url_construction(self, requestor, http_client_mock): CASES = ( ("%s?foo=bar" % stripe.api_base, "", {"foo": "bar"}), ("%s?foo=bar" % stripe.api_base, "?", {"foo": "bar"}), @@ -377,39 +214,59 @@ def test_url_construction(self, requestor, mock_response, check_call): ) for expected, url, params in CASES: - mock_response("{}", 200) + path = urlsplit(expected).path + query_string = urlsplit(expected).query + http_client_mock.stub_request( + "get", + path=path, + query_string=query_string, + rbody="{}", + rcode=200, + ) - requestor.request("get", url, params) + requestor.request( + "get", url, params, base_address="api", api_mode="V1" + ) - check_call("get", expected) + http_client_mock.assert_requested("get", abs_url=expected) - def test_empty_methods(self, requestor, mock_response, check_call): + def test_empty_methods(self, requestor, http_client_mock): for meth in VALID_API_METHODS: - mock_response("{}", 200) + http_client_mock.stub_request( + meth, path=self.valid_path, rbody="{}", rcode=200 + ) - resp, key = requestor.request(meth, self.valid_path, {}) + resp = requestor.request( + meth, self.valid_path, {}, base_address="api", api_mode="V1" + ) if meth == "post": post_data = "" else: post_data = None - check_call(meth, post_data=post_data) - assert isinstance(resp, StripeResponse) + http_client_mock.assert_requested(meth, post_data=post_data) + assert isinstance(resp, StripeObject) - assert resp.data == {} - assert resp.data == json.loads(resp.body) + assert resp == {} def test_empty_methods_streaming_response( - self, requestor, mock_streaming_response, check_call + self, requestor_streaming, http_client_mock_streaming ): for meth in VALID_API_METHODS: - mock_streaming_response(util.io.BytesIO(b"thisisdata"), 200) + http_client_mock_streaming.stub_request( + meth, + path=self.valid_path, + rbody=util.io.BytesIO(b"thisisdata"), + rcode=200, + ) - resp, key = requestor.request_stream( + resp = requestor_streaming.request_stream( meth, self.valid_path, {}, + base_address="api", + api_mode="V1", ) if meth == "post": @@ -417,37 +274,51 @@ def test_empty_methods_streaming_response( else: post_data = None - check_call(meth, post_data=post_data, is_streaming=True) + http_client_mock_streaming.assert_requested( + meth, post_data=post_data + ) assert isinstance(resp, StripeStreamResponse) assert resp.io.getvalue() == b"thisisdata" def test_methods_with_params_and_response( - self, requestor, mock_response, check_call + self, requestor, http_client_mock ): for method in VALID_API_METHODS: - mock_response('{"foo": "bar", "baz": 6}', 200) + encoded = ( + "adict[frobble]=bits&adatetime=1356994800&" + "alist[0]=1&alist[1]=2&alist[2]=3" + ) + + http_client_mock.stub_request( + method, + path=self.valid_path, + query_string=encoded if method != "post" else "", + rbody='{"foo": "bar", "baz": 6}', + rcode=200, + ) params = { "alist": [1, 2, 3], "adict": {"frobble": "bits"}, "adatetime": datetime.datetime(2013, 1, 1, tzinfo=GMT1()), } - encoded = ( - "adict[frobble]=bits&adatetime=1356994800&" - "alist[0]=1&alist[1]=2&alist[2]=3" - ) - resp, key = requestor.request(method, self.valid_path, params) - assert isinstance(resp, StripeResponse) + resp = requestor.request( + method, + self.valid_path, + params, + base_address="api", + api_mode="V1", + ) + assert isinstance(resp, StripeObject) - assert resp.data == {"foo": "bar", "baz": 6} - assert resp.data == json.loads(resp.body) + assert resp == {"foo": "bar", "baz": 6} if method == "post": - check_call( + http_client_mock.assert_requested( method, - post_data=QueryMatcher(parse_qsl(encoded)), + post_data=encoded, ) else: abs_url = "%s%s?%s" % ( @@ -455,14 +326,23 @@ def test_methods_with_params_and_response( self.valid_path, encoded, ) - check_call(method, abs_url=UrlMatcher(abs_url)) + http_client_mock.assert_requested(method, abs_url=abs_url) def test_methods_with_params_and_streaming_response( - self, requestor, mock_streaming_response, check_call + self, requestor_streaming, http_client_mock_streaming ): for method in VALID_API_METHODS: - mock_streaming_response( - util.io.BytesIO(b'{"foo": "bar", "baz": 6}'), 200 + encoded = ( + "adict[frobble]=bits&adatetime=1356994800&" + "alist[0]=1&alist[1]=2&alist[2]=3" + ) + + http_client_mock_streaming.stub_request( + method, + path=self.valid_path, + query_string=encoded if method != "post" else "", + rbody=util.io.BytesIO(b'{"foo": "bar", "baz": 6}'), + rcode=200, ) params = { @@ -470,25 +350,21 @@ def test_methods_with_params_and_streaming_response( "adict": {"frobble": "bits"}, "adatetime": datetime.datetime(2013, 1, 1, tzinfo=GMT1()), } - encoded = ( - "adict[frobble]=bits&adatetime=1356994800&" - "alist[0]=1&alist[1]=2&alist[2]=3" - ) - resp, key = requestor.request_stream( + resp = requestor_streaming.request_stream( method, self.valid_path, params, + base_address="api", + api_mode="V1", ) assert isinstance(resp, StripeStreamResponse) assert resp.io.getvalue() == b'{"foo": "bar", "baz": 6}' if method == "post": - check_call( - method, - post_data=QueryMatcher(parse_qsl(encoded)), - is_streaming=True, + http_client_mock_streaming.assert_requested( + method, post_data=encoded ) else: abs_url = "%s%s?%s" % ( @@ -496,84 +372,119 @@ def test_methods_with_params_and_streaming_response( self.valid_path, encoded, ) - check_call( - method, abs_url=UrlMatcher(abs_url), is_streaming=True + http_client_mock_streaming.assert_requested( + method, abs_url=abs_url ) - def test_uses_headers(self, requestor, mock_response, check_call): - mock_response("{}", 200) - requestor.request("get", self.valid_path, {}, {"foo": "bar"}) - check_call("get", headers=APIHeaderMatcher(extra={"foo": "bar"})) - - def test_uses_instance_key(self, http_client, mock_response, check_call): - key = "fookey" - requestor = stripe.api_requestor.APIRequestor(key, client=http_client) - - mock_response("{}", 200) - - resp, used_key = requestor.request("get", self.valid_path, {}) + def test_uses_headers(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", path=self.valid_path, rbody="{}", rcode=200 + ) + request_options: RequestOptions = {"headers": {"foo": "bar"}} + requestor.request( + "get", + self.valid_path, + {}, + options=request_options, + base_address="api", + api_mode="V1", + ) + http_client_mock.assert_requested("get", extra_headers={"foo": "bar"}) - check_call("get", headers=APIHeaderMatcher(key, request_method="get")) - assert used_key == key + def test_uses_api_version(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", path=self.valid_path, rbody="{}", rcode=200 + ) + request_options: RequestOptions = {"stripe_version": "fooversion"} + requestor.request( + "get", + self.valid_path, + options=request_options, + base_address="api", + api_mode="V1", + ) + http_client_mock.assert_requested( + "get", + stripe_version="fooversion", + ) - def test_uses_instance_api_version( - self, http_client, mock_response, check_call - ): - api_version = "fooversion" - requestor = stripe.api_requestor.APIRequestor( - api_version=api_version, client=http_client + def test_prefers_headers_api_version(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", path=self.valid_path, rbody="{}", rcode=200 + ) + request_options: RequestOptions = { + "stripe_version": "fooversion", + "headers": {"Stripe-Version": "barversion"}, + } + requestor.request( + "get", + self.valid_path, + {}, + options=request_options, + base_address="api", + api_mode="V1", + ) + http_client_mock.assert_requested( + "get", + stripe_version="barversion", ) - mock_response("{}", 200) + def test_uses_instance_key(self, requestor, http_client_mock): + key = "fookey" + requestor = requestor._replace_options(RequestOptions(api_key=key)) - requestor.request("get", self.valid_path, {}) + http_client_mock.stub_request( + "get", path=self.valid_path, rbody="{}", rcode=200 + ) - check_call( - "get", - headers=APIHeaderMatcher( - extra={"Stripe-Version": "fooversion"}, request_method="get" - ), + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" ) - def test_uses_instance_account( - self, http_client, mock_response, check_call - ): + http_client_mock.assert_requested("get", api_key=key) + assert requestor.api_key == key + + def test_uses_instance_account(self, requestor, http_client_mock): account = "acct_foo" - requestor = stripe.api_requestor.APIRequestor( - account=account, client=http_client + requestor = requestor._replace_options( + RequestOptions(stripe_account=account) ) - mock_response("{}", 200) + http_client_mock.stub_request( + "get", path=self.valid_path, rbody="{}", rcode=200 + ) - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) - check_call( + http_client_mock.assert_requested( "get", - headers=APIHeaderMatcher( - extra={"Stripe-Account": account}, request_method="get" - ), + stripe_account=account, ) - def test_sets_default_http_client(self, http_client): + def test_sets_default_http_client(self, mocker): assert not stripe.default_http_client - stripe.api_requestor.APIRequestor(client=http_client) + _APIRequestor( + client=mocker.Mock(stripe.http_client.HTTPClient) + )._get_http_client() # default_http_client is not populated if a client is provided assert not stripe.default_http_client - stripe.api_requestor.APIRequestor() + _APIRequestor()._get_http_client() # default_http_client is set when no client is specified assert stripe.default_http_client new_default_client = stripe.default_http_client - stripe.api_requestor.APIRequestor() + _APIRequestor() # the newly created client is reused assert stripe.default_http_client == new_default_client - def test_uses_app_info(self, requestor, mock_response, check_call): + def test_uses_app_info(self, requestor, http_client_mock): try: old = stripe.app_info stripe.set_app_info( @@ -583,189 +494,308 @@ def test_uses_app_info(self, requestor, mock_response, check_call): partner_id="partner_12345", ) - mock_response("{}", 200) - requestor.request("get", self.valid_path, {}) + http_client_mock.stub_request( + "get", path=self.valid_path, rbody="{}", rcode=200 + ) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) ua = "Stripe/v1 PythonBindings/%s" % (stripe.VERSION,) ua += " MyAwesomePlugin/1.2.34 (https://myawesomeplugin.info)" - header_matcher = APIHeaderMatcher( - user_agent=ua, - app_info={ - "name": "MyAwesomePlugin", - "url": "https://myawesomeplugin.info", - "version": "1.2.34", - "partner_id": "partner_12345", - }, - ) - check_call("get", headers=header_matcher) + expected_app_info = { + "name": "MyAwesomePlugin", + "url": "https://myawesomeplugin.info", + "version": "1.2.34", + "partner_id": "partner_12345", + } + + last_call = http_client_mock.get_last_call() + last_call.assert_method("get") + last_call.assert_header("User-Agent", ua) + assert ( + json.loads( + last_call.get_raw_header("X-Stripe-Client-User-Agent") + )["application"] + == expected_app_info + ) finally: stripe.app_info = old def test_handles_failed_platform_call( - self, requestor, mocker, mock_response, check_call + self, requestor, mocker, http_client_mock ): - mock_response("{}", 200) + http_client_mock.stub_request( + "get", path=self.valid_path, rbody="{}", rcode=200 + ) def fail(): raise RuntimeError mocker.patch("platform.platform", side_effect=fail) - requestor.request("get", self.valid_path, {}, {}) + requestor.request( + "get", self.valid_path, {}, {}, base_address="api", api_mode="V1" + ) - check_call("get", headers=APIHeaderMatcher(fail_platform_call=True)) + last_call = http_client_mock.get_last_call() + last_call.assert_method("get") + assert ( + json.loads(last_call.get_raw_header("X-Stripe-Client-User-Agent"))[ + "platform" + ] + == "(disabled)" + ) - def test_uses_given_idempotency_key( - self, requestor, mock_response, check_call - ): - mock_response("{}", 200) + def test_uses_given_idempotency_key(self, requestor, http_client_mock): meth = "post" + http_client_mock.stub_request( + meth, path=self.valid_path, rbody="{}", rcode=200 + ) + request_options: RequestOptions = {"idempotency_key": "123abc"} requestor.request( - meth, self.valid_path, {}, {"Idempotency-Key": "123abc"} + meth, + self.valid_path, + {}, + options=request_options, + base_address="api", + api_mode="V1", ) - header_matcher = APIHeaderMatcher( - request_method=meth, idempotency_key="123abc" + http_client_mock.assert_requested( + meth, idempotency_key="123abc", post_data="" ) - check_call(meth, headers=header_matcher, post_data="") def test_uuid4_idempotency_key_when_not_given( - self, requestor, mock_response, check_call + self, requestor, http_client_mock ): - mock_response("{}", 200) meth = "post" - requestor.request(meth, self.valid_path, {}) + http_client_mock.stub_request( + meth, path=self.valid_path, rbody="{}", rcode=200 + ) + requestor.request( + meth, self.valid_path, {}, base_address="api", api_mode="V1" + ) - header_matcher = APIHeaderMatcher( - request_method=meth, idempotency_key=AnyUUID4Matcher() + http_client_mock.assert_requested( + meth, idempotency_key=AnyUUID4Matcher(), post_data="" ) - check_call(meth, headers=header_matcher, post_data="") def test_fails_without_api_key(self, requestor): stripe.api_key = None with pytest.raises(stripe.error.AuthenticationError): - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) - def test_invalid_request_error_404(self, requestor, mock_response): - mock_response('{"error": {}}', 404) + def test_invalid_request_error_404(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", path=self.valid_path, rbody='{"error": {}}', rcode=404 + ) with pytest.raises(stripe.error.InvalidRequestError): - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) - def test_invalid_request_error_400(self, requestor, mock_response): - mock_response('{"error": {}}', 400) + def test_invalid_request_error_400(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", path=self.valid_path, rbody='{"error": {}}', rcode=400 + ) with pytest.raises(stripe.error.InvalidRequestError): - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) - def test_idempotency_error(self, requestor, mock_response): - mock_response('{"error": {"type": "idempotency_error"}}', 400) + def test_idempotency_error(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", + path=self.valid_path, + rbody='{"error": {"type": "idempotency_error"}}', + rcode=400, + ) with pytest.raises(stripe.error.IdempotencyError): - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) - def test_authentication_error(self, requestor, mock_response): - mock_response('{"error": {}}', 401) + def test_authentication_error(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", path=self.valid_path, rbody='{"error": {}}', rcode=401 + ) with pytest.raises(stripe.error.AuthenticationError): - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) - def test_permissions_error(self, requestor, mock_response): - mock_response('{"error": {}}', 403) + def test_permissions_error(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", path=self.valid_path, rbody='{"error": {}}', rcode=403 + ) with pytest.raises(stripe.error.PermissionError): - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) - def test_card_error(self, requestor, mock_response): - mock_response('{"error": {"code": "invalid_expiry_year"}}', 402) + def test_card_error(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", + path=self.valid_path, + rbody='{"error": {"code": "invalid_expiry_year"}}', + rcode=402, + ) with pytest.raises(stripe.error.CardError) as excinfo: - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) assert excinfo.value.code == "invalid_expiry_year" - def test_rate_limit_error(self, requestor, mock_response): - mock_response('{"error": {}}', 429) + def test_rate_limit_error(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", path=self.valid_path, rbody='{"error": {}}', rcode=429 + ) with pytest.raises(stripe.error.RateLimitError): - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) - def test_old_rate_limit_error(self, requestor, mock_response): + def test_old_rate_limit_error(self, requestor, http_client_mock): """ Tests legacy rate limit error pre-2015-09-18 """ - mock_response('{"error": {"code":"rate_limit"}}', 400) + http_client_mock.stub_request( + "get", + path=self.valid_path, + rbody='{"error": {"code":"rate_limit"}}', + rcode=400, + ) with pytest.raises(stripe.error.RateLimitError): - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) - def test_server_error(self, requestor, mock_response): - mock_response('{"error": {}}', 500) + def test_server_error(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", path=self.valid_path, rbody='{"error": {}}', rcode=500 + ) with pytest.raises(stripe.error.APIError): - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) - def test_invalid_json(self, requestor, mock_response): - mock_response("{", 200) + def test_invalid_json(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", path=self.valid_path, rbody="{", rcode=200 + ) with pytest.raises(stripe.error.APIError): - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) def test_invalid_method(self, requestor): with pytest.raises(stripe.error.APIConnectionError): - requestor.request("foo", "bar") + requestor.request("foo", "bar", base_address="api", api_mode="V1") - def test_oauth_invalid_requestor_error(self, requestor, mock_response): - mock_response('{"error": "invalid_request"}', 400) + def test_oauth_invalid_requestor_error(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", + path=self.valid_path, + rbody='{"error": "invalid_request"}', + rcode=400, + ) with pytest.raises(stripe.oauth_error.InvalidRequestError): - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) - def test_invalid_client_error(self, requestor, mock_response): - mock_response('{"error": "invalid_client"}', 401) + def test_invalid_client_error(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", + path=self.valid_path, + rbody='{"error": "invalid_client"}', + rcode=401, + ) with pytest.raises(stripe.oauth_error.InvalidClientError): - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) - def test_invalid_grant_error(self, requestor, mock_response): - mock_response('{"error": "invalid_grant"}', 400) + def test_invalid_grant_error(self, requestor, http_client_mock): + http_client_mock.stub_request( + "get", + path=self.valid_path, + rbody='{"error": "invalid_grant"}', + rcode=400, + ) with pytest.raises(stripe.oauth_error.InvalidGrantError): - requestor.request("get", self.valid_path, {}) + requestor.request( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) def test_extract_error_from_stream_request_for_bytes( - self, requestor, mock_streaming_response + self, requestor_streaming, http_client_mock_streaming ): - mock_streaming_response( - util.io.BytesIO(b'{"error": "invalid_grant"}'), 400 + http_client_mock_streaming.stub_request( + "get", + path=self.valid_path, + rbody=util.io.BytesIO(b'{"error": "invalid_grant"}'), + rcode=400, ) with pytest.raises(stripe.oauth_error.InvalidGrantError): - requestor.request_stream("get", self.valid_path, {}) + requestor_streaming.request_stream( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) def test_extract_error_from_stream_request_for_response( - self, requestor, mock_streaming_response + self, requestor_streaming, http_client_mock_streaming ): # Responses don't have getvalue, they only have a read method. - mock_streaming_response( - urllib3.response.HTTPResponse( + http_client_mock_streaming.stub_request( + "get", + path=self.valid_path, + rbody=urllib3.response.HTTPResponse( body=util.io.BytesIO(b'{"error": "invalid_grant"}'), preload_content=False, ), - 400, + rcode=400, ) with pytest.raises(stripe.oauth_error.InvalidGrantError): - requestor.request_stream("get", self.valid_path, {}) + requestor_streaming.request_stream( + "get", self.valid_path, {}, base_address="api", api_mode="V1" + ) - def test_raw_request_with_file_param(self, requestor, mock_response): + def test_raw_request_with_file_param(self, requestor, http_client_mock): test_file = tempfile.NamedTemporaryFile() test_file.write("\u263A".encode("utf-16")) test_file.seek(0) + meth = "post" + path = "/v1/files" params = {"file": test_file, "purpose": "dispute_evidence"} supplied_headers = {"Content-Type": "multipart/form-data"} - mock_response("{}", 200) - requestor.request("post", "/v1/files", params, supplied_headers) + http_client_mock.stub_request(meth, path=path, rbody="{}", rcode=200) + requestor.request( + meth, + path, + params, + supplied_headers, + base_address="api", + api_mode="V1", + ) assert supplied_headers["Content-Type"] == "multipart/form-data" @@ -781,21 +811,20 @@ def setup_stripe(self): stripe.api_key = orig_attrs["api_key"] stripe.default_http_client = orig_attrs["default_http_client"] - def test_default_http_client_called(self, mocker): - hc = mocker.Mock(stripe.http_client.HTTPClient) - hc._verify_ssl_certs = True - hc.name = "mockclient" - hc.request_with_retries = mocker.Mock( - return_value=('{"object": "list", "data": []}', 200, {}) + def test_default_http_client_called(self, http_client_mock): + http_client_mock.stub_request( + "get", + path="/v1/charges", + query_string="limit=3", + rbody='{"object": "list", "data": []}', + rcode=200, + rheaders={}, ) - stripe.default_http_client = hc stripe.Charge.list(limit=3) - hc.request_with_retries.assert_called_with( - "get", - "https://api.stripe.com/v1/charges?limit=3", - mocker.ANY, - None, - _usage=None, - ) + last_call = http_client_mock.get_last_call() + + last_call.assert_method("get") + last_call.assert_abs_url("https://api.stripe.com/v1/charges?limit=3") + last_call.assert_post_data(None) diff --git a/tests/test_exports.py b/tests/test_exports.py index 149032109..ebdb2499c 100644 --- a/tests/test_exports.py +++ b/tests/test_exports.py @@ -35,16 +35,6 @@ def test_can_import_stripe_object() -> None: assert StripeObjectFromStripe is StripeObjectFromStripeStripeObject -def test_can_import_api_requestor() -> None: - from stripe.api_requestor import APIRequestor as APIRequestorFromStripeAPIRequestor # type: ignore - from stripe import ( - APIRequestor as APIRequestorFromStripe, - ) - - assert stripe.APIRequestor is APIRequestorFromStripeAPIRequestor - assert APIRequestorFromStripe is APIRequestorFromStripeAPIRequestor - - def test_can_import_request_options() -> None: from stripe.request_options import RequestOptions as RequestOptionsStripeRequestOptions # type: ignore from stripe import ( @@ -403,3 +393,25 @@ def test_can_import_namespaced_resource() -> None: assert_output("stripe.tax is not None", "True") assert_output("stripe.tax.Calculation is not None", "True") + + +def test_can_import_top_level_service() -> None: + from stripe import AccountService as AccountServiceFromStripe + + assert stripe.AccountService == AccountServiceFromStripe + + assert_output("stripe.AccountService is not None", "True") + + +def test_can_import_namespaced_service() -> None: + from stripe import tax as TaxPackage + from stripe.tax import ( + CalculationService as CalculationServiceFromStripe, + ) + + assert stripe.tax is TaxPackage + assert stripe.tax.CalculationService is CalculationServiceFromStripe + assert stripe.tax.CalculationService is TaxPackage.CalculationService + + assert_output("stripe.tax is not None", "True") + assert_output("stripe.tax.CalculationService is not None", "True") diff --git a/tests/test_generated_examples.py b/tests/test_generated_examples.py index 0e1d4daac..d82519e35 100644 --- a/tests/test_generated_examples.py +++ b/tests/test_generated_examples.py @@ -4,6 +4,8 @@ import stripe from tests.http_client_mock import HTTPClientMock +import io +from stripe import StripeClient class TestGeneratedExamples(object): @@ -5292,3 +5294,10219 @@ def test_webhook_endpoints_post_2( query_string="", post_data="url=https%3A%2F%2Fexample.com%2Fnew_endpoint", ) + + def test_account_links_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/account_links", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.account_links.create( + { + "account": "acct_xxxxxxxxxxxxx", + "refresh_url": "https://example.com/reauth", + "return_url": "https://example.com/return", + "type": "account_onboarding", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/account_links", + query_string="", + api_base="https://api.stripe.com", + post_data="account=acct_xxxxxxxxxxxxx&refresh_url=https%3A%2F%2Fexample.com%2Freauth&return_url=https%3A%2F%2Fexample.com%2Freturn&type=account_onboarding", + ) + + def test_accounts_capabilities_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/accounts/acct_xxxxxxxxxxxxx/capabilities", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.capabilities.list("acct_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/accounts/acct_xxxxxxxxxxxxx/capabilities", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_accounts_capabilities_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/accounts/acct_xxxxxxxxxxxxx/capabilities/card_payments", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.capabilities.retrieve( + "acct_xxxxxxxxxxxxx", + "card_payments", + ) + http_client_mock.assert_requested( + "get", + path="/v1/accounts/acct_xxxxxxxxxxxxx/capabilities/card_payments", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_accounts_capabilities_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/accounts/acct_xxxxxxxxxxxxx/capabilities/card_payments", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.capabilities.update( + "acct_xxxxxxxxxxxxx", + "card_payments", + {"requested": True}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/accounts/acct_xxxxxxxxxxxxx/capabilities/card_payments", + query_string="", + api_base="https://api.stripe.com", + post_data="requested=True", + ) + + def test_accounts_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/accounts/acct_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.delete("acct_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/accounts/acct_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_accounts_external_accounts_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts/ba_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.external_accounts.delete( + "acct_xxxxxxxxxxxxx", + "ba_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "delete", + path="/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts/ba_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_accounts_external_accounts_delete_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts/card_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.external_accounts.delete( + "acct_xxxxxxxxxxxxx", + "card_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "delete", + path="/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts/card_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_accounts_external_accounts_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.external_accounts.list( + "acct_xxxxxxxxxxxxx", + {"limit": 3}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_accounts_external_accounts_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts", + "object=bank_account&limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.external_accounts.list( + "acct_xxxxxxxxxxxxx", + {"object": "bank_account", "limit": 3}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts", + query_string="object=bank_account&limit=3", + api_base="https://api.stripe.com", + ) + + def test_accounts_external_accounts_get_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts", + "object=card&limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.external_accounts.list( + "acct_xxxxxxxxxxxxx", + {"object": "card", "limit": 3}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts", + query_string="object=card&limit=3", + api_base="https://api.stripe.com", + ) + + def test_accounts_external_accounts_get_4_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts/ba_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.external_accounts.retrieve( + "acct_xxxxxxxxxxxxx", + "ba_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "get", + path="/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts/ba_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_accounts_external_accounts_get_5_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts/card_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.external_accounts.retrieve( + "acct_xxxxxxxxxxxxx", + "card_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "get", + path="/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts/card_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_accounts_external_accounts_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.external_accounts.create( + "acct_xxxxxxxxxxxxx", + {"external_account": "btok_xxxxxxxxxxxxx"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts", + query_string="", + api_base="https://api.stripe.com", + post_data="external_account=btok_xxxxxxxxxxxxx", + ) + + def test_accounts_external_accounts_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.external_accounts.create( + "acct_xxxxxxxxxxxxx", + {"external_account": "tok_xxxx_debit"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts", + query_string="", + api_base="https://api.stripe.com", + post_data="external_account=tok_xxxx_debit", + ) + + def test_accounts_external_accounts_post_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts/ba_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.external_accounts.update( + "acct_xxxxxxxxxxxxx", + "ba_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts/ba_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_accounts_external_accounts_post_4_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts/card_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.external_accounts.update( + "acct_xxxxxxxxxxxxx", + "card_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/accounts/acct_xxxxxxxxxxxxx/external_accounts/card_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_accounts_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/accounts", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/accounts", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_accounts_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/accounts/acct_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.retrieve("acct_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/accounts/acct_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_accounts_login_links_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/accounts/acct_xxxxxxxxxxxxx/login_links", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.login_links.create("acct_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/accounts/acct_xxxxxxxxxxxxx/login_links", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_accounts_persons_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/accounts/acct_xxxxxxxxxxxxx/persons/person_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.persons.delete( + "acct_xxxxxxxxxxxxx", + "person_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "delete", + path="/v1/accounts/acct_xxxxxxxxxxxxx/persons/person_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_accounts_persons_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/accounts/acct_xxxxxxxxxxxxx/persons", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.persons.list( + "acct_xxxxxxxxxxxxx", + {"limit": 3}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/accounts/acct_xxxxxxxxxxxxx/persons", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_accounts_persons_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/accounts/acct_xxxxxxxxxxxxx/persons/person_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.persons.retrieve( + "acct_xxxxxxxxxxxxx", + "person_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "get", + path="/v1/accounts/acct_xxxxxxxxxxxxx/persons/person_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_accounts_persons_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/accounts/acct_xxxxxxxxxxxxx/persons", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.persons.create( + "acct_xxxxxxxxxxxxx", + {"first_name": "Jane", "last_name": "Diaz"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/accounts/acct_xxxxxxxxxxxxx/persons", + query_string="", + api_base="https://api.stripe.com", + post_data="first_name=Jane&last_name=Diaz", + ) + + def test_accounts_persons_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/accounts/acct_xxxxxxxxxxxxx/persons/person_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.persons.update( + "acct_xxxxxxxxxxxxx", + "person_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/accounts/acct_xxxxxxxxxxxxx/persons/person_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_accounts_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/accounts", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.create( + { + "type": "custom", + "country": "US", + "email": "jenny.rosen@example.com", + "capabilities": { + "card_payments": {"requested": True}, + "transfers": {"requested": True}, + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/accounts", + query_string="", + api_base="https://api.stripe.com", + post_data="type=custom&country=US&email=jenny.rosen%40example.com&capabilities[card_payments][requested]=True&capabilities[transfers][requested]=True", + ) + + def test_accounts_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/accounts/acct_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.update( + "acct_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/accounts/acct_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_accounts_reject_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/accounts/acct_xxxxxxxxxxxxx/reject", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.accounts.reject( + "acct_xxxxxxxxxxxxx", + {"reason": "fraud"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/accounts/acct_xxxxxxxxxxxxx/reject", + query_string="", + api_base="https://api.stripe.com", + post_data="reason=fraud", + ) + + def test_application_fees_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/application_fees", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.application_fees.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/application_fees", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_application_fees_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/application_fees/fee_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.application_fees.retrieve("fee_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/application_fees/fee_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_application_fees_refunds_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/application_fees/fee_xxxxxxxxxxxxx/refunds", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.application_fees.refunds.list( + "fee_xxxxxxxxxxxxx", + {"limit": 3}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/application_fees/fee_xxxxxxxxxxxxx/refunds", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_application_fees_refunds_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/application_fees/fee_xxxxxxxxxxxxx/refunds/fr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.application_fees.refunds.retrieve( + "fee_xxxxxxxxxxxxx", + "fr_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "get", + path="/v1/application_fees/fee_xxxxxxxxxxxxx/refunds/fr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_application_fees_refunds_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/application_fees/fee_xxxxxxxxxxxxx/refunds", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.application_fees.refunds.create("fee_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/application_fees/fee_xxxxxxxxxxxxx/refunds", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_application_fees_refunds_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/application_fees/fee_xxxxxxxxxxxxx/refunds/fr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.application_fees.refunds.update( + "fee_xxxxxxxxxxxxx", + "fr_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/application_fees/fee_xxxxxxxxxxxxx/refunds/fr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_apps_secrets_delete_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/apps/secrets/delete", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.apps.secrets.delete_where( + { + "name": "my-api-key", + "scope": {"type": "account"}, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/apps/secrets/delete", + query_string="", + api_base="https://api.stripe.com", + post_data="name=my-api-key&scope[type]=account", + ) + + def test_apps_secrets_find_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/apps/secrets/find", + "name=sec_123&scope[type]=account", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.apps.secrets.find( + { + "name": "sec_123", + "scope": {"type": "account"}, + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/apps/secrets/find", + query_string="name=sec_123&scope[type]=account", + api_base="https://api.stripe.com", + ) + + def test_apps_secrets_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/apps/secrets", + "scope[type]=account&limit=2", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.apps.secrets.list({"scope": {"type": "account"}, "limit": 2}) + http_client_mock.assert_requested( + "get", + path="/v1/apps/secrets", + query_string="scope[type]=account&limit=2", + api_base="https://api.stripe.com", + ) + + def test_apps_secrets_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/apps/secrets", + "scope[type]=account&limit=2", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.apps.secrets.list({"scope": {"type": "account"}, "limit": 2}) + http_client_mock.assert_requested( + "get", + path="/v1/apps/secrets", + query_string="scope[type]=account&limit=2", + api_base="https://api.stripe.com", + ) + + def test_apps_secrets_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/apps/secrets", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.apps.secrets.create( + { + "name": "sec_123", + "payload": "very secret string", + "scope": {"type": "account"}, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/apps/secrets", + query_string="", + api_base="https://api.stripe.com", + post_data="name=sec_123&payload=very%20secret%20string&scope[type]=account", + ) + + def test_apps_secrets_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/apps/secrets", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.apps.secrets.create( + { + "name": "my-api-key", + "payload": "secret_key_xxxxxx", + "scope": {"type": "account"}, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/apps/secrets", + query_string="", + api_base="https://api.stripe.com", + post_data="name=my-api-key&payload=secret_key_xxxxxx&scope[type]=account", + ) + + def test_balance_transactions_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/balance_transactions", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.balance_transactions.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/balance_transactions", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_balance_transactions_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/balance_transactions/txn_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.balance_transactions.retrieve("txn_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/balance_transactions/txn_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_billing_portal_configurations_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/billing_portal/configurations", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.billing_portal.configurations.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/billing_portal/configurations", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_billing_portal_configurations_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/billing_portal/configurations/bpc_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.billing_portal.configurations.retrieve("bpc_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/billing_portal/configurations/bpc_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_billing_portal_configurations_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/billing_portal/configurations", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.billing_portal.configurations.create( + { + "features": { + "customer_update": { + "allowed_updates": ["email", "tax_id"], + "enabled": True, + }, + "invoice_history": {"enabled": True}, + }, + "business_profile": { + "privacy_policy_url": "https://example.com/privacy", + "terms_of_service_url": "https://example.com/terms", + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/billing_portal/configurations", + query_string="", + api_base="https://api.stripe.com", + post_data="features[customer_update][allowed_updates][0]=email&features[customer_update][allowed_updates][1]=tax_id&features[customer_update][enabled]=True&features[invoice_history][enabled]=True&business_profile[privacy_policy_url]=https%3A%2F%2Fexample.com%2Fprivacy&business_profile[terms_of_service_url]=https%3A%2F%2Fexample.com%2Fterms", + ) + + def test_billing_portal_configurations_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/billing_portal/configurations/bpc_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.billing_portal.configurations.update( + "bpc_xxxxxxxxxxxxx", + { + "business_profile": { + "privacy_policy_url": "https://example.com/privacy", + "terms_of_service_url": "https://example.com/terms", + }, + }, + ) + http_client_mock.assert_requested( + "post", + path="/v1/billing_portal/configurations/bpc_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="business_profile[privacy_policy_url]=https%3A%2F%2Fexample.com%2Fprivacy&business_profile[terms_of_service_url]=https%3A%2F%2Fexample.com%2Fterms", + ) + + def test_billing_portal_sessions_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/billing_portal/sessions", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.billing_portal.sessions.create( + { + "customer": "cus_xxxxxxxxxxxxx", + "return_url": "https://example.com/account", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/billing_portal/sessions", + query_string="", + api_base="https://api.stripe.com", + post_data="customer=cus_xxxxxxxxxxxxx&return_url=https%3A%2F%2Fexample.com%2Faccount", + ) + + def test_charges_capture_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/charges/ch_xxxxxxxxxxxxx/capture", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.charges.capture("ch_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/charges/ch_xxxxxxxxxxxxx/capture", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_charges_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/charges", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.charges.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/charges", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_charges_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/charges/ch_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.charges.retrieve("ch_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/charges/ch_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_charges_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/charges", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.charges.create( + { + "amount": 2000, + "currency": "usd", + "source": "tok_xxxx", + "description": "My First Test Charge (created for API docs at https://www.stripe.com/docs/api)", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/charges", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=2000¤cy=usd&source=tok_xxxx&description=My%20First%20Test%20Charge%20%28created%20for%20API%20docs%20at%20https%3A%2F%2Fwww.stripe.com%2Fdocs%2Fapi%29", + ) + + def test_charges_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/charges/ch_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.charges.update( + "ch_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/charges/ch_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_charges_search_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/charges/search", + "query=amount%3E999%20AND%20metadata%5B%27order_id%27%5D%3A%276735%27", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.charges.search( + { + "query": "amount>999 AND metadata['order_id']:'6735'", + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/charges/search", + query_string="query=amount%3E999%20AND%20metadata%5B%27order_id%27%5D%3A%276735%27", + api_base="https://api.stripe.com", + ) + + def test_checkout_sessions_expire_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/checkout/sessions/sess_xyz/expire", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.checkout.sessions.expire("sess_xyz") + http_client_mock.assert_requested( + "post", + path="/v1/checkout/sessions/sess_xyz/expire", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_checkout_sessions_expire_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/checkout/sessions/cs_test_xxxxxxxxxxxxx/expire", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.checkout.sessions.expire("cs_test_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/checkout/sessions/cs_test_xxxxxxxxxxxxx/expire", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_checkout_sessions_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/checkout/sessions", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.checkout.sessions.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/checkout/sessions", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_checkout_sessions_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/checkout/sessions/cs_test_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.checkout.sessions.retrieve("cs_test_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/checkout/sessions/cs_test_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_checkout_sessions_line_items_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/checkout/sessions/sess_xyz/line_items", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.checkout.sessions.line_items.list("sess_xyz") + http_client_mock.assert_requested( + "get", + path="/v1/checkout/sessions/sess_xyz/line_items", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_checkout_sessions_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/checkout/sessions", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.checkout.sessions.create( + { + "success_url": "https://example.com/success", + "cancel_url": "https://example.com/cancel", + "mode": "payment", + "shipping_options": [ + {"shipping_rate": "shr_standard"}, + { + "shipping_rate_data": { + "display_name": "Standard", + "delivery_estimate": { + "minimum": {"unit": "day", "value": 5}, + "maximum": {"unit": "day", "value": 7}, + }, + }, + }, + ], + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/checkout/sessions", + query_string="", + api_base="https://api.stripe.com", + post_data="success_url=https%3A%2F%2Fexample.com%2Fsuccess&cancel_url=https%3A%2F%2Fexample.com%2Fcancel&mode=payment&shipping_options[0][shipping_rate]=shr_standard&shipping_options[1][shipping_rate_data][display_name]=Standard&shipping_options[1][shipping_rate_data][delivery_estimate][minimum][unit]=day&shipping_options[1][shipping_rate_data][delivery_estimate][minimum][value]=5&shipping_options[1][shipping_rate_data][delivery_estimate][maximum][unit]=day&shipping_options[1][shipping_rate_data][delivery_estimate][maximum][value]=7", + ) + + def test_checkout_sessions_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/checkout/sessions", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.checkout.sessions.create( + { + "success_url": "https://example.com/success", + "line_items": [ + {"price": "price_xxxxxxxxxxxxx", "quantity": 2} + ], + "mode": "payment", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/checkout/sessions", + query_string="", + api_base="https://api.stripe.com", + post_data="success_url=https%3A%2F%2Fexample.com%2Fsuccess&line_items[0][price]=price_xxxxxxxxxxxxx&line_items[0][quantity]=2&mode=payment", + ) + + def test_country_specs_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/country_specs", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.country_specs.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/country_specs", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_country_specs_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/country_specs/US", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.country_specs.retrieve("US") + http_client_mock.assert_requested( + "get", + path="/v1/country_specs/US", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_coupons_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/coupons/Z4OV52SU", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.coupons.delete("Z4OV52SU") + http_client_mock.assert_requested( + "delete", + path="/v1/coupons/Z4OV52SU", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_coupons_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/coupons", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.coupons.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/coupons", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_coupons_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/coupons/Z4OV52SU", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.coupons.retrieve("Z4OV52SU") + http_client_mock.assert_requested( + "get", + path="/v1/coupons/Z4OV52SU", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_coupons_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/coupons", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.coupons.create( + { + "percent_off": 25.5, + "duration": "repeating", + "duration_in_months": 3, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/coupons", + query_string="", + api_base="https://api.stripe.com", + post_data="percent_off=25.5&duration=repeating&duration_in_months=3", + ) + + def test_coupons_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/coupons/Z4OV52SU", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.coupons.update( + "Z4OV52SU", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/coupons/Z4OV52SU", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_credit_notes_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/credit_notes", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.credit_notes.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/credit_notes", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_credit_notes_lines_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/credit_notes/cn_xxxxxxxxxxxxx/lines", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.credit_notes.line_items.list( + "cn_xxxxxxxxxxxxx", + {"limit": 3}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/credit_notes/cn_xxxxxxxxxxxxx/lines", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_credit_notes_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/credit_notes", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.credit_notes.create( + { + "invoice": "in_xxxxxxxxxxxxx", + "lines": [ + { + "type": "invoice_line_item", + "invoice_line_item": "il_xxxxxxxxxxxxx", + "quantity": 1, + }, + ], + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/credit_notes", + query_string="", + api_base="https://api.stripe.com", + post_data="invoice=in_xxxxxxxxxxxxx&lines[0][type]=invoice_line_item&lines[0][invoice_line_item]=il_xxxxxxxxxxxxx&lines[0][quantity]=1", + ) + + def test_credit_notes_preview_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/credit_notes/preview", + "invoice=in_xxxxxxxxxxxxx&lines[0][type]=invoice_line_item&lines[0][invoice_line_item]=il_xxxxxxxxxxxxx&lines[0][quantity]=1", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.credit_notes.preview( + { + "invoice": "in_xxxxxxxxxxxxx", + "lines": [ + { + "type": "invoice_line_item", + "invoice_line_item": "il_xxxxxxxxxxxxx", + "quantity": 1, + }, + ], + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/credit_notes/preview", + query_string="invoice=in_xxxxxxxxxxxxx&lines[0][type]=invoice_line_item&lines[0][invoice_line_item]=il_xxxxxxxxxxxxx&lines[0][quantity]=1", + api_base="https://api.stripe.com", + ) + + def test_credit_notes_preview_lines_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/credit_notes/preview/lines", + "limit=3&invoice=in_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.credit_notes.preview_lines.list( + { + "limit": 3, + "invoice": "in_xxxxxxxxxxxxx", + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/credit_notes/preview/lines", + query_string="limit=3&invoice=in_xxxxxxxxxxxxx", + api_base="https://api.stripe.com", + ) + + def test_credit_notes_void_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/credit_notes/cn_xxxxxxxxxxxxx/void", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.credit_notes.void_credit_note("cn_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/credit_notes/cn_xxxxxxxxxxxxx/void", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_customer_sessions_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customer_sessions", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customer_sessions.create( + { + "customer": "cus_123", + "components": {"buy_button": {"enabled": True}}, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/customer_sessions", + query_string="", + api_base="https://api.stripe.com", + post_data="customer=cus_123&components[buy_button][enabled]=True", + ) + + def test_customers_balance_transactions_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/cus_xxxxxxxxxxxxx/balance_transactions", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.balance_transactions.list( + "cus_xxxxxxxxxxxxx", + {"limit": 3}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx/balance_transactions", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_customers_balance_transactions_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/cus_xxxxxxxxxxxxx/balance_transactions/cbtxn_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.balance_transactions.retrieve( + "cus_xxxxxxxxxxxxx", + "cbtxn_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx/balance_transactions/cbtxn_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_customers_balance_transactions_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customers/cus_xxxxxxxxxxxxx/balance_transactions", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.balance_transactions.create( + "cus_xxxxxxxxxxxxx", + {"amount": -500, "currency": "usd"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/customers/cus_xxxxxxxxxxxxx/balance_transactions", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=-500¤cy=usd", + ) + + def test_customers_balance_transactions_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customers/cus_xxxxxxxxxxxxx/balance_transactions/cbtxn_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.balance_transactions.update( + "cus_xxxxxxxxxxxxx", + "cbtxn_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/customers/cus_xxxxxxxxxxxxx/balance_transactions/cbtxn_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_customers_cash_balance_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/cus_123/cash_balance", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.cash_balance.retrieve("cus_123") + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_123/cash_balance", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_customers_cash_balance_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customers/cus_123/cash_balance", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.cash_balance.update( + "cus_123", + {"settings": {"reconciliation_mode": "manual"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/customers/cus_123/cash_balance", + query_string="", + api_base="https://api.stripe.com", + post_data="settings[reconciliation_mode]=manual", + ) + + def test_customers_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/customers/cus_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.delete("cus_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/customers/cus_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_customers_funding_instructions_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customers/cus_123/funding_instructions", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.funding_instructions.create( + "cus_123", + { + "bank_transfer": { + "requested_address_types": ["zengin"], + "type": "jp_bank_transfer", + }, + "currency": "usd", + "funding_type": "bank_transfer", + }, + ) + http_client_mock.assert_requested( + "post", + path="/v1/customers/cus_123/funding_instructions", + query_string="", + api_base="https://api.stripe.com", + post_data="bank_transfer[requested_address_types][0]=zengin&bank_transfer[type]=jp_bank_transfer¤cy=usd&funding_type=bank_transfer", + ) + + def test_customers_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/customers", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_customers_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/customers", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_customers_get_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/cus_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.retrieve("cus_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_customers_payment_methods_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/cus_xyz/payment_methods", + "type=card", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.payment_methods.list( + "cus_xyz", + {"type": "card"}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xyz/payment_methods", + query_string="type=card", + api_base="https://api.stripe.com", + ) + + def test_customers_payment_methods_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/cus_xxxxxxxxxxxxx/payment_methods", + "type=card", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.payment_methods.list( + "cus_xxxxxxxxxxxxx", + {"type": "card"}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx/payment_methods", + query_string="type=card", + api_base="https://api.stripe.com", + ) + + def test_customers_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customers", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.create( + { + "description": "My First Test Customer (created for API docs at https://www.stripe.com/docs/api)", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/customers", + query_string="", + api_base="https://api.stripe.com", + post_data="description=My%20First%20Test%20Customer%20%28created%20for%20API%20docs%20at%20https%3A%2F%2Fwww.stripe.com%2Fdocs%2Fapi%29", + ) + + def test_customers_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customers/cus_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.update( + "cus_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/customers/cus_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_customers_search_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/search", + "query=name%3A%27fakename%27%20AND%20metadata%5B%27foo%27%5D%3A%27bar%27", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.search( + { + "query": "name:'fakename' AND metadata['foo']:'bar'", + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/customers/search", + query_string="query=name%3A%27fakename%27%20AND%20metadata%5B%27foo%27%5D%3A%27bar%27", + api_base="https://api.stripe.com", + ) + + def test_customers_search_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/search", + "query=name%3A%27fakename%27%20AND%20metadata%5B%27foo%27%5D%3A%27bar%27", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.search( + { + "query": "name:'fakename' AND metadata['foo']:'bar'", + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/customers/search", + query_string="query=name%3A%27fakename%27%20AND%20metadata%5B%27foo%27%5D%3A%27bar%27", + api_base="https://api.stripe.com", + ) + + def test_customers_sources_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/customers/cus_xxxxxxxxxxxxx/sources/ba_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.sources.detach( + "cus_xxxxxxxxxxxxx", + "ba_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "delete", + path="/v1/customers/cus_xxxxxxxxxxxxx/sources/ba_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_customers_sources_delete_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/customers/cus_xxxxxxxxxxxxx/sources/card_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.sources.detach( + "cus_xxxxxxxxxxxxx", + "card_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "delete", + path="/v1/customers/cus_xxxxxxxxxxxxx/sources/card_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_customers_sources_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/cus_xxxxxxxxxxxxx/sources", + "object=bank_account&limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.payment_sources.list( + "cus_xxxxxxxxxxxxx", + {"object": "bank_account", "limit": 3}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx/sources", + query_string="object=bank_account&limit=3", + api_base="https://api.stripe.com", + ) + + def test_customers_sources_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/cus_xxxxxxxxxxxxx/sources", + "object=card&limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.payment_sources.list( + "cus_xxxxxxxxxxxxx", + {"object": "card", "limit": 3}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx/sources", + query_string="object=card&limit=3", + api_base="https://api.stripe.com", + ) + + def test_customers_sources_get_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/cus_xxxxxxxxxxxxx/sources/ba_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.payment_sources.retrieve( + "cus_xxxxxxxxxxxxx", + "ba_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx/sources/ba_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_customers_sources_get_4_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/cus_xxxxxxxxxxxxx/sources/card_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.payment_sources.retrieve( + "cus_xxxxxxxxxxxxx", + "card_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx/sources/card_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_customers_sources_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customers/cus_123/sources/card_123", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.payment_sources.update( + "cus_123", + "card_123", + {"account_holder_name": "Kamil"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/customers/cus_123/sources/card_123", + query_string="", + api_base="https://api.stripe.com", + post_data="account_holder_name=Kamil", + ) + + def test_customers_sources_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customers/cus_xxxxxxxxxxxxx/sources", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.payment_sources.create( + "cus_xxxxxxxxxxxxx", + {"source": "btok_xxxxxxxxxxxxx"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/customers/cus_xxxxxxxxxxxxx/sources", + query_string="", + api_base="https://api.stripe.com", + post_data="source=btok_xxxxxxxxxxxxx", + ) + + def test_customers_sources_post_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customers/cus_xxxxxxxxxxxxx/sources", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.payment_sources.create( + "cus_xxxxxxxxxxxxx", + {"source": "tok_xxxx"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/customers/cus_xxxxxxxxxxxxx/sources", + query_string="", + api_base="https://api.stripe.com", + post_data="source=tok_xxxx", + ) + + def test_customers_sources_post_4_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customers/cus_xxxxxxxxxxxxx/sources/ba_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.payment_sources.update( + "cus_xxxxxxxxxxxxx", + "ba_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/customers/cus_xxxxxxxxxxxxx/sources/ba_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_customers_sources_post_5_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customers/cus_xxxxxxxxxxxxx/sources/card_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.payment_sources.update( + "cus_xxxxxxxxxxxxx", + "card_xxxxxxxxxxxxx", + {"name": "Jenny Rosen"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/customers/cus_xxxxxxxxxxxxx/sources/card_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="name=Jenny%20Rosen", + ) + + def test_customers_sources_verify_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customers/cus_xxxxxxxxxxxxx/sources/ba_xxxxxxxxxxxxx/verify", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.payment_sources.verify( + "cus_xxxxxxxxxxxxx", + "ba_xxxxxxxxxxxxx", + {"amounts": [32, 45]}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/customers/cus_xxxxxxxxxxxxx/sources/ba_xxxxxxxxxxxxx/verify", + query_string="", + api_base="https://api.stripe.com", + post_data="amounts[0]=32&amounts[1]=45", + ) + + def test_customers_tax_ids_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/customers/cus_xxxxxxxxxxxxx/tax_ids/txi_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.tax_ids.delete( + "cus_xxxxxxxxxxxxx", + "txi_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "delete", + path="/v1/customers/cus_xxxxxxxxxxxxx/tax_ids/txi_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_customers_tax_ids_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/cus_xxxxxxxxxxxxx/tax_ids", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.tax_ids.list( + "cus_xxxxxxxxxxxxx", + {"limit": 3}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx/tax_ids", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_customers_tax_ids_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/customers/cus_xxxxxxxxxxxxx/tax_ids/txi_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.tax_ids.retrieve( + "cus_xxxxxxxxxxxxx", + "txi_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx/tax_ids/txi_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_customers_tax_ids_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/customers/cus_xxxxxxxxxxxxx/tax_ids", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.customers.tax_ids.create( + "cus_xxxxxxxxxxxxx", + {"type": "eu_vat", "value": "DE123456789"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/customers/cus_xxxxxxxxxxxxx/tax_ids", + query_string="", + api_base="https://api.stripe.com", + post_data="type=eu_vat&value=DE123456789", + ) + + def test_disputes_close_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/disputes/dp_xxxxxxxxxxxxx/close", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.disputes.close("dp_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/disputes/dp_xxxxxxxxxxxxx/close", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_disputes_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/disputes", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.disputes.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/disputes", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_disputes_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/disputes/dp_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.disputes.retrieve("dp_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/disputes/dp_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_disputes_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/disputes/dp_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.disputes.update( + "dp_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/disputes/dp_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_events_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/events", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.events.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/events", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_events_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/events/evt_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.events.retrieve("evt_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/events/evt_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_file_links_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/file_links", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.file_links.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/file_links", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_file_links_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/file_links/link_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.file_links.retrieve("link_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/file_links/link_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_file_links_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/file_links", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.file_links.create({"file": "file_xxxxxxxxxxxxx"}) + http_client_mock.assert_requested( + "post", + path="/v1/file_links", + query_string="", + api_base="https://api.stripe.com", + post_data="file=file_xxxxxxxxxxxxx", + ) + + def test_file_links_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/file_links/link_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.file_links.update( + "link_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/file_links/link_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_files_get_service(self, http_client_mock: HTTPClientMock) -> None: + http_client_mock.stub_request( + "get", + "/v1/files", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.files.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/files", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_files_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/files/file_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.files.retrieve("file_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/files/file_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_files_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/files", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.files.create( + { + "purpose": "account_requirement", + "file": io.StringIO("foo"), + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/files", + query_string="", + api_base="https://files.stripe.com", + ) + + def test_financial_connections_accounts_disconnect_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/financial_connections/accounts/fca_xyz/disconnect", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.accounts.disconnect("fca_xyz") + http_client_mock.assert_requested( + "post", + path="/v1/financial_connections/accounts/fca_xyz/disconnect", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_financial_connections_accounts_disconnect_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/financial_connections/accounts/fca_xxxxxxxxxxxxx/disconnect", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.accounts.disconnect("fca_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/financial_connections/accounts/fca_xxxxxxxxxxxxx/disconnect", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_financial_connections_accounts_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/financial_connections/accounts", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.accounts.list() + http_client_mock.assert_requested( + "get", + path="/v1/financial_connections/accounts", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_financial_connections_accounts_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/financial_connections/accounts/fca_xyz", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.accounts.retrieve("fca_xyz") + http_client_mock.assert_requested( + "get", + path="/v1/financial_connections/accounts/fca_xyz", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_financial_connections_accounts_get_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/financial_connections/accounts", + "account_holder[customer]=cus_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.accounts.list( + { + "account_holder": {"customer": "cus_xxxxxxxxxxxxx"}, + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/financial_connections/accounts", + query_string="account_holder[customer]=cus_xxxxxxxxxxxxx", + api_base="https://api.stripe.com", + ) + + def test_financial_connections_accounts_get_4_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/financial_connections/accounts/fca_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.accounts.retrieve("fca_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/financial_connections/accounts/fca_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_financial_connections_accounts_owners_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/financial_connections/accounts/fca_xyz/owners", + "ownership=fcaowns_xyz", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.accounts.owners.list( + "fca_xyz", + {"ownership": "fcaowns_xyz"}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/financial_connections/accounts/fca_xyz/owners", + query_string="ownership=fcaowns_xyz", + api_base="https://api.stripe.com", + ) + + def test_financial_connections_accounts_owners_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/financial_connections/accounts/fca_xxxxxxxxxxxxx/owners", + "limit=3&ownership=fcaowns_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.accounts.owners.list( + "fca_xxxxxxxxxxxxx", + {"limit": 3, "ownership": "fcaowns_xxxxxxxxxxxxx"}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/financial_connections/accounts/fca_xxxxxxxxxxxxx/owners", + query_string="limit=3&ownership=fcaowns_xxxxxxxxxxxxx", + api_base="https://api.stripe.com", + ) + + def test_financial_connections_accounts_refresh_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/financial_connections/accounts/fca_xyz/refresh", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.accounts.refresh( + "fca_xyz", + {"features": ["balance"]}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/financial_connections/accounts/fca_xyz/refresh", + query_string="", + api_base="https://api.stripe.com", + post_data="features[0]=balance", + ) + + def test_financial_connections_accounts_subscribe_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/financial_connections/accounts/fa_123/subscribe", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.accounts.subscribe( + "fa_123", + {"features": ["transactions"]}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/financial_connections/accounts/fa_123/subscribe", + query_string="", + api_base="https://api.stripe.com", + post_data="features[0]=transactions", + ) + + def test_financial_connections_accounts_unsubscribe_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/financial_connections/accounts/fa_123/unsubscribe", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.accounts.unsubscribe( + "fa_123", + {"features": ["transactions"]}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/financial_connections/accounts/fa_123/unsubscribe", + query_string="", + api_base="https://api.stripe.com", + post_data="features[0]=transactions", + ) + + def test_financial_connections_sessions_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/financial_connections/sessions/fcsess_xyz", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.sessions.retrieve("fcsess_xyz") + http_client_mock.assert_requested( + "get", + path="/v1/financial_connections/sessions/fcsess_xyz", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_financial_connections_sessions_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/financial_connections/sessions/fcsess_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.sessions.retrieve("fcsess_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/financial_connections/sessions/fcsess_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_financial_connections_sessions_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/financial_connections/sessions", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.sessions.create( + { + "account_holder": {"type": "customer", "customer": "cus_123"}, + "permissions": ["balances"], + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/financial_connections/sessions", + query_string="", + api_base="https://api.stripe.com", + post_data="account_holder[type]=customer&account_holder[customer]=cus_123&permissions[0]=balances", + ) + + def test_financial_connections_sessions_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/financial_connections/sessions", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.sessions.create( + { + "account_holder": { + "type": "customer", + "customer": "cus_xxxxxxxxxxxxx", + }, + "permissions": ["payment_method", "balances"], + "filters": {"countries": ["US"]}, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/financial_connections/sessions", + query_string="", + api_base="https://api.stripe.com", + post_data="account_holder[type]=customer&account_holder[customer]=cus_xxxxxxxxxxxxx&permissions[0]=payment_method&permissions[1]=balances&filters[countries][0]=US", + ) + + def test_financial_connections_transactions_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/financial_connections/transactions/tr_123", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.transactions.retrieve("tr_123") + http_client_mock.assert_requested( + "get", + path="/v1/financial_connections/transactions/tr_123", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_financial_connections_transactions_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/financial_connections/transactions", + "account=fca_xyz", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.financial_connections.transactions.list({"account": "fca_xyz"}) + http_client_mock.assert_requested( + "get", + path="/v1/financial_connections/transactions", + query_string="account=fca_xyz", + api_base="https://api.stripe.com", + ) + + def test_identity_verification_reports_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/identity/verification_reports", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.identity.verification_reports.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/identity/verification_reports", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_identity_verification_reports_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/identity/verification_reports/vr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.identity.verification_reports.retrieve("vr_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/identity/verification_reports/vr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_identity_verification_sessions_cancel_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/identity/verification_sessions/vs_xxxxxxxxxxxxx/cancel", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.identity.verification_sessions.cancel("vs_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/identity/verification_sessions/vs_xxxxxxxxxxxxx/cancel", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_identity_verification_sessions_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/identity/verification_sessions", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.identity.verification_sessions.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/identity/verification_sessions", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_identity_verification_sessions_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/identity/verification_sessions/vs_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.identity.verification_sessions.retrieve("vs_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/identity/verification_sessions/vs_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_identity_verification_sessions_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/identity/verification_sessions", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.identity.verification_sessions.create({"type": "document"}) + http_client_mock.assert_requested( + "post", + path="/v1/identity/verification_sessions", + query_string="", + api_base="https://api.stripe.com", + post_data="type=document", + ) + + def test_identity_verification_sessions_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/identity/verification_sessions/vs_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.identity.verification_sessions.update( + "vs_xxxxxxxxxxxxx", + {"type": "id_number"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/identity/verification_sessions/vs_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="type=id_number", + ) + + def test_identity_verification_sessions_redact_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/identity/verification_sessions/vs_xxxxxxxxxxxxx/redact", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.identity.verification_sessions.redact("vs_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/identity/verification_sessions/vs_xxxxxxxxxxxxx/redact", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_invoiceitems_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/invoiceitems/ii_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoice_items.delete("ii_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/invoiceitems/ii_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_invoiceitems_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/invoiceitems", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoice_items.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/invoiceitems", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_invoiceitems_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/invoiceitems/ii_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoice_items.retrieve("ii_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/invoiceitems/ii_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_invoiceitems_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/invoiceitems", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoice_items.create( + { + "customer": "cus_xxxxxxxxxxxxx", + "price": "price_xxxxxxxxxxxxx", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/invoiceitems", + query_string="", + api_base="https://api.stripe.com", + post_data="customer=cus_xxxxxxxxxxxxx&price=price_xxxxxxxxxxxxx", + ) + + def test_invoiceitems_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/invoiceitems/ii_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoice_items.update( + "ii_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/invoiceitems/ii_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_invoices_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/invoices/in_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoices.delete("in_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/invoices/in_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_invoices_finalize_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/invoices/in_xxxxxxxxxxxxx/finalize", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoices.finalize_invoice("in_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/invoices/in_xxxxxxxxxxxxx/finalize", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_invoices_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/invoices", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoices.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/invoices", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_invoices_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/invoices/in_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoices.retrieve("in_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/invoices/in_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_invoices_get_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/invoices/in_xxxxxxxxxxxxx", + "expand[0]=customer", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoices.retrieve( + "in_xxxxxxxxxxxxx", + {"expand": ["customer"]}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/invoices/in_xxxxxxxxxxxxx", + query_string="expand[0]=customer", + api_base="https://api.stripe.com", + ) + + def test_invoices_mark_uncollectible_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/invoices/in_xxxxxxxxxxxxx/mark_uncollectible", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoices.mark_uncollectible("in_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/invoices/in_xxxxxxxxxxxxx/mark_uncollectible", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_invoices_pay_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/invoices/in_xxxxxxxxxxxxx/pay", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoices.pay("in_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/invoices/in_xxxxxxxxxxxxx/pay", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_invoices_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/invoices", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoices.create({"customer": "cus_xxxxxxxxxxxxx"}) + http_client_mock.assert_requested( + "post", + path="/v1/invoices", + query_string="", + api_base="https://api.stripe.com", + post_data="customer=cus_xxxxxxxxxxxxx", + ) + + def test_invoices_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/invoices/in_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoices.update( + "in_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/invoices/in_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_invoices_search_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/invoices/search", + "query=total%3E999%20AND%20metadata%5B%27order_id%27%5D%3A%276735%27", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoices.search( + { + "query": "total>999 AND metadata['order_id']:'6735'", + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/invoices/search", + query_string="query=total%3E999%20AND%20metadata%5B%27order_id%27%5D%3A%276735%27", + api_base="https://api.stripe.com", + ) + + def test_invoices_send_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/invoices/in_xxxxxxxxxxxxx/send", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoices.send_invoice("in_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/invoices/in_xxxxxxxxxxxxx/send", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_invoices_upcoming_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/invoices/upcoming", + "customer=cus_9utnxg47pWjV1e", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoices.upcoming({"customer": "cus_9utnxg47pWjV1e"}) + http_client_mock.assert_requested( + "get", + path="/v1/invoices/upcoming", + query_string="customer=cus_9utnxg47pWjV1e", + api_base="https://api.stripe.com", + ) + + def test_invoices_void_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/invoices/in_xxxxxxxxxxxxx/void", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.invoices.void_invoice("in_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/invoices/in_xxxxxxxxxxxxx/void", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_issuing_authorizations_approve_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/issuing/authorizations/iauth_xxxxxxxxxxxxx/approve", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.authorizations.approve("iauth_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/issuing/authorizations/iauth_xxxxxxxxxxxxx/approve", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_issuing_authorizations_decline_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/issuing/authorizations/iauth_xxxxxxxxxxxxx/decline", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.authorizations.decline("iauth_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/issuing/authorizations/iauth_xxxxxxxxxxxxx/decline", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_issuing_authorizations_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/issuing/authorizations", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.authorizations.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/issuing/authorizations", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_issuing_authorizations_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/issuing/authorizations/iauth_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.authorizations.retrieve("iauth_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/issuing/authorizations/iauth_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_issuing_authorizations_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/issuing/authorizations/iauth_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.authorizations.update( + "iauth_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/issuing/authorizations/iauth_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_issuing_cardholders_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/issuing/cardholders", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.cardholders.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/issuing/cardholders", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_issuing_cardholders_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/issuing/cardholders/ich_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.cardholders.retrieve("ich_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/issuing/cardholders/ich_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_issuing_cardholders_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/issuing/cardholders", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.cardholders.create( + { + "type": "individual", + "name": "Jenny Rosen", + "email": "jenny.rosen@example.com", + "phone_number": "+18888675309", + "billing": { + "address": { + "line1": "1234 Main Street", + "city": "San Francisco", + "state": "CA", + "country": "US", + "postal_code": "94111", + }, + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/issuing/cardholders", + query_string="", + api_base="https://api.stripe.com", + post_data="type=individual&name=Jenny%20Rosen&email=jenny.rosen%40example.com&phone_number=%2B18888675309&billing[address][line1]=1234%20Main%20Street&billing[address][city]=San%20Francisco&billing[address][state]=CA&billing[address][country]=US&billing[address][postal_code]=94111", + ) + + def test_issuing_cardholders_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/issuing/cardholders/ich_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.cardholders.update( + "ich_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/issuing/cardholders/ich_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_issuing_cards_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/issuing/cards", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.cards.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/issuing/cards", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_issuing_cards_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/issuing/cards/ic_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.cards.retrieve("ic_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/issuing/cards/ic_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_issuing_cards_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/issuing/cards", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.cards.create( + { + "cardholder": "ich_xxxxxxxxxxxxx", + "currency": "usd", + "type": "virtual", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/issuing/cards", + query_string="", + api_base="https://api.stripe.com", + post_data="cardholder=ich_xxxxxxxxxxxxx¤cy=usd&type=virtual", + ) + + def test_issuing_cards_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/issuing/cards/ic_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.cards.update( + "ic_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/issuing/cards/ic_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_issuing_disputes_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/issuing/disputes", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.disputes.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/issuing/disputes", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_issuing_disputes_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/issuing/disputes/idp_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.disputes.retrieve("idp_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/issuing/disputes/idp_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_issuing_disputes_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/issuing/disputes", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.disputes.create( + { + "transaction": "ipi_xxxxxxxxxxxxx", + "evidence": { + "reason": "fraudulent", + "fraudulent": { + "explanation": "Purchase was unrecognized." + }, + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/issuing/disputes", + query_string="", + api_base="https://api.stripe.com", + post_data="transaction=ipi_xxxxxxxxxxxxx&evidence[reason]=fraudulent&evidence[fraudulent][explanation]=Purchase%20was%20unrecognized.", + ) + + def test_issuing_disputes_submit_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/issuing/disputes/idp_xxxxxxxxxxxxx/submit", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.disputes.submit("idp_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/issuing/disputes/idp_xxxxxxxxxxxxx/submit", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_issuing_transactions_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/issuing/transactions", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.transactions.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/issuing/transactions", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_issuing_transactions_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/issuing/transactions/ipi_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.transactions.retrieve("ipi_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/issuing/transactions/ipi_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_issuing_transactions_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/issuing/transactions/ipi_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.issuing.transactions.update( + "ipi_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/issuing/transactions/ipi_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_mandates_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/mandates/mandate_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.mandates.retrieve("mandate_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/mandates/mandate_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payment_intents_apply_customer_balance_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_intents/pi_xxxxxxxxxxxxx/apply_customer_balance", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.apply_customer_balance("pi_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/payment_intents/pi_xxxxxxxxxxxxx/apply_customer_balance", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payment_intents_cancel_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_intents/pi_xxxxxxxxxxxxx/cancel", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.cancel("pi_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/payment_intents/pi_xxxxxxxxxxxxx/cancel", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payment_intents_capture_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_intents/pi_xxxxxxxxxxxxx/capture", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.capture("pi_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/payment_intents/pi_xxxxxxxxxxxxx/capture", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payment_intents_confirm_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_intents/pi_xxxxxxxxxxxxx/confirm", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.confirm( + "pi_xxxxxxxxxxxxx", + {"payment_method": "pm_card_visa"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_intents/pi_xxxxxxxxxxxxx/confirm", + query_string="", + api_base="https://api.stripe.com", + post_data="payment_method=pm_card_visa", + ) + + def test_payment_intents_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/payment_intents", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/payment_intents", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_payment_intents_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/payment_intents/pi_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.retrieve("pi_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/payment_intents/pi_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payment_intents_increment_authorization_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_intents/pi_xxxxxxxxxxxxx/increment_authorization", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.increment_authorization( + "pi_xxxxxxxxxxxxx", + {"amount": 2099}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_intents/pi_xxxxxxxxxxxxx/increment_authorization", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=2099", + ) + + def test_payment_intents_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_intents", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.create( + { + "amount": 1099, + "currency": "eur", + "automatic_payment_methods": {"enabled": True}, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_intents", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=1099¤cy=eur&automatic_payment_methods[enabled]=True", + ) + + def test_payment_intents_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_intents", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.create( + { + "amount": 2000, + "currency": "usd", + "automatic_payment_methods": {"enabled": True}, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_intents", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=2000¤cy=usd&automatic_payment_methods[enabled]=True", + ) + + def test_payment_intents_post_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_intents/pi_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.update( + "pi_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_intents/pi_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_payment_intents_post_4_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_intents", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.create( + { + "amount": 200, + "currency": "usd", + "payment_method_data": { + "type": "p24", + "p24": {"bank": "blik"}, + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_intents", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=200¤cy=usd&payment_method_data[type]=p24&payment_method_data[p24][bank]=blik", + ) + + def test_payment_intents_search_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/payment_intents/search", + "query=status%3A%27succeeded%27%20AND%20metadata%5B%27order_id%27%5D%3A%276735%27", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.search( + { + "query": "status:'succeeded' AND metadata['order_id']:'6735'", + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/payment_intents/search", + query_string="query=status%3A%27succeeded%27%20AND%20metadata%5B%27order_id%27%5D%3A%276735%27", + api_base="https://api.stripe.com", + ) + + def test_payment_intents_verify_microdeposits_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_intents/pi_xxxxxxxxxxxxx/verify_microdeposits", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.verify_microdeposits("pi_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/payment_intents/pi_xxxxxxxxxxxxx/verify_microdeposits", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payment_intents_verify_microdeposits_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_intents/pi_xxxxxxxxxxxxx/verify_microdeposits", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_intents.verify_microdeposits( + "pi_xxxxxxxxxxxxx", + {"amounts": [32, 45]}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_intents/pi_xxxxxxxxxxxxx/verify_microdeposits", + query_string="", + api_base="https://api.stripe.com", + post_data="amounts[0]=32&amounts[1]=45", + ) + + def test_payment_links_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/payment_links/pl_xyz", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_links.retrieve("pl_xyz") + http_client_mock.assert_requested( + "get", + path="/v1/payment_links/pl_xyz", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payment_links_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/payment_links", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_links.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/payment_links", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_payment_links_get_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/payment_links/plink_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_links.retrieve("plink_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/payment_links/plink_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payment_links_line_items_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/payment_links/pl_xyz/line_items", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_links.line_items.list("pl_xyz") + http_client_mock.assert_requested( + "get", + path="/v1/payment_links/pl_xyz/line_items", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payment_links_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_links", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_links.create( + { + "line_items": [ + {"price": "price_xxxxxxxxxxxxx", "quantity": 1} + ], + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_links", + query_string="", + api_base="https://api.stripe.com", + post_data="line_items[0][price]=price_xxxxxxxxxxxxx&line_items[0][quantity]=1", + ) + + def test_payment_links_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_links", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_links.create( + { + "line_items": [ + {"price": "price_xxxxxxxxxxxxx", "quantity": 1} + ], + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_links", + query_string="", + api_base="https://api.stripe.com", + post_data="line_items[0][price]=price_xxxxxxxxxxxxx&line_items[0][quantity]=1", + ) + + def test_payment_links_post_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_links/plink_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_links.update( + "plink_xxxxxxxxxxxxx", + {"active": False}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_links/plink_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="active=False", + ) + + def test_payment_method_configurations_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/payment_method_configurations", + "application=foo", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_method_configurations.list({"application": "foo"}) + http_client_mock.assert_requested( + "get", + path="/v1/payment_method_configurations", + query_string="application=foo", + api_base="https://api.stripe.com", + ) + + def test_payment_method_configurations_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/payment_method_configurations/foo", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_method_configurations.retrieve("foo") + http_client_mock.assert_requested( + "get", + path="/v1/payment_method_configurations/foo", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payment_method_configurations_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_method_configurations", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_method_configurations.create( + { + "acss_debit": {"display_preference": {"preference": "none"}}, + "affirm": {"display_preference": {"preference": "none"}}, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_method_configurations", + query_string="", + api_base="https://api.stripe.com", + post_data="acss_debit[display_preference][preference]=none&affirm[display_preference][preference]=none", + ) + + def test_payment_method_configurations_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_method_configurations/foo", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_method_configurations.update( + "foo", + {"acss_debit": {"display_preference": {"preference": "on"}}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_method_configurations/foo", + query_string="", + api_base="https://api.stripe.com", + post_data="acss_debit[display_preference][preference]=on", + ) + + def test_payment_methods_attach_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_methods/pm_xxxxxxxxxxxxx/attach", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_methods.attach( + "pm_xxxxxxxxxxxxx", + {"customer": "cus_xxxxxxxxxxxxx"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_methods/pm_xxxxxxxxxxxxx/attach", + query_string="", + api_base="https://api.stripe.com", + post_data="customer=cus_xxxxxxxxxxxxx", + ) + + def test_payment_methods_detach_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_methods/pm_xxxxxxxxxxxxx/detach", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_methods.detach("pm_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/payment_methods/pm_xxxxxxxxxxxxx/detach", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payment_methods_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/payment_methods", + "customer=cus_xxxxxxxxxxxxx&type=card", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_methods.list( + { + "customer": "cus_xxxxxxxxxxxxx", + "type": "card", + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/payment_methods", + query_string="customer=cus_xxxxxxxxxxxxx&type=card", + api_base="https://api.stripe.com", + ) + + def test_payment_methods_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/payment_methods/pm_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_methods.retrieve("pm_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/payment_methods/pm_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payment_methods_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_methods", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_methods.create( + { + "type": "card", + "card": { + "number": "4242424242424242", + "exp_month": 8, + "exp_year": 2024, + "cvc": "314", + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_methods", + query_string="", + api_base="https://api.stripe.com", + post_data="type=card&card[number]=4242424242424242&card[exp_month]=8&card[exp_year]=2024&card[cvc]=314", + ) + + def test_payment_methods_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payment_methods/pm_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payment_methods.update( + "pm_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/payment_methods/pm_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_payouts_cancel_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payouts/po_xxxxxxxxxxxxx/cancel", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payouts.cancel("po_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/payouts/po_xxxxxxxxxxxxx/cancel", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payouts_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/payouts", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payouts.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/payouts", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_payouts_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/payouts/po_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payouts.retrieve("po_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/payouts/po_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_payouts_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payouts", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payouts.create({"amount": 1100, "currency": "usd"}) + http_client_mock.assert_requested( + "post", + path="/v1/payouts", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=1100¤cy=usd", + ) + + def test_payouts_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payouts/po_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payouts.update( + "po_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/payouts/po_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_payouts_reverse_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/payouts/po_xxxxxxxxxxxxx/reverse", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.payouts.reverse("po_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/payouts/po_xxxxxxxxxxxxx/reverse", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_plans_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/plans/price_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.plans.delete("price_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/plans/price_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_plans_get_service(self, http_client_mock: HTTPClientMock) -> None: + http_client_mock.stub_request( + "get", + "/v1/plans", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.plans.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/plans", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_plans_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/plans/price_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.plans.retrieve("price_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/plans/price_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_plans_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/plans", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.plans.create( + { + "amount": 2000, + "currency": "usd", + "interval": "month", + "product": "prod_xxxxxxxxxxxxx", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/plans", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=2000¤cy=usd&interval=month&product=prod_xxxxxxxxxxxxx", + ) + + def test_plans_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/plans", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.plans.create( + { + "amount": 2000, + "currency": "usd", + "interval": "month", + "product": {"name": "My product"}, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/plans", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=2000¤cy=usd&interval=month&product[name]=My%20product", + ) + + def test_plans_post_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/plans/price_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.plans.update( + "price_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/plans/price_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_prices_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/prices", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.prices.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/prices", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_prices_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/prices/price_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.prices.retrieve("price_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/prices/price_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_prices_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/prices", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.prices.create( + { + "unit_amount": 2000, + "currency": "usd", + "currency_options": { + "uah": {"unit_amount": 5000}, + "eur": {"unit_amount": 1800}, + }, + "recurring": {"interval": "month"}, + "product": "prod_xxxxxxxxxxxxx", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/prices", + query_string="", + api_base="https://api.stripe.com", + post_data="unit_amount=2000¤cy=usd¤cy_options[uah][unit_amount]=5000¤cy_options[eur][unit_amount]=1800&recurring[interval]=month&product=prod_xxxxxxxxxxxxx", + ) + + def test_prices_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/prices", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.prices.create( + { + "unit_amount": 2000, + "currency": "usd", + "recurring": {"interval": "month"}, + "product": "prod_xxxxxxxxxxxxx", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/prices", + query_string="", + api_base="https://api.stripe.com", + post_data="unit_amount=2000¤cy=usd&recurring[interval]=month&product=prod_xxxxxxxxxxxxx", + ) + + def test_prices_post_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/prices/price_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.prices.update( + "price_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/prices/price_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_prices_search_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/prices/search", + "query=active%3A%27true%27%20AND%20metadata%5B%27order_id%27%5D%3A%276735%27", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.prices.search( + { + "query": "active:'true' AND metadata['order_id']:'6735'", + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/prices/search", + query_string="query=active%3A%27true%27%20AND%20metadata%5B%27order_id%27%5D%3A%276735%27", + api_base="https://api.stripe.com", + ) + + def test_products_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/products/prod_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.products.delete("prod_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/products/prod_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_products_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/products", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.products.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/products", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_products_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/products/prod_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.products.retrieve("prod_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/products/prod_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_products_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/products", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.products.create({"name": "Gold Special"}) + http_client_mock.assert_requested( + "post", + path="/v1/products", + query_string="", + api_base="https://api.stripe.com", + post_data="name=Gold%20Special", + ) + + def test_products_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/products/prod_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.products.update( + "prod_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/products/prod_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_products_search_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/products/search", + "query=active%3A%27true%27%20AND%20metadata%5B%27order_id%27%5D%3A%276735%27", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.products.search( + { + "query": "active:'true' AND metadata['order_id']:'6735'", + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/products/search", + query_string="query=active%3A%27true%27%20AND%20metadata%5B%27order_id%27%5D%3A%276735%27", + api_base="https://api.stripe.com", + ) + + def test_promotion_codes_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/promotion_codes", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.promotion_codes.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/promotion_codes", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_promotion_codes_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/promotion_codes/promo_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.promotion_codes.retrieve("promo_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/promotion_codes/promo_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_promotion_codes_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/promotion_codes", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.promotion_codes.create({"coupon": "Z4OV52SU"}) + http_client_mock.assert_requested( + "post", + path="/v1/promotion_codes", + query_string="", + api_base="https://api.stripe.com", + post_data="coupon=Z4OV52SU", + ) + + def test_promotion_codes_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/promotion_codes/promo_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.promotion_codes.update( + "promo_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/promotion_codes/promo_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_quotes_accept_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/quotes/qt_xxxxxxxxxxxxx/accept", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.quotes.accept("qt_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/quotes/qt_xxxxxxxxxxxxx/accept", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_quotes_cancel_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/quotes/qt_xxxxxxxxxxxxx/cancel", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.quotes.cancel("qt_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/quotes/qt_xxxxxxxxxxxxx/cancel", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_quotes_finalize_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/quotes/qt_xxxxxxxxxxxxx/finalize", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.quotes.finalize_quote("qt_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/quotes/qt_xxxxxxxxxxxxx/finalize", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_quotes_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/quotes", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.quotes.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/quotes", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_quotes_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/quotes/qt_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.quotes.retrieve("qt_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/quotes/qt_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_quotes_line_items_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/quotes/qt_xxxxxxxxxxxxx/line_items", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.quotes.line_items.list("qt_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/quotes/qt_xxxxxxxxxxxxx/line_items", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_quotes_pdf_get_service( + self, http_client_mock_streaming: HTTPClientMock + ) -> None: + http_client_mock_streaming.stub_request( + "get", + "/v1/quotes/qt_xxxxxxxxxxxxx/pdf", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock_streaming.get_mock_http_client(), + ) + + client.quotes.pdf("qt_xxxxxxxxxxxxx") + http_client_mock_streaming.assert_requested( + "get", + path="/v1/quotes/qt_xxxxxxxxxxxxx/pdf", + query_string="", + api_base="https://files.stripe.com", + ) + + def test_quotes_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/quotes", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.quotes.create( + { + "customer": "cus_xxxxxxxxxxxxx", + "line_items": [ + {"price": "price_xxxxxxxxxxxxx", "quantity": 2} + ], + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/quotes", + query_string="", + api_base="https://api.stripe.com", + post_data="customer=cus_xxxxxxxxxxxxx&line_items[0][price]=price_xxxxxxxxxxxxx&line_items[0][quantity]=2", + ) + + def test_quotes_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/quotes/qt_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.quotes.update( + "qt_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/quotes/qt_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_radar_early_fraud_warnings_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/radar/early_fraud_warnings", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.radar.early_fraud_warnings.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/radar/early_fraud_warnings", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_radar_early_fraud_warnings_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/radar/early_fraud_warnings/issfr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.radar.early_fraud_warnings.retrieve("issfr_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/radar/early_fraud_warnings/issfr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_radar_value_list_items_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/radar/value_list_items/rsli_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.radar.value_list_items.delete("rsli_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/radar/value_list_items/rsli_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_radar_value_list_items_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/radar/value_list_items", + "limit=3&value_list=rsl_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.radar.value_list_items.list( + { + "limit": 3, + "value_list": "rsl_xxxxxxxxxxxxx", + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/radar/value_list_items", + query_string="limit=3&value_list=rsl_xxxxxxxxxxxxx", + api_base="https://api.stripe.com", + ) + + def test_radar_value_list_items_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/radar/value_list_items/rsli_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.radar.value_list_items.retrieve("rsli_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/radar/value_list_items/rsli_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_radar_value_list_items_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/radar/value_list_items", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.radar.value_list_items.create( + { + "value_list": "rsl_xxxxxxxxxxxxx", + "value": "1.2.3.4", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/radar/value_list_items", + query_string="", + api_base="https://api.stripe.com", + post_data="value_list=rsl_xxxxxxxxxxxxx&value=1.2.3.4", + ) + + def test_radar_value_lists_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/radar/value_lists/rsl_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.radar.value_lists.delete("rsl_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/radar/value_lists/rsl_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_radar_value_lists_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/radar/value_lists", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.radar.value_lists.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/radar/value_lists", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_radar_value_lists_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/radar/value_lists/rsl_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.radar.value_lists.retrieve("rsl_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/radar/value_lists/rsl_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_radar_value_lists_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/radar/value_lists", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.radar.value_lists.create( + { + "alias": "custom_ip_xxxxxxxxxxxxx", + "name": "Custom IP Blocklist", + "item_type": "ip_address", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/radar/value_lists", + query_string="", + api_base="https://api.stripe.com", + post_data="alias=custom_ip_xxxxxxxxxxxxx&name=Custom%20IP%20Blocklist&item_type=ip_address", + ) + + def test_radar_value_lists_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/radar/value_lists/rsl_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.radar.value_lists.update( + "rsl_xxxxxxxxxxxxx", + {"name": "Updated IP Block List"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/radar/value_lists/rsl_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="name=Updated%20IP%20Block%20List", + ) + + def test_refunds_cancel_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/refunds/re_xxxxxxxxxxxxx/cancel", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.refunds.cancel("re_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/refunds/re_xxxxxxxxxxxxx/cancel", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_refunds_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/refunds", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.refunds.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/refunds", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_refunds_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/refunds/re_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.refunds.retrieve("re_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/refunds/re_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_refunds_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/refunds", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.refunds.create({"charge": "ch_xxxxxxxxxxxxx"}) + http_client_mock.assert_requested( + "post", + path="/v1/refunds", + query_string="", + api_base="https://api.stripe.com", + post_data="charge=ch_xxxxxxxxxxxxx", + ) + + def test_refunds_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/refunds/re_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.refunds.update( + "re_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/refunds/re_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_reporting_report_runs_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/reporting/report_runs", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.reporting.report_runs.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/reporting/report_runs", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_reporting_report_runs_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/reporting/report_runs/frr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.reporting.report_runs.retrieve("frr_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/reporting/report_runs/frr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_reporting_report_runs_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/reporting/report_runs", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.reporting.report_runs.create( + { + "report_type": "balance.summary.1", + "parameters": { + "interval_start": 1522540800, + "interval_end": 1525132800, + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/reporting/report_runs", + query_string="", + api_base="https://api.stripe.com", + post_data="report_type=balance.summary.1¶meters[interval_start]=1522540800¶meters[interval_end]=1525132800", + ) + + def test_reporting_report_types_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/reporting/report_types", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.reporting.report_types.list() + http_client_mock.assert_requested( + "get", + path="/v1/reporting/report_types", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_reporting_report_types_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/reporting/report_types/balance.summary.1", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.reporting.report_types.retrieve("balance.summary.1") + http_client_mock.assert_requested( + "get", + path="/v1/reporting/report_types/balance.summary.1", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_reviews_approve_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/reviews/prv_xxxxxxxxxxxxx/approve", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.reviews.approve("prv_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/reviews/prv_xxxxxxxxxxxxx/approve", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_reviews_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/reviews", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.reviews.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/reviews", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_reviews_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/reviews/prv_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.reviews.retrieve("prv_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/reviews/prv_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_setup_attempts_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/setup_attempts", + "limit=3&setup_intent=si_xyz", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.setup_attempts.list({"limit": 3, "setup_intent": "si_xyz"}) + http_client_mock.assert_requested( + "get", + path="/v1/setup_attempts", + query_string="limit=3&setup_intent=si_xyz", + api_base="https://api.stripe.com", + ) + + def test_setup_intents_cancel_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/setup_intents/seti_xxxxxxxxxxxxx/cancel", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.setup_intents.cancel("seti_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/setup_intents/seti_xxxxxxxxxxxxx/cancel", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_setup_intents_confirm_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/setup_intents/seti_xxxxxxxxxxxxx/confirm", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.setup_intents.confirm( + "seti_xxxxxxxxxxxxx", + {"payment_method": "pm_card_visa"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/setup_intents/seti_xxxxxxxxxxxxx/confirm", + query_string="", + api_base="https://api.stripe.com", + post_data="payment_method=pm_card_visa", + ) + + def test_setup_intents_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/setup_intents", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.setup_intents.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/setup_intents", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_setup_intents_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/setup_intents/seti_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.setup_intents.retrieve("seti_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/setup_intents/seti_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_setup_intents_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/setup_intents", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.setup_intents.create({"payment_method_types": ["card"]}) + http_client_mock.assert_requested( + "post", + path="/v1/setup_intents", + query_string="", + api_base="https://api.stripe.com", + post_data="payment_method_types[0]=card", + ) + + def test_setup_intents_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/setup_intents/seti_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.setup_intents.update( + "seti_xxxxxxxxxxxxx", + {"metadata": {"user_id": "3435453"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/setup_intents/seti_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[user_id]=3435453", + ) + + def test_setup_intents_verify_microdeposits_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/setup_intents/seti_xxxxxxxxxxxxx/verify_microdeposits", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.setup_intents.verify_microdeposits("seti_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/setup_intents/seti_xxxxxxxxxxxxx/verify_microdeposits", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_setup_intents_verify_microdeposits_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/setup_intents/seti_xxxxxxxxxxxxx/verify_microdeposits", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.setup_intents.verify_microdeposits( + "seti_xxxxxxxxxxxxx", + {"amounts": [32, 45]}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/setup_intents/seti_xxxxxxxxxxxxx/verify_microdeposits", + query_string="", + api_base="https://api.stripe.com", + post_data="amounts[0]=32&amounts[1]=45", + ) + + def test_shipping_rates_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/shipping_rates", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.shipping_rates.list() + http_client_mock.assert_requested( + "get", + path="/v1/shipping_rates", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_shipping_rates_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/shipping_rates", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.shipping_rates.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/shipping_rates", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_shipping_rates_get_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/shipping_rates/shr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.shipping_rates.retrieve("shr_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/shipping_rates/shr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_shipping_rates_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/shipping_rates", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.shipping_rates.create( + { + "display_name": "Sample Shipper", + "fixed_amount": {"currency": "usd", "amount": 400}, + "type": "fixed_amount", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/shipping_rates", + query_string="", + api_base="https://api.stripe.com", + post_data="display_name=Sample%20Shipper&fixed_amount[currency]=usd&fixed_amount[amount]=400&type=fixed_amount", + ) + + def test_shipping_rates_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/shipping_rates", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.shipping_rates.create( + { + "display_name": "Ground shipping", + "type": "fixed_amount", + "fixed_amount": {"amount": 500, "currency": "usd"}, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/shipping_rates", + query_string="", + api_base="https://api.stripe.com", + post_data="display_name=Ground%20shipping&type=fixed_amount&fixed_amount[amount]=500&fixed_amount[currency]=usd", + ) + + def test_shipping_rates_post_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/shipping_rates/shr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.shipping_rates.update( + "shr_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/shipping_rates/shr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_sigma_scheduled_query_runs_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/sigma/scheduled_query_runs", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.sigma.scheduled_query_runs.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/sigma/scheduled_query_runs", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_sigma_scheduled_query_runs_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/sigma/scheduled_query_runs/sqr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.sigma.scheduled_query_runs.retrieve("sqr_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/sigma/scheduled_query_runs/sqr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_sources_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/sources/src_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.sources.retrieve("src_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/sources/src_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_sources_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/sources/src_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.sources.retrieve("src_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/sources/src_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_sources_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/sources/src_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.sources.update( + "src_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/sources/src_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_subscription_items_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/subscription_items/si_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscription_items.delete("si_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/subscription_items/si_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_subscription_items_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/subscription_items", + "subscription=sub_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscription_items.list({"subscription": "sub_xxxxxxxxxxxxx"}) + http_client_mock.assert_requested( + "get", + path="/v1/subscription_items", + query_string="subscription=sub_xxxxxxxxxxxxx", + api_base="https://api.stripe.com", + ) + + def test_subscription_items_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/subscription_items/si_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscription_items.retrieve("si_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/subscription_items/si_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_subscription_items_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/subscription_items", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscription_items.create( + { + "subscription": "sub_xxxxxxxxxxxxx", + "price": "price_xxxxxxxxxxxxx", + "quantity": 2, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/subscription_items", + query_string="", + api_base="https://api.stripe.com", + post_data="subscription=sub_xxxxxxxxxxxxx&price=price_xxxxxxxxxxxxx&quantity=2", + ) + + def test_subscription_items_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/subscription_items/si_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscription_items.update( + "si_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/subscription_items/si_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_subscription_items_usage_record_summaries_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/subscription_items/si_xxxxxxxxxxxxx/usage_record_summaries", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscription_items.usage_record_summaries.list( + "si_xxxxxxxxxxxxx", + {"limit": 3}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/subscription_items/si_xxxxxxxxxxxxx/usage_record_summaries", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_subscription_items_usage_records_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/subscription_items/si_xxxxxxxxxxxxx/usage_records", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscription_items.usage_records.create( + "si_xxxxxxxxxxxxx", + {"quantity": 100, "timestamp": 1571252444}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/subscription_items/si_xxxxxxxxxxxxx/usage_records", + query_string="", + api_base="https://api.stripe.com", + post_data="quantity=100×tamp=1571252444", + ) + + def test_subscription_schedules_cancel_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/subscription_schedules/sub_sched_xxxxxxxxxxxxx/cancel", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscription_schedules.cancel("sub_sched_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/subscription_schedules/sub_sched_xxxxxxxxxxxxx/cancel", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_subscription_schedules_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/subscription_schedules", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscription_schedules.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/subscription_schedules", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_subscription_schedules_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/subscription_schedules/sub_sched_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscription_schedules.retrieve("sub_sched_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/subscription_schedules/sub_sched_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_subscription_schedules_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/subscription_schedules", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscription_schedules.create( + { + "customer": "cus_xxxxxxxxxxxxx", + "start_date": 1676070661, + "end_behavior": "release", + "phases": [ + { + "items": [ + {"price": "price_xxxxxxxxxxxxx", "quantity": 1} + ], + "iterations": 12, + }, + ], + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/subscription_schedules", + query_string="", + api_base="https://api.stripe.com", + post_data="customer=cus_xxxxxxxxxxxxx&start_date=1676070661&end_behavior=release&phases[0][items][0][price]=price_xxxxxxxxxxxxx&phases[0][items][0][quantity]=1&phases[0][iterations]=12", + ) + + def test_subscription_schedules_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/subscription_schedules/sub_sched_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscription_schedules.update( + "sub_sched_xxxxxxxxxxxxx", + {"end_behavior": "release"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/subscription_schedules/sub_sched_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="end_behavior=release", + ) + + def test_subscription_schedules_release_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/subscription_schedules/sub_sched_xxxxxxxxxxxxx/release", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscription_schedules.release("sub_sched_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/subscription_schedules/sub_sched_xxxxxxxxxxxxx/release", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_subscriptions_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/subscriptions/sub_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscriptions.cancel("sub_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/subscriptions/sub_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_subscriptions_discount_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/subscriptions/sub_xyz/discount", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscriptions.delete_discount("sub_xyz") + http_client_mock.assert_requested( + "delete", + path="/v1/subscriptions/sub_xyz/discount", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_subscriptions_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/subscriptions", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscriptions.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/subscriptions", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_subscriptions_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/subscriptions/sub_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscriptions.retrieve("sub_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/subscriptions/sub_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_subscriptions_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/subscriptions", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscriptions.create( + { + "customer": "cus_xxxxxxxxxxxxx", + "items": [{"price": "price_xxxxxxxxxxxxx"}], + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/subscriptions", + query_string="", + api_base="https://api.stripe.com", + post_data="customer=cus_xxxxxxxxxxxxx&items[0][price]=price_xxxxxxxxxxxxx", + ) + + def test_subscriptions_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/subscriptions/sub_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscriptions.update( + "sub_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/subscriptions/sub_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_subscriptions_search_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/subscriptions/search", + "query=status%3A%27active%27%20AND%20metadata%5B%27order_id%27%5D%3A%276735%27", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.subscriptions.search( + { + "query": "status:'active' AND metadata['order_id']:'6735'", + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/subscriptions/search", + query_string="query=status%3A%27active%27%20AND%20metadata%5B%27order_id%27%5D%3A%276735%27", + api_base="https://api.stripe.com", + ) + + def test_tax_calculations_line_items_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/tax/calculations/xxx/line_items", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax.calculations.line_items.list("xxx") + http_client_mock.assert_requested( + "get", + path="/v1/tax/calculations/xxx/line_items", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_tax_calculations_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/tax/calculations", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax.calculations.create( + { + "currency": "usd", + "line_items": [{"amount": 1000, "reference": "L1"}], + "customer_details": { + "address": { + "line1": "354 Oyster Point Blvd", + "city": "South San Francisco", + "state": "CA", + "postal_code": "94080", + "country": "US", + }, + "address_source": "shipping", + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/tax/calculations", + query_string="", + api_base="https://api.stripe.com", + post_data="currency=usd&line_items[0][amount]=1000&line_items[0][reference]=L1&customer_details[address][line1]=354%20Oyster%20Point%20Blvd&customer_details[address][city]=South%20San%20Francisco&customer_details[address][state]=CA&customer_details[address][postal_code]=94080&customer_details[address][country]=US&customer_details[address_source]=shipping", + ) + + def test_tax_codes_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/tax_codes", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax_codes.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/tax_codes", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_tax_codes_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/tax_codes/txcd_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax_codes.retrieve("txcd_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/tax_codes/txcd_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_tax_rates_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/tax_rates", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax_rates.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/tax_rates", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_tax_rates_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/tax_rates/txr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax_rates.retrieve("txr_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/tax_rates/txr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_tax_rates_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/tax_rates", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax_rates.create( + { + "display_name": "VAT", + "description": "VAT Germany", + "jurisdiction": "DE", + "percentage": 16, + "inclusive": False, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/tax_rates", + query_string="", + api_base="https://api.stripe.com", + post_data="display_name=VAT&description=VAT%20Germany&jurisdiction=DE&percentage=16&inclusive=False", + ) + + def test_tax_rates_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/tax_rates/txr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax_rates.update( + "txr_xxxxxxxxxxxxx", + {"active": False}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/tax_rates/txr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="active=False", + ) + + def test_tax_registrations_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/tax/registrations", + "status=all", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax.registrations.list({"status": "all"}) + http_client_mock.assert_requested( + "get", + path="/v1/tax/registrations", + query_string="status=all", + api_base="https://api.stripe.com", + ) + + def test_tax_registrations_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/tax/registrations", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax.registrations.create( + { + "country": "IE", + "country_options": {"ie": {"type": "oss_union"}}, + "active_from": "now", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/tax/registrations", + query_string="", + api_base="https://api.stripe.com", + post_data="country=IE&country_options[ie][type]=oss_union&active_from=now", + ) + + def test_tax_registrations_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/tax/registrations/taxreg_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax.registrations.update( + "taxreg_xxxxxxxxxxxxx", + {"expires_at": "now"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/tax/registrations/taxreg_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="expires_at=now", + ) + + def test_tax_settings_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/tax/settings", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax.settings.retrieve() + http_client_mock.assert_requested( + "get", + path="/v1/tax/settings", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_tax_settings_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/tax/settings", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax.settings.update({"defaults": {"tax_code": "txcd_10000000"}}) + http_client_mock.assert_requested( + "post", + path="/v1/tax/settings", + query_string="", + api_base="https://api.stripe.com", + post_data="defaults[tax_code]=txcd_10000000", + ) + + def test_tax_transactions_create_from_calculation_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/tax/transactions/create_from_calculation", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tax.transactions.create_from_calculation( + { + "calculation": "xxx", + "reference": "yyy", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/tax/transactions/create_from_calculation", + query_string="", + api_base="https://api.stripe.com", + post_data="calculation=xxx&reference=yyy", + ) + + def test_terminal_configurations_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/terminal/configurations/uc_123", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.configurations.delete("uc_123") + http_client_mock.assert_requested( + "delete", + path="/v1/terminal/configurations/uc_123", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_terminal_configurations_delete_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/terminal/configurations/tmc_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.configurations.delete("tmc_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/terminal/configurations/tmc_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_terminal_configurations_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/terminal/configurations", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.configurations.list() + http_client_mock.assert_requested( + "get", + path="/v1/terminal/configurations", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_terminal_configurations_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/terminal/configurations/uc_123", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.configurations.retrieve("uc_123") + http_client_mock.assert_requested( + "get", + path="/v1/terminal/configurations/uc_123", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_terminal_configurations_get_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/terminal/configurations", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.configurations.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/terminal/configurations", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_terminal_configurations_get_4_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/terminal/configurations/tmc_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.configurations.retrieve("tmc_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/terminal/configurations/tmc_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_terminal_configurations_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/terminal/configurations", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.configurations.create() + http_client_mock.assert_requested( + "post", + path="/v1/terminal/configurations", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_terminal_configurations_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/terminal/configurations/uc_123", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.configurations.update( + "uc_123", + {"tipping": {"usd": {"fixed_amounts": [10]}}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/terminal/configurations/uc_123", + query_string="", + api_base="https://api.stripe.com", + post_data="tipping[usd][fixed_amounts][0]=10", + ) + + def test_terminal_configurations_post_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/terminal/configurations", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.configurations.create( + { + "bbpos_wisepos_e": {"splashscreen": "file_xxxxxxxxxxxxx"}, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/terminal/configurations", + query_string="", + api_base="https://api.stripe.com", + post_data="bbpos_wisepos_e[splashscreen]=file_xxxxxxxxxxxxx", + ) + + def test_terminal_configurations_post_4_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/terminal/configurations/tmc_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.configurations.update( + "tmc_xxxxxxxxxxxxx", + {"bbpos_wisepos_e": {"splashscreen": "file_xxxxxxxxxxxxx"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/terminal/configurations/tmc_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="bbpos_wisepos_e[splashscreen]=file_xxxxxxxxxxxxx", + ) + + def test_terminal_connection_tokens_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/terminal/connection_tokens", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.connection_tokens.create() + http_client_mock.assert_requested( + "post", + path="/v1/terminal/connection_tokens", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_terminal_locations_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/terminal/locations/tml_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.locations.delete("tml_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/terminal/locations/tml_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_terminal_locations_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/terminal/locations", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.locations.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/terminal/locations", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_terminal_locations_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/terminal/locations/tml_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.locations.retrieve("tml_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/terminal/locations/tml_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_terminal_locations_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/terminal/locations", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.locations.create( + { + "display_name": "My First Store", + "address": { + "line1": "1234 Main Street", + "city": "San Francisco", + "postal_code": "94111", + "state": "CA", + "country": "US", + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/terminal/locations", + query_string="", + api_base="https://api.stripe.com", + post_data="display_name=My%20First%20Store&address[line1]=1234%20Main%20Street&address[city]=San%20Francisco&address[postal_code]=94111&address[state]=CA&address[country]=US", + ) + + def test_terminal_locations_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/terminal/locations/tml_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.locations.update( + "tml_xxxxxxxxxxxxx", + {"display_name": "My First Store"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/terminal/locations/tml_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="display_name=My%20First%20Store", + ) + + def test_terminal_readers_cancel_action_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/terminal/readers/tmr_xxxxxxxxxxxxx/cancel_action", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.readers.cancel_action("tmr_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/terminal/readers/tmr_xxxxxxxxxxxxx/cancel_action", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_terminal_readers_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/terminal/readers/tmr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.readers.delete("tmr_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/terminal/readers/tmr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_terminal_readers_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/terminal/readers", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.readers.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/terminal/readers", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_terminal_readers_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/terminal/readers/tmr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.readers.retrieve("tmr_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/terminal/readers/tmr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_terminal_readers_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/terminal/readers", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.readers.create( + { + "registration_code": "puppies-plug-could", + "label": "Blue Rabbit", + "location": "tml_1234", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/terminal/readers", + query_string="", + api_base="https://api.stripe.com", + post_data="registration_code=puppies-plug-could&label=Blue%20Rabbit&location=tml_1234", + ) + + def test_terminal_readers_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/terminal/readers/tmr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.readers.update( + "tmr_xxxxxxxxxxxxx", + {"label": "Blue Rabbit"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/terminal/readers/tmr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="label=Blue%20Rabbit", + ) + + def test_terminal_readers_process_payment_intent_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/terminal/readers/tmr_xxxxxxxxxxxxx/process_payment_intent", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.readers.process_payment_intent( + "tmr_xxxxxxxxxxxxx", + {"payment_intent": "pi_xxxxxxxxxxxxx"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/terminal/readers/tmr_xxxxxxxxxxxxx/process_payment_intent", + query_string="", + api_base="https://api.stripe.com", + post_data="payment_intent=pi_xxxxxxxxxxxxx", + ) + + def test_terminal_readers_process_setup_intent_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/terminal/readers/tmr_xxxxxxxxxxxxx/process_setup_intent", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.terminal.readers.process_setup_intent( + "tmr_xxxxxxxxxxxxx", + { + "setup_intent": "seti_xxxxxxxxxxxxx", + "customer_consent_collected": True, + }, + ) + http_client_mock.assert_requested( + "post", + path="/v1/terminal/readers/tmr_xxxxxxxxxxxxx/process_setup_intent", + query_string="", + api_base="https://api.stripe.com", + post_data="setup_intent=seti_xxxxxxxxxxxxx&customer_consent_collected=True", + ) + + def test_test_helpers_customers_fund_cash_balance_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/customers/cus_123/fund_cash_balance", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.customers.fund_cash_balance( + "cus_123", + {"amount": 30, "currency": "eur"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/customers/cus_123/fund_cash_balance", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=30¤cy=eur", + ) + + def test_test_helpers_issuing_authorizations_capture_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/issuing/authorizations/example_authorization/capture", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.issuing.authorizations.capture( + "example_authorization", + { + "capture_amount": 100, + "close_authorization": True, + "purchase_details": { + "flight": { + "departure_at": 1633651200, + "passenger_name": "John Doe", + "refundable": True, + "segments": [ + { + "arrival_airport_code": "SFO", + "carrier": "Delta", + "departure_airport_code": "LAX", + "flight_number": "DL100", + "service_class": "Economy", + "stopover_allowed": True, + }, + ], + "travel_agency": "Orbitz", + }, + "fuel": { + "type": "diesel", + "unit": "liter", + "unit_cost_decimal": "3.5", + "volume_decimal": "10", + }, + "lodging": {"check_in_at": 1633651200, "nights": 2}, + "receipt": [ + { + "description": "Room charge", + "quantity": "1", + "total": 200, + "unit_cost": 200, + }, + ], + "reference": "foo", + }, + }, + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/issuing/authorizations/example_authorization/capture", + query_string="", + api_base="https://api.stripe.com", + post_data="capture_amount=100&close_authorization=True&purchase_details[flight][departure_at]=1633651200&purchase_details[flight][passenger_name]=John%20Doe&purchase_details[flight][refundable]=True&purchase_details[flight][segments][0][arrival_airport_code]=SFO&purchase_details[flight][segments][0][carrier]=Delta&purchase_details[flight][segments][0][departure_airport_code]=LAX&purchase_details[flight][segments][0][flight_number]=DL100&purchase_details[flight][segments][0][service_class]=Economy&purchase_details[flight][segments][0][stopover_allowed]=True&purchase_details[flight][travel_agency]=Orbitz&purchase_details[fuel][type]=diesel&purchase_details[fuel][unit]=liter&purchase_details[fuel][unit_cost_decimal]=3.5&purchase_details[fuel][volume_decimal]=10&purchase_details[lodging][check_in_at]=1633651200&purchase_details[lodging][nights]=2&purchase_details[receipt][0][description]=Room%20charge&purchase_details[receipt][0][quantity]=1&purchase_details[receipt][0][total]=200&purchase_details[receipt][0][unit_cost]=200&purchase_details[reference]=foo", + ) + + def test_test_helpers_issuing_authorizations_expire_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/issuing/authorizations/example_authorization/expire", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.issuing.authorizations.expire( + "example_authorization", + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/issuing/authorizations/example_authorization/expire", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_issuing_authorizations_increment_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/issuing/authorizations/example_authorization/increment", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.issuing.authorizations.increment( + "example_authorization", + {"increment_amount": 50, "is_amount_controllable": True}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/issuing/authorizations/example_authorization/increment", + query_string="", + api_base="https://api.stripe.com", + post_data="increment_amount=50&is_amount_controllable=True", + ) + + def test_test_helpers_issuing_authorizations_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/issuing/authorizations", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.issuing.authorizations.create( + { + "amount": 100, + "amount_details": {"atm_fee": 10, "cashback_amount": 5}, + "authorization_method": "chip", + "card": "foo", + "currency": "usd", + "is_amount_controllable": True, + "merchant_data": { + "category": "ac_refrigeration_repair", + "city": "foo", + "country": "bar", + "name": "foo", + "network_id": "bar", + "postal_code": "foo", + "state": "bar", + "terminal_id": "foo", + }, + "network_data": {"acquiring_institution_id": "foo"}, + "verification_data": { + "address_line1_check": "mismatch", + "address_postal_code_check": "match", + "cvc_check": "match", + "expiry_check": "mismatch", + }, + "wallet": "apple_pay", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/issuing/authorizations", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=100&amount_details[atm_fee]=10&amount_details[cashback_amount]=5&authorization_method=chip&card=foo¤cy=usd&is_amount_controllable=True&merchant_data[category]=ac_refrigeration_repair&merchant_data[city]=foo&merchant_data[country]=bar&merchant_data[name]=foo&merchant_data[network_id]=bar&merchant_data[postal_code]=foo&merchant_data[state]=bar&merchant_data[terminal_id]=foo&network_data[acquiring_institution_id]=foo&verification_data[address_line1_check]=mismatch&verification_data[address_postal_code_check]=match&verification_data[cvc_check]=match&verification_data[expiry_check]=mismatch&wallet=apple_pay", + ) + + def test_test_helpers_issuing_authorizations_reverse_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/issuing/authorizations/example_authorization/reverse", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.issuing.authorizations.reverse( + "example_authorization", + {"reverse_amount": 20}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/issuing/authorizations/example_authorization/reverse", + query_string="", + api_base="https://api.stripe.com", + post_data="reverse_amount=20", + ) + + def test_test_helpers_issuing_cards_shipping_deliver_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/issuing/cards/card_123/shipping/deliver", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.issuing.cards.deliver_card("card_123") + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/issuing/cards/card_123/shipping/deliver", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_issuing_cards_shipping_fail_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/issuing/cards/card_123/shipping/fail", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.issuing.cards.fail_card("card_123") + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/issuing/cards/card_123/shipping/fail", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_issuing_cards_shipping_return_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/issuing/cards/card_123/shipping/return", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.issuing.cards.return_card("card_123") + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/issuing/cards/card_123/shipping/return", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_issuing_cards_shipping_ship_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/issuing/cards/card_123/shipping/ship", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.issuing.cards.ship_card("card_123") + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/issuing/cards/card_123/shipping/ship", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_issuing_transactions_create_force_capture_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/issuing/transactions/create_force_capture", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.issuing.transactions.create_force_capture( + { + "amount": 100, + "card": "foo", + "currency": "usd", + "merchant_data": { + "category": "ac_refrigeration_repair", + "city": "foo", + "country": "US", + "name": "foo", + "network_id": "bar", + "postal_code": "10001", + "state": "NY", + "terminal_id": "foo", + }, + "purchase_details": { + "flight": { + "departure_at": 1633651200, + "passenger_name": "John Doe", + "refundable": True, + "segments": [ + { + "arrival_airport_code": "SFO", + "carrier": "Delta", + "departure_airport_code": "LAX", + "flight_number": "DL100", + "service_class": "Economy", + "stopover_allowed": True, + }, + ], + "travel_agency": "Orbitz", + }, + "fuel": { + "type": "diesel", + "unit": "liter", + "unit_cost_decimal": "3.5", + "volume_decimal": "10", + }, + "lodging": {"check_in_at": 1533651200, "nights": 2}, + "receipt": [ + { + "description": "Room charge", + "quantity": "1", + "total": 200, + "unit_cost": 200, + }, + ], + "reference": "foo", + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/issuing/transactions/create_force_capture", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=100&card=foo¤cy=usd&merchant_data[category]=ac_refrigeration_repair&merchant_data[city]=foo&merchant_data[country]=US&merchant_data[name]=foo&merchant_data[network_id]=bar&merchant_data[postal_code]=10001&merchant_data[state]=NY&merchant_data[terminal_id]=foo&purchase_details[flight][departure_at]=1633651200&purchase_details[flight][passenger_name]=John%20Doe&purchase_details[flight][refundable]=True&purchase_details[flight][segments][0][arrival_airport_code]=SFO&purchase_details[flight][segments][0][carrier]=Delta&purchase_details[flight][segments][0][departure_airport_code]=LAX&purchase_details[flight][segments][0][flight_number]=DL100&purchase_details[flight][segments][0][service_class]=Economy&purchase_details[flight][segments][0][stopover_allowed]=True&purchase_details[flight][travel_agency]=Orbitz&purchase_details[fuel][type]=diesel&purchase_details[fuel][unit]=liter&purchase_details[fuel][unit_cost_decimal]=3.5&purchase_details[fuel][volume_decimal]=10&purchase_details[lodging][check_in_at]=1533651200&purchase_details[lodging][nights]=2&purchase_details[receipt][0][description]=Room%20charge&purchase_details[receipt][0][quantity]=1&purchase_details[receipt][0][total]=200&purchase_details[receipt][0][unit_cost]=200&purchase_details[reference]=foo", + ) + + def test_test_helpers_issuing_transactions_create_unlinked_refund_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/issuing/transactions/create_unlinked_refund", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.issuing.transactions.create_unlinked_refund( + { + "amount": 100, + "card": "foo", + "currency": "usd", + "merchant_data": { + "category": "ac_refrigeration_repair", + "city": "foo", + "country": "bar", + "name": "foo", + "network_id": "bar", + "postal_code": "foo", + "state": "bar", + "terminal_id": "foo", + }, + "purchase_details": { + "flight": { + "departure_at": 1533651200, + "passenger_name": "John Doe", + "refundable": True, + "segments": [ + { + "arrival_airport_code": "SFO", + "carrier": "Delta", + "departure_airport_code": "LAX", + "flight_number": "DL100", + "service_class": "Economy", + "stopover_allowed": True, + }, + ], + "travel_agency": "Orbitz", + }, + "fuel": { + "type": "diesel", + "unit": "liter", + "unit_cost_decimal": "3.5", + "volume_decimal": "10", + }, + "lodging": {"check_in_at": 1533651200, "nights": 2}, + "receipt": [ + { + "description": "Room charge", + "quantity": "1", + "total": 200, + "unit_cost": 200, + }, + ], + "reference": "foo", + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/issuing/transactions/create_unlinked_refund", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=100&card=foo¤cy=usd&merchant_data[category]=ac_refrigeration_repair&merchant_data[city]=foo&merchant_data[country]=bar&merchant_data[name]=foo&merchant_data[network_id]=bar&merchant_data[postal_code]=foo&merchant_data[state]=bar&merchant_data[terminal_id]=foo&purchase_details[flight][departure_at]=1533651200&purchase_details[flight][passenger_name]=John%20Doe&purchase_details[flight][refundable]=True&purchase_details[flight][segments][0][arrival_airport_code]=SFO&purchase_details[flight][segments][0][carrier]=Delta&purchase_details[flight][segments][0][departure_airport_code]=LAX&purchase_details[flight][segments][0][flight_number]=DL100&purchase_details[flight][segments][0][service_class]=Economy&purchase_details[flight][segments][0][stopover_allowed]=True&purchase_details[flight][travel_agency]=Orbitz&purchase_details[fuel][type]=diesel&purchase_details[fuel][unit]=liter&purchase_details[fuel][unit_cost_decimal]=3.5&purchase_details[fuel][volume_decimal]=10&purchase_details[lodging][check_in_at]=1533651200&purchase_details[lodging][nights]=2&purchase_details[receipt][0][description]=Room%20charge&purchase_details[receipt][0][quantity]=1&purchase_details[receipt][0][total]=200&purchase_details[receipt][0][unit_cost]=200&purchase_details[reference]=foo", + ) + + def test_test_helpers_issuing_transactions_refund_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/issuing/transactions/example_transaction/refund", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.issuing.transactions.refund( + "example_transaction", + {"refund_amount": 50}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/issuing/transactions/example_transaction/refund", + query_string="", + api_base="https://api.stripe.com", + post_data="refund_amount=50", + ) + + def test_test_helpers_refunds_expire_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/refunds/re_123/expire", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.refunds.expire("re_123") + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/refunds/re_123/expire", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_test_clocks_advance_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/test_clocks/clock_xyz/advance", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.test_clocks.advance( + "clock_xyz", + {"frozen_time": 142}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/test_clocks/clock_xyz/advance", + query_string="", + api_base="https://api.stripe.com", + post_data="frozen_time=142", + ) + + def test_test_helpers_test_clocks_advance_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/test_clocks/clock_xxxxxxxxxxxxx/advance", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.test_clocks.advance( + "clock_xxxxxxxxxxxxx", + {"frozen_time": 1675552261}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/test_clocks/clock_xxxxxxxxxxxxx/advance", + query_string="", + api_base="https://api.stripe.com", + post_data="frozen_time=1675552261", + ) + + def test_test_helpers_test_clocks_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/test_helpers/test_clocks/clock_xyz", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.test_clocks.delete("clock_xyz") + http_client_mock.assert_requested( + "delete", + path="/v1/test_helpers/test_clocks/clock_xyz", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_test_clocks_delete_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/test_helpers/test_clocks/clock_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.test_clocks.delete("clock_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/test_helpers/test_clocks/clock_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_test_clocks_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/test_helpers/test_clocks", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.test_clocks.list() + http_client_mock.assert_requested( + "get", + path="/v1/test_helpers/test_clocks", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_test_clocks_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/test_helpers/test_clocks/clock_xyz", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.test_clocks.retrieve("clock_xyz") + http_client_mock.assert_requested( + "get", + path="/v1/test_helpers/test_clocks/clock_xyz", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_test_clocks_get_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/test_helpers/test_clocks", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.test_clocks.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/test_helpers/test_clocks", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_test_clocks_get_4_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/test_helpers/test_clocks/clock_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.test_clocks.retrieve("clock_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/test_helpers/test_clocks/clock_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_test_clocks_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/test_clocks", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.test_clocks.create( + { + "frozen_time": 123, + "name": "cogsworth", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/test_clocks", + query_string="", + api_base="https://api.stripe.com", + post_data="frozen_time=123&name=cogsworth", + ) + + def test_test_helpers_test_clocks_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/test_clocks", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.test_clocks.create({"frozen_time": 1577836800}) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/test_clocks", + query_string="", + api_base="https://api.stripe.com", + post_data="frozen_time=1577836800", + ) + + def test_test_helpers_treasury_inbound_transfers_fail_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/treasury/inbound_transfers/ibt_123/fail", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.treasury.inbound_transfers.fail( + "ibt_123", + {"failure_details": {"code": "account_closed"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/treasury/inbound_transfers/ibt_123/fail", + query_string="", + api_base="https://api.stripe.com", + post_data="failure_details[code]=account_closed", + ) + + def test_test_helpers_treasury_inbound_transfers_return_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/treasury/inbound_transfers/ibt_123/return", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.treasury.inbound_transfers.return_inbound_transfer( + "ibt_123", + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/treasury/inbound_transfers/ibt_123/return", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_treasury_inbound_transfers_succeed_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/treasury/inbound_transfers/ibt_123/succeed", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.treasury.inbound_transfers.succeed("ibt_123") + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/treasury/inbound_transfers/ibt_123/succeed", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_treasury_outbound_transfers_fail_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/treasury/outbound_transfers/obt_123/fail", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.treasury.outbound_transfers.fail("obt_123") + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/treasury/outbound_transfers/obt_123/fail", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_treasury_outbound_transfers_post_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/treasury/outbound_transfers/obt_123/post", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.treasury.outbound_transfers.post("obt_123") + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/treasury/outbound_transfers/obt_123/post", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_test_helpers_treasury_outbound_transfers_return_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/treasury/outbound_transfers/obt_123/return", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.treasury.outbound_transfers.return_outbound_transfer( + "obt_123", + {"returned_details": {"code": "account_closed"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/treasury/outbound_transfers/obt_123/return", + query_string="", + api_base="https://api.stripe.com", + post_data="returned_details[code]=account_closed", + ) + + def test_test_helpers_treasury_received_credits_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/treasury/received_credits", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.treasury.received_credits.create( + { + "financial_account": "fa_123", + "network": "ach", + "amount": 1234, + "currency": "usd", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/treasury/received_credits", + query_string="", + api_base="https://api.stripe.com", + post_data="financial_account=fa_123&network=ach&amount=1234¤cy=usd", + ) + + def test_test_helpers_treasury_received_debits_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/test_helpers/treasury/received_debits", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.test_helpers.treasury.received_debits.create( + { + "financial_account": "fa_123", + "network": "ach", + "amount": 1234, + "currency": "usd", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/test_helpers/treasury/received_debits", + query_string="", + api_base="https://api.stripe.com", + post_data="financial_account=fa_123&network=ach&amount=1234¤cy=usd", + ) + + def test_tokens_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/tokens/tok_xxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tokens.retrieve("tok_xxxx") + http_client_mock.assert_requested( + "get", + path="/v1/tokens/tok_xxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_tokens_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/tokens", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tokens.create( + { + "card": { + "number": "4242424242424242", + "exp_month": "5", + "exp_year": "2023", + "cvc": "314", + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/tokens", + query_string="", + api_base="https://api.stripe.com", + post_data="card[number]=4242424242424242&card[exp_month]=5&card[exp_year]=2023&card[cvc]=314", + ) + + def test_tokens_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/tokens", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tokens.create( + { + "bank_account": { + "country": "US", + "currency": "usd", + "account_holder_name": "Jenny Rosen", + "account_holder_type": "individual", + "routing_number": "110000000", + "account_number": "000123456789", + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/tokens", + query_string="", + api_base="https://api.stripe.com", + post_data="bank_account[country]=US&bank_account[currency]=usd&bank_account[account_holder_name]=Jenny%20Rosen&bank_account[account_holder_type]=individual&bank_account[routing_number]=110000000&bank_account[account_number]=000123456789", + ) + + def test_tokens_post_3_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/tokens", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tokens.create({"pii": {"id_number": "000000000"}}) + http_client_mock.assert_requested( + "post", + path="/v1/tokens", + query_string="", + api_base="https://api.stripe.com", + post_data="pii[id_number]=000000000", + ) + + def test_tokens_post_4_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/tokens", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tokens.create( + { + "account": { + "individual": {"first_name": "Jane", "last_name": "Doe"}, + "tos_shown_and_accepted": True, + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/tokens", + query_string="", + api_base="https://api.stripe.com", + post_data="account[individual][first_name]=Jane&account[individual][last_name]=Doe&account[tos_shown_and_accepted]=True", + ) + + def test_tokens_post_5_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/tokens", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tokens.create( + { + "person": { + "first_name": "Jane", + "last_name": "Doe", + "relationship": {"owner": True}, + }, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/tokens", + query_string="", + api_base="https://api.stripe.com", + post_data="person[first_name]=Jane&person[last_name]=Doe&person[relationship][owner]=True", + ) + + def test_tokens_post_6_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/tokens", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.tokens.create({"cvc_update": {"cvc": "123"}}) + http_client_mock.assert_requested( + "post", + path="/v1/tokens", + query_string="", + api_base="https://api.stripe.com", + post_data="cvc_update[cvc]=123", + ) + + def test_topups_cancel_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/topups/tu_xxxxxxxxxxxxx/cancel", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.topups.cancel("tu_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/topups/tu_xxxxxxxxxxxxx/cancel", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_topups_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/topups", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.topups.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/topups", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_topups_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/topups/tu_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.topups.retrieve("tu_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/topups/tu_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_topups_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/topups", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.topups.create( + { + "amount": 2000, + "currency": "usd", + "description": "Top-up for Jenny Rosen", + "statement_descriptor": "Top-up", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/topups", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=2000¤cy=usd&description=Top-up%20for%20Jenny%20Rosen&statement_descriptor=Top-up", + ) + + def test_topups_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/topups/tu_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.topups.update( + "tu_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/topups/tu_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_transfers_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/transfers", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.transfers.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/transfers", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_transfers_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/transfers/tr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.transfers.retrieve("tr_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/transfers/tr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_transfers_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/transfers", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.transfers.create( + { + "amount": 400, + "currency": "usd", + "destination": "acct_xxxxxxxxxxxxx", + "transfer_group": "ORDER_95", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/transfers", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=400¤cy=usd&destination=acct_xxxxxxxxxxxxx&transfer_group=ORDER_95", + ) + + def test_transfers_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/transfers/tr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.transfers.update( + "tr_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/transfers/tr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_transfers_reversals_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/transfers/tr_xxxxxxxxxxxxx/reversals", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.transfers.reversals.list( + "tr_xxxxxxxxxxxxx", + {"limit": 3}, + ) + http_client_mock.assert_requested( + "get", + path="/v1/transfers/tr_xxxxxxxxxxxxx/reversals", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_transfers_reversals_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/transfers/tr_xxxxxxxxxxxxx/reversals/trr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.transfers.reversals.retrieve( + "tr_xxxxxxxxxxxxx", + "trr_xxxxxxxxxxxxx", + ) + http_client_mock.assert_requested( + "get", + path="/v1/transfers/tr_xxxxxxxxxxxxx/reversals/trr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_transfers_reversals_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/transfers/tr_xxxxxxxxxxxxx/reversals", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.transfers.reversals.create( + "tr_xxxxxxxxxxxxx", + {"amount": 100}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/transfers/tr_xxxxxxxxxxxxx/reversals", + query_string="", + api_base="https://api.stripe.com", + post_data="amount=100", + ) + + def test_transfers_reversals_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/transfers/tr_xxxxxxxxxxxxx/reversals/trr_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.transfers.reversals.update( + "tr_xxxxxxxxxxxxx", + "trr_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/transfers/tr_xxxxxxxxxxxxx/reversals/trr_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_treasury_credit_reversals_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/credit_reversals", + "financial_account=fa_xxxxxxxxxxxxx&limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.credit_reversals.list( + { + "financial_account": "fa_xxxxxxxxxxxxx", + "limit": 3, + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/treasury/credit_reversals", + query_string="financial_account=fa_xxxxxxxxxxxxx&limit=3", + api_base="https://api.stripe.com", + ) + + def test_treasury_credit_reversals_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/credit_reversals/credrev_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.credit_reversals.retrieve("credrev_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/treasury/credit_reversals/credrev_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_treasury_credit_reversals_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/treasury/credit_reversals", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.credit_reversals.create( + { + "received_credit": "rc_xxxxxxxxxxxxx", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/treasury/credit_reversals", + query_string="", + api_base="https://api.stripe.com", + post_data="received_credit=rc_xxxxxxxxxxxxx", + ) + + def test_treasury_debit_reversals_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/debit_reversals", + "financial_account=fa_xxxxxxxxxxxxx&limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.debit_reversals.list( + { + "financial_account": "fa_xxxxxxxxxxxxx", + "limit": 3, + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/treasury/debit_reversals", + query_string="financial_account=fa_xxxxxxxxxxxxx&limit=3", + api_base="https://api.stripe.com", + ) + + def test_treasury_debit_reversals_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/debit_reversals/debrev_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.debit_reversals.retrieve("debrev_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/treasury/debit_reversals/debrev_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_treasury_debit_reversals_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/treasury/debit_reversals", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.debit_reversals.create( + { + "received_debit": "rd_xxxxxxxxxxxxx", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/treasury/debit_reversals", + query_string="", + api_base="https://api.stripe.com", + post_data="received_debit=rd_xxxxxxxxxxxxx", + ) + + def test_treasury_financial_accounts_features_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/financial_accounts/fa_xxxxxxxxxxxxx/features", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.financial_accounts.features.list("fa_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/treasury/financial_accounts/fa_xxxxxxxxxxxxx/features", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_treasury_financial_accounts_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/financial_accounts", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.financial_accounts.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/treasury/financial_accounts", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_treasury_financial_accounts_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/financial_accounts/fa_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.financial_accounts.retrieve("fa_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/treasury/financial_accounts/fa_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_treasury_financial_accounts_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/treasury/financial_accounts", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.financial_accounts.create( + { + "supported_currencies": ["usd"], + "features": {}, + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/treasury/financial_accounts", + query_string="", + api_base="https://api.stripe.com", + post_data="supported_currencies[0]=usd", + ) + + def test_treasury_financial_accounts_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/treasury/financial_accounts/fa_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.financial_accounts.update( + "fa_xxxxxxxxxxxxx", + {"metadata": {"order_id": "6735"}}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/treasury/financial_accounts/fa_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="metadata[order_id]=6735", + ) + + def test_treasury_inbound_transfers_cancel_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/treasury/inbound_transfers/ibt_xxxxxxxxxxxxx/cancel", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.inbound_transfers.cancel("ibt_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/treasury/inbound_transfers/ibt_xxxxxxxxxxxxx/cancel", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_treasury_inbound_transfers_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/inbound_transfers", + "financial_account=fa_xxxxxxxxxxxxx&limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.inbound_transfers.list( + { + "financial_account": "fa_xxxxxxxxxxxxx", + "limit": 3, + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/treasury/inbound_transfers", + query_string="financial_account=fa_xxxxxxxxxxxxx&limit=3", + api_base="https://api.stripe.com", + ) + + def test_treasury_inbound_transfers_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/inbound_transfers/ibt_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.inbound_transfers.retrieve("ibt_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/treasury/inbound_transfers/ibt_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_treasury_inbound_transfers_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/treasury/inbound_transfers", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.inbound_transfers.create( + { + "financial_account": "fa_xxxxxxxxxxxxx", + "amount": 10000, + "currency": "usd", + "origin_payment_method": "pm_xxxxxxxxxxxxx", + "description": "InboundTransfer from my bank account", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/treasury/inbound_transfers", + query_string="", + api_base="https://api.stripe.com", + post_data="financial_account=fa_xxxxxxxxxxxxx&amount=10000¤cy=usd&origin_payment_method=pm_xxxxxxxxxxxxx&description=InboundTransfer%20from%20my%20bank%20account", + ) + + def test_treasury_outbound_payments_cancel_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/treasury/outbound_payments/bot_xxxxxxxxxxxxx/cancel", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.outbound_payments.cancel("bot_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/treasury/outbound_payments/bot_xxxxxxxxxxxxx/cancel", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_treasury_outbound_payments_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/outbound_payments", + "financial_account=fa_xxxxxxxxxxxxx&limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.outbound_payments.list( + { + "financial_account": "fa_xxxxxxxxxxxxx", + "limit": 3, + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/treasury/outbound_payments", + query_string="financial_account=fa_xxxxxxxxxxxxx&limit=3", + api_base="https://api.stripe.com", + ) + + def test_treasury_outbound_payments_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/outbound_payments/bot_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.outbound_payments.retrieve("bot_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/treasury/outbound_payments/bot_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_treasury_outbound_payments_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/treasury/outbound_payments", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.outbound_payments.create( + { + "financial_account": "fa_xxxxxxxxxxxxx", + "amount": 10000, + "currency": "usd", + "customer": "cus_xxxxxxxxxxxxx", + "destination_payment_method": "pm_xxxxxxxxxxxxx", + "description": "OutboundPayment to a 3rd party", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/treasury/outbound_payments", + query_string="", + api_base="https://api.stripe.com", + post_data="financial_account=fa_xxxxxxxxxxxxx&amount=10000¤cy=usd&customer=cus_xxxxxxxxxxxxx&destination_payment_method=pm_xxxxxxxxxxxxx&description=OutboundPayment%20to%20a%203rd%20party", + ) + + def test_treasury_outbound_transfers_cancel_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/treasury/outbound_transfers/obt_xxxxxxxxxxxxx/cancel", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.outbound_transfers.cancel("obt_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "post", + path="/v1/treasury/outbound_transfers/obt_xxxxxxxxxxxxx/cancel", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_treasury_outbound_transfers_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/outbound_transfers", + "financial_account=fa_xxxxxxxxxxxxx&limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.outbound_transfers.list( + { + "financial_account": "fa_xxxxxxxxxxxxx", + "limit": 3, + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/treasury/outbound_transfers", + query_string="financial_account=fa_xxxxxxxxxxxxx&limit=3", + api_base="https://api.stripe.com", + ) + + def test_treasury_outbound_transfers_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/outbound_transfers/obt_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.outbound_transfers.retrieve("obt_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/treasury/outbound_transfers/obt_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_treasury_outbound_transfers_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/treasury/outbound_transfers", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.outbound_transfers.create( + { + "financial_account": "fa_xxxxxxxxxxxxx", + "destination_payment_method": "pm_xxxxxxxxxxxxx", + "amount": 500, + "currency": "usd", + "description": "OutboundTransfer to my external bank account", + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/treasury/outbound_transfers", + query_string="", + api_base="https://api.stripe.com", + post_data="financial_account=fa_xxxxxxxxxxxxx&destination_payment_method=pm_xxxxxxxxxxxxx&amount=500¤cy=usd&description=OutboundTransfer%20to%20my%20external%20bank%20account", + ) + + def test_treasury_received_credits_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/received_credits", + "financial_account=fa_xxxxxxxxxxxxx&limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.received_credits.list( + { + "financial_account": "fa_xxxxxxxxxxxxx", + "limit": 3, + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/treasury/received_credits", + query_string="financial_account=fa_xxxxxxxxxxxxx&limit=3", + api_base="https://api.stripe.com", + ) + + def test_treasury_received_credits_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/received_credits/rc_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.received_credits.retrieve("rc_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/treasury/received_credits/rc_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_treasury_received_debits_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/received_debits", + "financial_account=fa_xxxxxxxxxxxxx&limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.received_debits.list( + { + "financial_account": "fa_xxxxxxxxxxxxx", + "limit": 3, + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/treasury/received_debits", + query_string="financial_account=fa_xxxxxxxxxxxxx&limit=3", + api_base="https://api.stripe.com", + ) + + def test_treasury_received_debits_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/received_debits/rd_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.received_debits.retrieve("rd_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/treasury/received_debits/rd_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_treasury_transaction_entries_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/transaction_entries", + "financial_account=fa_xxxxxxxxxxxxx&limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.transaction_entries.list( + { + "financial_account": "fa_xxxxxxxxxxxxx", + "limit": 3, + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/treasury/transaction_entries", + query_string="financial_account=fa_xxxxxxxxxxxxx&limit=3", + api_base="https://api.stripe.com", + ) + + def test_treasury_transaction_entries_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/transaction_entries/trxne_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.transaction_entries.retrieve("trxne_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/treasury/transaction_entries/trxne_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_treasury_transactions_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/transactions", + "financial_account=fa_xxxxxxxxxxxxx&limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.transactions.list( + { + "financial_account": "fa_xxxxxxxxxxxxx", + "limit": 3, + } + ) + http_client_mock.assert_requested( + "get", + path="/v1/treasury/transactions", + query_string="financial_account=fa_xxxxxxxxxxxxx&limit=3", + api_base="https://api.stripe.com", + ) + + def test_treasury_transactions_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/treasury/transactions/trxn_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.treasury.transactions.retrieve("trxn_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/treasury/transactions/trxn_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_webhook_endpoints_delete_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "delete", + "/v1/webhook_endpoints/we_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.webhook_endpoints.delete("we_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "delete", + path="/v1/webhook_endpoints/we_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_webhook_endpoints_get_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/webhook_endpoints", + "limit=3", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.webhook_endpoints.list({"limit": 3}) + http_client_mock.assert_requested( + "get", + path="/v1/webhook_endpoints", + query_string="limit=3", + api_base="https://api.stripe.com", + ) + + def test_webhook_endpoints_get_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "get", + "/v1/webhook_endpoints/we_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.webhook_endpoints.retrieve("we_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/webhook_endpoints/we_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + ) + + def test_webhook_endpoints_post_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/webhook_endpoints", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.webhook_endpoints.create( + { + "url": "https://example.com/my/webhook/endpoint", + "enabled_events": ["charge.failed", "charge.succeeded"], + } + ) + http_client_mock.assert_requested( + "post", + path="/v1/webhook_endpoints", + query_string="", + api_base="https://api.stripe.com", + post_data="url=https%3A%2F%2Fexample.com%2Fmy%2Fwebhook%2Fendpoint&enabled_events[0]=charge.failed&enabled_events[1]=charge.succeeded", + ) + + def test_webhook_endpoints_post_2_service( + self, http_client_mock: HTTPClientMock + ) -> None: + http_client_mock.stub_request( + "post", + "/v1/webhook_endpoints/we_xxxxxxxxxxxxx", + ) + client = StripeClient( + "sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + + client.webhook_endpoints.update( + "we_xxxxxxxxxxxxx", + {"url": "https://example.com/new_endpoint"}, + ) + http_client_mock.assert_requested( + "post", + path="/v1/webhook_endpoints/we_xxxxxxxxxxxxx", + query_string="", + api_base="https://api.stripe.com", + post_data="url=https%3A%2F%2Fexample.com%2Fnew_endpoint", + ) diff --git a/tests/test_http_client.py b/tests/test_http_client.py index 60dc93aac..07c378ecb 100644 --- a/tests/test_http_client.py +++ b/tests/test_http_client.py @@ -1,5 +1,6 @@ from typing import Any from typing_extensions import Type +from unittest.mock import call import pytest import json @@ -146,63 +147,116 @@ def test_should_retry_on_codes(self): four_xx = list(range(400, 431)) client = _http_client.new_default_http_client() - client._max_network_retries = lambda: 1 codes = one_xx + two_xx + three_xx + four_xx codes.remove(409) # These status codes should not be retried by default. for code in codes: - assert client._should_retry((None, code, None), None, 0) is False + assert ( + client._should_retry( + (None, code, None), None, 0, max_network_retries=1 + ) + is False + ) # These status codes should be retried by default. - assert client._should_retry((None, 409, None), None, 0) is True - assert client._should_retry((None, 500, None), None, 0) is True - assert client._should_retry((None, 503, None), None, 0) is True + assert ( + client._should_retry( + (None, 409, None), None, 0, max_network_retries=1 + ) + is True + ) + assert ( + client._should_retry( + (None, 500, None), None, 0, max_network_retries=1 + ) + is True + ) + assert ( + client._should_retry( + (None, 503, None), None, 0, max_network_retries=1 + ) + is True + ) def test_should_retry_on_error(self, mocker): client = _http_client.new_default_http_client() - client._max_network_retries = lambda: 1 api_connection_error = mocker.Mock() api_connection_error.should_retry = True - assert client._should_retry(None, api_connection_error, 0) is True + assert ( + client._should_retry( + None, api_connection_error, 0, max_network_retries=1 + ) + is True + ) api_connection_error.should_retry = False - assert client._should_retry(None, api_connection_error, 0) is False + assert ( + client._should_retry( + None, api_connection_error, 0, max_network_retries=1 + ) + is False + ) def test_should_retry_on_stripe_should_retry_true(self, mocker): client = _http_client.new_default_http_client() - client._max_network_retries = lambda: 1 headers = {"stripe-should-retry": "true"} # Ordinarily, we would not retry a 400, but with the header as true, we would. - assert client._should_retry((None, 400, {}), None, 0) is False - assert client._should_retry((None, 400, headers), None, 0) is True + assert ( + client._should_retry( + (None, 400, {}), None, 0, max_network_retries=1 + ) + is False + ) + assert ( + client._should_retry( + (None, 400, headers), None, 0, max_network_retries=1 + ) + is True + ) def test_should_retry_on_stripe_should_retry_false(self, mocker): client = _http_client.new_default_http_client() - client._max_network_retries = lambda: 1 headers = {"stripe-should-retry": "false"} # Ordinarily, we would retry a 500, but with the header as false, we would not. - assert client._should_retry((None, 500, {}), None, 0) is True - assert client._should_retry((None, 500, headers), None, 0) is False + assert ( + client._should_retry( + (None, 500, {}), None, 0, max_network_retries=1 + ) + is True + ) + assert ( + client._should_retry( + (None, 500, headers), None, 0, max_network_retries=1 + ) + is False + ) def test_should_retry_on_num_retries(self, mocker): client = _http_client.new_default_http_client() max_test_retries = 10 - client._max_network_retries = lambda: max_test_retries api_connection_error = mocker.Mock() api_connection_error.should_retry = True assert ( client._should_retry( - None, api_connection_error, max_test_retries + 1 + None, + api_connection_error, + max_test_retries + 1, + max_network_retries=max_test_retries, ) is False ) assert ( - client._should_retry((None, 409, None), None, max_test_retries + 1) + client._should_retry( + (None, 409, None), + None, + max_test_retries + 1, + max_network_retries=max_test_retries, + ) is False ) @@ -411,7 +465,7 @@ def check_call( times=None, ): times = times or 1 - args = (method, url) + pargs = (method, url) kwargs = { "headers": headers, "data": post_data, @@ -423,7 +477,7 @@ def check_call( if is_streaming: kwargs["stream"] = True - calls = [(args, kwargs) for _ in range(times)] + calls = [call(*pargs, **kwargs) for _ in range(times)] session.request.assert_has_calls(calls) return check_call @@ -541,17 +595,18 @@ def make_client(self): # Override sleep time to speed up tests client._sleep_time_seconds = lambda num_retries, response=None: 0.0001 # Override configured max retries - client._max_network_retries = lambda: self.max_retries() return client def make_request(self, *args, **kwargs): client = self.make_client() - return client.request_with_retries("GET", self.valid_url, {}, None) + return client.request_with_retries( + "GET", self.valid_url, {}, None, self.max_retries() + ) def make_request_stream(self, *args, **kwargs): client = self.make_client() return client.request_stream_with_retries( - "GET", self.valid_url, {}, None + "GET", self.valid_url, {}, None, self.max_retries() ) def test_retry_error_until_response( diff --git a/tests/test_integration.py b/tests/test_integration.py index 7262ecc20..81b81d2a8 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -93,6 +93,7 @@ def setup_stripe(self): stripe.api_base = "http://localhost:12111" # stripe-mock stripe.api_key = "sk_test_123" stripe.default_http_client = None + stripe._default_proxy = None stripe.enable_telemetry = False stripe.max_network_retries = 3 stripe.proxy = None @@ -162,6 +163,38 @@ class MockServerRequestHandler(TestHandler): stripe.Balance.retrieve() assert MockServerRequestHandler.num_requests == 1 + def test_hits_proxy_through_stripe_client_proxy(self): + class MockServerRequestHandler(TestHandler): + pass + + self.setup_mock_server(MockServerRequestHandler) + + client = stripe.StripeClient( + "sk_test_123", + proxy="http://localhost:%s" % self.mock_server_port, + base_addresses={"api": "http://localhost:12111"}, + ) + client.balance.retrieve() + + assert MockServerRequestHandler.num_requests == 1 + + def test_hits_proxy_through_stripe_client_http_client(self): + class MockServerRequestHandler(TestHandler): + pass + + self.setup_mock_server(MockServerRequestHandler) + + client = stripe.StripeClient( + "sk_test_123", + http_client=stripe.http_client.new_default_http_client( + proxy="http://localhost:%s" % self.mock_server_port + ), + base_addresses={"api": "http://localhost:12111"}, + ) + client.balance.retrieve() + + assert MockServerRequestHandler.num_requests == 1 + def test_passes_client_telemetry_when_enabled(self): class MockServerRequestHandler(TestHandler): def do_request(self, req_num): diff --git a/tests/test_request_options.py b/tests/test_request_options.py new file mode 100644 index 000000000..b57995ba1 --- /dev/null +++ b/tests/test_request_options.py @@ -0,0 +1,57 @@ +from stripe._request_options import ( + RequestOptions, + merge_options, + extract_options_from_dict, +) +from stripe._requestor_options import RequestorOptions + + +class TestRequestOptions(object): + def test_merge(self): + options = RequestorOptions( + api_key="sk_test_123", + stripe_account="acct_123", + base_addresses={"api": "https://api.stripe.com"}, + ) + other: RequestOptions = { + "api_key": "sk_test_456", + "stripe_version": "2020-01-01", + "headers": {"foo": "bar"}, + } + merged = merge_options(options, other) + assert merged.get("api_key") == "sk_test_456" + assert merged.get("stripe_version") == "2020-01-01" + assert merged.get("stripe_account") == "acct_123" + assert merged.get("headers") == {"foo": "bar"} + + def test_merge_none(self): + options = RequestorOptions( + api_key="sk_test_123", + stripe_account="acct_123", + base_addresses={"api": "https://api.stripe.com"}, + ) + merged = merge_options(options, None) + assert merged.get("api_key") == "sk_test_123" + assert merged.get("stripe_version") is None + assert merged.get("stripe_account") == "acct_123" + assert merged.get("headers") is None + + def test_extract_from_dict(self): + options, remaining = extract_options_from_dict( + { + "api_key": "sk_test_123", + "stripe_version": "2020-01-01", + "stripe_account": "acct_123", + "idempotency_key": "idemp_123", + "headers": { + "X-Stripe-Header": "Some-Value", + }, + "foo": "bar", + } + ) + assert options.get("api_key") == "sk_test_123" + assert options.get("stripe_version") == "2020-01-01" + assert options.get("stripe_account") == "acct_123" + assert options.get("idempotency_key") == "idemp_123" + assert options.get("headers") == {"X-Stripe-Header": "Some-Value"} + assert remaining == {"foo": "bar"} diff --git a/tests/test_requestor_options.py b/tests/test_requestor_options.py new file mode 100644 index 000000000..2ed3731ad --- /dev/null +++ b/tests/test_requestor_options.py @@ -0,0 +1,70 @@ +import stripe +from stripe._requestor_options import ( + RequestorOptions, + _GlobalRequestorOptions, +) + + +class TestRequestorOptions(object): + def test_to_dict(self): + requestor = RequestorOptions( + api_key="sk_test_123", + stripe_account="acct_123", + stripe_version="2019-12-03", + base_addresses={ + "api": "https://api.example.com", + "connect": "https://connect.example.com", + "files": "https://files.example.com", + }, + max_network_retries=3, + ) + assert requestor.to_dict() == { + "api_key": "sk_test_123", + "stripe_account": "acct_123", + "stripe_version": "2019-12-03", + "base_addresses": { + "api": "https://api.example.com", + "connect": "https://connect.example.com", + "files": "https://files.example.com", + }, + "max_network_retries": 3, + } + + def test_global_options_get_updated( + self, + ): + global_options = _GlobalRequestorOptions() + orig_api_key = stripe.api_key + orig_api_base = stripe.api_base + orig_connect_base = stripe.connect_api_base + orig_upload_base = stripe.upload_api_base + orig_max_network_retries = stripe.max_network_retries + assert global_options.api_key == orig_api_key + assert global_options.base_addresses["api"] == orig_api_base + assert global_options.base_addresses["connect"] == orig_connect_base + assert global_options.base_addresses["files"] == orig_upload_base + assert global_options.stripe_account is None + stripe.api_key = "sk_test_555555555" + stripe.api_base = "https://api.example.com" + stripe.connect_api_base = "https://connect.example.com" + stripe.upload_api_base = "https://upload.example.com" + stripe.max_network_retries = 3 + assert global_options.api_key == "sk_test_555555555" + assert ( + global_options.base_addresses["api"] == "https://api.example.com" + ) + assert ( + global_options.base_addresses["connect"] + == "https://connect.example.com" + ) + assert ( + global_options.base_addresses["files"] + == "https://upload.example.com" + ) + assert global_options.stripe_account is None + assert global_options.max_network_retries == 3 + stripe.api_key = orig_api_key + stripe.api_base = orig_api_base + stripe.connect_api_base = orig_connect_base + stripe.upload_api_base = orig_upload_base + stripe.max_network_retries = orig_max_network_retries diff --git a/tests/test_stripe_client.py b/tests/test_stripe_client.py new file mode 100644 index 000000000..c04e9e6fe --- /dev/null +++ b/tests/test_stripe_client.py @@ -0,0 +1,374 @@ +from __future__ import absolute_import, division, print_function +import stripe +import pytest + +from stripe._http_client import new_default_http_client + + +class TestStripeClient(object): + def test_constructor_with_posargs(self): + client = stripe.StripeClient("sk_test_456") + assert client._requestor.api_key == "sk_test_456" + + def test_v1_customers_retrieve( + self, stripe_mock_stripe_client, http_client_mock + ): + method = "get" + path = "/v1/customers/cus_xxxxxxxxxxxxx" + http_client_mock.stub_request( + method, + path=path, + rbody='{"id": "cus_xxxxxxxxxxxxx","object": "customer"}', + rcode=200, + rheaders={}, + ) + customer = stripe_mock_stripe_client.customers.retrieve( + "cus_xxxxxxxxxxxxx" + ) + http_client_mock.assert_requested(method, path=path) + assert customer.id is not None + + def test_no_api_key(self): + with pytest.raises(stripe.error.AuthenticationError): + stripe.StripeClient(None) # type: ignore + + def test_http_client_and_options_overlap(self): + with pytest.raises(ValueError): + stripe.StripeClient( + api_key="sk_test_123", + http_client=new_default_http_client(), + proxy="http://localhost:8080", + ) + + with pytest.raises(ValueError): + stripe.StripeClient( + api_key="sk_test_123", + http_client=new_default_http_client(), + verify_ssl_certs=False, + ) + + def test_client_level_options(self, http_client_mock): + method = "get" + path = "/v1/customers/cus_xxxxxxxxxxxxx" + http_client_mock.stub_request( + method, + path=path, + rbody='{"id": "cus_xxxxxxxxxxxxx","object": "customer"}', + rcode=200, + rheaders={}, + ) + + api_base = "https://example.com" + api_key = "sk_test_456" + stripe_account = "acct_123" + + stripe_client = stripe.StripeClient( + api_key=api_key, + http_client=http_client_mock.get_mock_http_client(), + base_addresses={"api": api_base}, + stripe_account=stripe_account, + ) + + stripe_client.customers.retrieve("cus_xxxxxxxxxxxxx") + + http_client_mock.assert_requested( + method, + api_base=api_base, + path=path, + api_key=api_key, + stripe_account=stripe_account, + stripe_version=stripe.api_version, + ) + + def test_uses_default_api_base_if_none_specified(self, http_client_mock): + http_client_mock.stub_request( + "get", + "/v1/customers/cus_xxxxxxxxxxxxx", + ) + stripe.StripeClient( + api_key="sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ).customers.retrieve("cus_xxxxxxxxxxxxx") + + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx", + api_key="sk_test_123", + api_base=stripe.DEFAULT_API_BASE, + ) + + def test_request_level_options(self, http_client_mock): + method = "get" + path = "/v1/customers/cus_xxxxxxxxxxxxx" + http_client_mock.stub_request( + method, + path=path, + rbody='{"id": "cus_xxxxxxxxxxxxx","object": "customer"}', + rcode=200, + rheaders={}, + ) + + client_api_base = "https://example.com" + client_api_key = "sk_test_456" + client_stripe_account = "acct_123" + + request_api_key = "sk_test_789" + request_stripe_account = "acct_456" + + stripe_client = stripe.StripeClient( + api_key=client_api_key, + http_client=http_client_mock.get_mock_http_client(), + base_addresses={"api": client_api_base}, + stripe_account=client_stripe_account, + ) + + stripe_client.customers.retrieve( + "cus_xxxxxxxxxxxxx", + options={ + "api_key": request_api_key, + "stripe_account": request_stripe_account, + }, + ) + + http_client_mock.assert_requested( + method, + api_base=client_api_base, + path=path, + api_key=request_api_key, + stripe_account=request_stripe_account, + stripe_version=stripe.api_version, + ) + + def test_separate_clients_have_separate_options(self, http_client_mock): + method = "get" + path = "/v1/customers/cus_xxxxxxxxxxxxx" + http_client_mock.stub_request( + method, + path=path, + rbody='{"id": "cus_xxxxxxxxxxxxx","object": "customer"}', + rcode=200, + rheaders={}, + ) + + stripe_client_1 = stripe.StripeClient( + api_key="sk_test_123", + base_addresses={"api": "https://example.com"}, + http_client=http_client_mock.get_mock_http_client(), + ) + stripe_client_2 = stripe.StripeClient( + api_key="sk_test_456", + base_addresses={"api": "https://example2.com"}, + http_client=http_client_mock.get_mock_http_client(), + ) + + stripe_client_1.customers.retrieve("cus_xxxxxxxxxxxxx") + stripe_client_2.customers.retrieve("cus_xxxxxxxxxxxxx") + + http_client_mock.assert_requested( + method, + api_base="https://example.com", + path=path, + api_key="sk_test_123", + stripe_version=stripe.api_version, + ) + http_client_mock.assert_requested( + method, + api_base="https://example2.com", + path=path, + api_key="sk_test_456", + stripe_version=stripe.api_version, + ) + + def test_carries_over_requestor_options_to_resource( + self, http_client_mock + ): + client = stripe.StripeClient( + api_key="sk_test_123", + stripe_account="acct_123", + base_addresses={ + "api": "https://example.com", + }, + http_client=http_client_mock.get_mock_http_client(), + ) + http_client_mock.stub_request( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx", + rbody='{"id": "cus_xxxxxxxxxxxxx","object": "customer"}', + rcode=200, + rheaders={}, + ) + cus = client.customers.retrieve("cus_xxxxxxxxxxxxx") + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx", + api_key="sk_test_123", + stripe_account="acct_123", + api_base="https://example.com", + ) + + http_client_mock.stub_request( + "delete", + path="/v1/customers/cus_xxxxxxxxxxxxx", + rbody='{"id": "cus_xxxxxxxxxxxxx","object": "customer"}', + rcode=200, + rheaders={}, + ) + cus.delete() + http_client_mock.assert_requested( + "delete", + path="/v1/customers/cus_xxxxxxxxxxxxx", + api_key="sk_test_123", + stripe_account="acct_123", + api_base="https://example.com", + ) + + def test_user_options_are_not_mutated(self, http_client_mock): + client = stripe.StripeClient( + http_client=http_client_mock.get_mock_http_client(), + api_key="sk_test_abc", + ) + + http_client_mock.stub_request( + "get", + path="/v1/accounts", + rbody='{"data": [{"id": "x"}], "next_page": "page_2"}', + rcode=200, + rheaders={}, + ) + + my_options: stripe.RequestOptions = {"api_key": "sk_test_xyz"} + + client.accounts.list(options=my_options) + + assert my_options == {"api_key": "sk_test_xyz"} + + def test_carries_over_request_options_to_resource(self, http_client_mock): + client = stripe.StripeClient( + api_key="sk_test_123", + stripe_account="acct_123", + stripe_version="2019-12-03", + http_client=http_client_mock.get_mock_http_client(), + ) + http_client_mock.stub_request( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx", + rbody='{"id": "cus_xxxxxxxxxxxxx","object": "customer"}', + rcode=200, + rheaders={}, + ) + cus = client.customers.retrieve( + "cus_xxxxxxxxxxxxx", + {}, + { + "api_key": "sk_test_456", + "stripe_version": "2023-12-03", + "stripe_account": "acct_456", + }, + ) + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx", + api_key="sk_test_456", + stripe_account="acct_456", + stripe_version="2023-12-03", + ) + + http_client_mock.stub_request( + "delete", + path="/v1/customers/cus_xxxxxxxxxxxxx", + rbody='{"id": "cus_xxxxxxxxxxxxx","object": "customer"}', + rcode=200, + rheaders={}, + ) + + cus.delete() + assert cus._requestor is not client._requestor + http_client_mock.assert_requested( + "delete", + path="/v1/customers/cus_xxxxxxxxxxxxx", + api_key="sk_test_456", + stripe_account="acct_456", + stripe_version="2023-12-03", + ) + + def test_respects_max_network_retries_in_request_options( + self, http_client_mock + ): + client = stripe.StripeClient( + api_key="sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + ) + http_client_mock.stub_request( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx", + rbody='{"id": "cus_xxxxxxxxxxxxx","object": "customer"}', + rcode=200, + rheaders={}, + ) + + client.customers.retrieve( + "cus_xxxxxxxxxxxxx", + {}, + { + "max_network_retries": 2, + }, + ) + + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx", + api_key="sk_test_123", + max_network_retries=2, + ) + + def test_respects_max_network_retries_in_client_options( + self, http_client_mock + ): + client = stripe.StripeClient( + api_key="sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + max_network_retries=2, + ) + http_client_mock.stub_request( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx", + rbody='{"id": "cus_xxxxxxxxxxxxx","object": "customer"}', + rcode=200, + rheaders={}, + ) + + client.customers.retrieve("cus_xxxxxxxxxxxxx") + + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx", + api_key="sk_test_123", + max_network_retries=2, + ) + + def test_prefers_max_network_retries_in_request_options( + self, http_client_mock + ): + client = stripe.StripeClient( + api_key="sk_test_123", + http_client=http_client_mock.get_mock_http_client(), + max_network_retries=2, + ) + http_client_mock.stub_request( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx", + rbody='{"id": "cus_xxxxxxxxxxxxx","object": "customer"}', + rcode=200, + rheaders={}, + ) + + client.customers.retrieve( + "cus_xxxxxxxxxxxxx", options={"max_network_retries": 0} + ) + + http_client_mock.assert_requested( + "get", + path="/v1/customers/cus_xxxxxxxxxxxxx", + api_key="sk_test_123", + max_network_retries=0, + ) diff --git a/tests/test_stripe_object.py b/tests/test_stripe_object.py index 2e984f15e..94780da14 100644 --- a/tests/test_stripe_object.py +++ b/tests/test_stripe_object.py @@ -138,7 +138,7 @@ def test_refresh_from(self, mocker): assert obj.api_key == "mykey" assert obj.foo == "bar" assert obj["trans"] == "me" - assert obj.stripe_version is None + assert obj.stripe_version is stripe.api_version assert obj.stripe_account is None assert obj.last_response is None @@ -392,9 +392,42 @@ def test_sends_request_with_api_key(self, http_client_mock): path="/foo", ) - obj.request("get", "/foo") + obj._request("get", "/foo", base_address="api", api_mode="V1") http_client_mock.assert_requested( api_key="key", stripe_account=None, ) + + def test_refresh_from_creates_new_requestor(self): + obj = stripe.stripe_object.StripeObject.construct_from( + {}, key="origkey" + ) + + orig_requestor = obj._requestor + assert obj.api_key == "origkey" + + obj.refresh_from({}, "newkey") + + new_requestor = obj._requestor + assert orig_requestor is not new_requestor + assert obj.api_key == "newkey" + assert orig_requestor.api_key == "origkey" + + def test_can_update_api_key(self, http_client_mock): + obj = stripe.stripe_object.StripeObject("id", "key") + + http_client_mock.stub_request( + "get", + path="/foo", + ) + + obj.api_key = "key2" + obj._request("get", "/foo", base_address="api", api_mode="V1") + + assert "api_key" not in obj.items() + + http_client_mock.assert_requested( + api_key="key2", + stripe_account=None, + ) diff --git a/tests/test_webhook.py b/tests/test_webhook.py index 52568e464..53389f725 100644 --- a/tests/test_webhook.py +++ b/tests/test_webhook.py @@ -7,7 +7,8 @@ DUMMY_WEBHOOK_PAYLOAD = """{ "id": "evt_test_webhook", - "object": "event" + "object": "event", + "data": { "object": { "id": "rdr_123", "object": "terminal.reader" } } }""" DUMMY_WEBHOOK_SECRET = "whsec_test_secret" @@ -129,3 +130,69 @@ def test_timestamp_off_but_no_tolerance(self): assert stripe.WebhookSignature.verify_header( DUMMY_WEBHOOK_PAYLOAD, header, DUMMY_WEBHOOK_SECRET ) + + +class TestStripeClientConstructEvent(object): + def test_construct_event(self, stripe_mock_stripe_client): + header = generate_header() + event = stripe_mock_stripe_client.construct_event( + DUMMY_WEBHOOK_PAYLOAD, header, DUMMY_WEBHOOK_SECRET + ) + assert isinstance(event, stripe.Event) + + def test_raise_on_json_error(self, stripe_mock_stripe_client): + payload = "this is not valid JSON" + header = generate_header(payload=payload) + with pytest.raises(ValueError): + stripe_mock_stripe_client.construct_event( + payload, header, DUMMY_WEBHOOK_SECRET + ) + + def test_raise_on_invalid_header(self, stripe_mock_stripe_client): + header = "bad_header" + with pytest.raises(stripe.error.SignatureVerificationError): + stripe_mock_stripe_client.construct_event( + DUMMY_WEBHOOK_PAYLOAD, header, DUMMY_WEBHOOK_SECRET + ) + + def test_construct_event_from_bytearray(self, stripe_mock_stripe_client): + header = generate_header() + payload = bytearray(DUMMY_WEBHOOK_PAYLOAD, "utf-8") + event = stripe_mock_stripe_client.construct_event( + payload, header, DUMMY_WEBHOOK_SECRET + ) + assert isinstance(event, stripe.Event) + + def test_construct_event_from_bytes(self, stripe_mock_stripe_client): + header = generate_header() + payload = bytes(DUMMY_WEBHOOK_PAYLOAD, "utf-8") + event = stripe_mock_stripe_client.construct_event( + payload, header, DUMMY_WEBHOOK_SECRET + ) + assert isinstance(event, stripe.Event) + + def test_construct_event_inherits_requestor(self, http_client_mock): + http_client_mock.stub_request("delete", "/v1/terminal/readers/rdr_123") + + client = stripe.StripeClient( + "sk_test_777", + stripe_account="acct_777", + stripe_version="2222-22-22", + http_client=http_client_mock.get_mock_http_client(), + ) + header = generate_header() + event = client.construct_event( + DUMMY_WEBHOOK_PAYLOAD, header, DUMMY_WEBHOOK_SECRET + ) + assert event._requestor == client._requestor + + assert isinstance(event.data.object, stripe.terminal.Reader) + event.data.object.delete() + + http_client_mock.assert_requested( + "delete", + path="/v1/terminal/readers/rdr_123", + api_key="sk_test_777", + stripe_account="acct_777", + stripe_version="2222-22-22", + )