swarmauri_billing_square 0.9.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Jacob Stewart @ Swarmauri]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.4
2
+ Name: swarmauri_billing_square
3
+ Version: 0.9.2
4
+ Summary: Square billing provider for the Swarmauri SDK.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Keywords: swarmauri,sdk,billing,square,community,payments,point of sale,payment gateway,recurring billing,subscription management,e-commerce integration
8
+ Author: Jacob Stewart
9
+ Author-email: jacob@swarmauri.com
10
+ Requires-Python: >=3.10,<3.13
11
+ Classifier: Development Status :: 1 - Planning
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Information Technology
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Office/Business :: Financial :: Point-Of-Sale
22
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
23
+ Requires-Dist: squareup (>=33.0.0)
24
+ Requires-Dist: swarmauri_base
25
+ Requires-Dist: swarmauri_core
26
+ Description-Content-Type: text/markdown
27
+
28
+ ![Swarmauri Logo](https://github.com/swarmauri/swarmauri-sdk/blob/3d4d1cfa949399d7019ae9d8f296afba773dfb7f/assets/swarmauri.brand.theme.svg)
29
+
30
+ <p align="center">
31
+ <a href="https://pypi.org/project/swarmauri_billing_square/">
32
+ <img src="https://img.shields.io/pypi/dm/swarmauri_billing_square" alt="PyPI - Downloads"/></a>
33
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_billing_square/">
34
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_billing_square.svg"/></a>
35
+ <a href="https://pypi.org/project/swarmauri_billing_square/">
36
+ <img src="https://img.shields.io/pypi/pyversions/swarmauri_billing_square" alt="PyPI - Python Version"/></a>
37
+ <a href="https://pypi.org/project/swarmauri_billing_square/">
38
+ <img src="https://img.shields.io/pypi/l/swarmauri_billing_square" alt="PyPI - License"/></a>
39
+ <a href="https://pypi.org/project/swarmauri_billing_square/">
40
+ <img src="https://img.shields.io/pypi/v/swarmauri_billing_square?label=swarmauri_billing_square&color=green" alt="PyPI - swarmauri_billing_square"/></a>
41
+ </p>
42
+
43
+ ---
44
+
45
+ # Swarmauri Billing Square
46
+
47
+ The **Swarmauri Billing Square** package delivers a Square-backed billing provider that speaks the Swarmauri billing interfaces. It uses the official Square Python SDK to manage catalog items, hosted checkout links, card-not-present payments, subscriptions, and invoices.
48
+
49
+ ## Features
50
+
51
+ - ✅ Turns Square catalog items and variations into Swarmauri product and price references.
52
+ - ✅ Generates hosted checkout links through the Payments API Link service.
53
+ - ✅ Supports payment intents, captures, and cancellations using Square's server APIs.
54
+ - ✅ Manages subscriptions and invoices, including publishing and cancellation flows.
55
+ - ✅ Surfaces marketplace fee splits and dispute listings for downstream automation.
56
+
57
+ ## Installation
58
+
59
+ ```bash
60
+ pip install swarmauri_billing_square
61
+ ```
62
+
63
+ ```bash
64
+ uv add swarmauri_billing_square
65
+ ```
66
+
67
+ ## Usage
68
+
69
+ ```python
70
+ from swarmauri_billing_square import SquareBillingProvider
71
+ from swarmauri_base.billing import CheckoutRequest, PriceSpec, ProductSpec
72
+
73
+ provider = SquareBillingProvider(
74
+ access_token="sq0atp-...",
75
+ location_id="L8899XYZ",
76
+ )
77
+
78
+ product = provider.create_product(
79
+ ProductSpec(name="Digital Membership", description="Premium access"),
80
+ idempotency_key="prod-square-001",
81
+ )
82
+
83
+ price = provider.create_price(
84
+ product,
85
+ PriceSpec(currency="USD", unit_amount_minor=2500, nickname="Monthly"),
86
+ idempotency_key="price-square-001",
87
+ )
88
+
89
+ checkout = provider.create_checkout(
90
+ price,
91
+ CheckoutRequest(
92
+ quantity=1,
93
+ success_url="https://merchant.example/success",
94
+ cancel_url="https://merchant.example/cancel",
95
+ idempotency_key="checkout-square-001",
96
+ ),
97
+ )
98
+
99
+ print(product.id, price.id, checkout.url)
100
+ ```
101
+
102
+ ## Capability Mapping
103
+
104
+ Square capabilities advertised by this provider map to `swarmauri_core.billing.Capability`. Use `capabilities_to_tigrbl` to translate capabilities to the tigrbl billing vocabulary when required.
105
+
106
+ ## Contributing
107
+
108
+ Community improvements are welcome! Enhancements that broaden Square API coverage or harden error handling are greatly appreciated.
109
+
@@ -0,0 +1,81 @@
1
+ ![Swarmauri Logo](https://github.com/swarmauri/swarmauri-sdk/blob/3d4d1cfa949399d7019ae9d8f296afba773dfb7f/assets/swarmauri.brand.theme.svg)
2
+
3
+ <p align="center">
4
+ <a href="https://pypi.org/project/swarmauri_billing_square/">
5
+ <img src="https://img.shields.io/pypi/dm/swarmauri_billing_square" alt="PyPI - Downloads"/></a>
6
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_billing_square/">
7
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_billing_square.svg"/></a>
8
+ <a href="https://pypi.org/project/swarmauri_billing_square/">
9
+ <img src="https://img.shields.io/pypi/pyversions/swarmauri_billing_square" alt="PyPI - Python Version"/></a>
10
+ <a href="https://pypi.org/project/swarmauri_billing_square/">
11
+ <img src="https://img.shields.io/pypi/l/swarmauri_billing_square" alt="PyPI - License"/></a>
12
+ <a href="https://pypi.org/project/swarmauri_billing_square/">
13
+ <img src="https://img.shields.io/pypi/v/swarmauri_billing_square?label=swarmauri_billing_square&color=green" alt="PyPI - swarmauri_billing_square"/></a>
14
+ </p>
15
+
16
+ ---
17
+
18
+ # Swarmauri Billing Square
19
+
20
+ The **Swarmauri Billing Square** package delivers a Square-backed billing provider that speaks the Swarmauri billing interfaces. It uses the official Square Python SDK to manage catalog items, hosted checkout links, card-not-present payments, subscriptions, and invoices.
21
+
22
+ ## Features
23
+
24
+ - ✅ Turns Square catalog items and variations into Swarmauri product and price references.
25
+ - ✅ Generates hosted checkout links through the Payments API Link service.
26
+ - ✅ Supports payment intents, captures, and cancellations using Square's server APIs.
27
+ - ✅ Manages subscriptions and invoices, including publishing and cancellation flows.
28
+ - ✅ Surfaces marketplace fee splits and dispute listings for downstream automation.
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ pip install swarmauri_billing_square
34
+ ```
35
+
36
+ ```bash
37
+ uv add swarmauri_billing_square
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ```python
43
+ from swarmauri_billing_square import SquareBillingProvider
44
+ from swarmauri_base.billing import CheckoutRequest, PriceSpec, ProductSpec
45
+
46
+ provider = SquareBillingProvider(
47
+ access_token="sq0atp-...",
48
+ location_id="L8899XYZ",
49
+ )
50
+
51
+ product = provider.create_product(
52
+ ProductSpec(name="Digital Membership", description="Premium access"),
53
+ idempotency_key="prod-square-001",
54
+ )
55
+
56
+ price = provider.create_price(
57
+ product,
58
+ PriceSpec(currency="USD", unit_amount_minor=2500, nickname="Monthly"),
59
+ idempotency_key="price-square-001",
60
+ )
61
+
62
+ checkout = provider.create_checkout(
63
+ price,
64
+ CheckoutRequest(
65
+ quantity=1,
66
+ success_url="https://merchant.example/success",
67
+ cancel_url="https://merchant.example/cancel",
68
+ idempotency_key="checkout-square-001",
69
+ ),
70
+ )
71
+
72
+ print(product.id, price.id, checkout.url)
73
+ ```
74
+
75
+ ## Capability Mapping
76
+
77
+ Square capabilities advertised by this provider map to `swarmauri_core.billing.Capability`. Use `capabilities_to_tigrbl` to translate capabilities to the tigrbl billing vocabulary when required.
78
+
79
+ ## Contributing
80
+
81
+ Community improvements are welcome! Enhancements that broaden Square API coverage or harden error handling are greatly appreciated.
@@ -0,0 +1,86 @@
1
+ [project]
2
+ name = "swarmauri_billing_square"
3
+ version = "0.9.2"
4
+ description = "Square billing provider for the Swarmauri SDK."
5
+ license = "Apache-2.0"
6
+ readme = "README.md"
7
+ repository = "http://github.com/swarmauri/swarmauri-sdk"
8
+ requires-python = ">=3.10,<3.13"
9
+ classifiers = [
10
+ "Development Status :: 1 - Planning",
11
+ "Intended Audience :: Developers",
12
+ "Intended Audience :: Information Technology",
13
+ "License :: OSI Approved :: Apache Software License",
14
+ "Operating System :: OS Independent",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Topic :: Office/Business :: Financial :: Point-Of-Sale",
21
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
22
+ ]
23
+ authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
24
+ dependencies = [
25
+ "swarmauri_core",
26
+ "swarmauri_base",
27
+ "squareup>=33.0.0",
28
+ ]
29
+ keywords = [
30
+ "swarmauri",
31
+ "sdk",
32
+ "billing",
33
+ "square",
34
+ "community",
35
+ "payments",
36
+ "point of sale",
37
+ "payment gateway",
38
+ "recurring billing",
39
+ "subscription management",
40
+ "e-commerce integration",
41
+ ]
42
+
43
+ [tool.uv.sources]
44
+ swarmauri_core = { workspace = true }
45
+ swarmauri_base = { workspace = true }
46
+
47
+ [tool.pytest.ini_options]
48
+ norecursedirs = ["combined", "scripts"]
49
+ markers = [
50
+ "test: standard test",
51
+ "unit: Unit tests",
52
+ "i9n: Integration tests",
53
+ "r8n: Regression tests",
54
+ "timeout: mark test to timeout after X seconds",
55
+ "xpass: Expected passes",
56
+ "xfail: Expected failures",
57
+ "acceptance: Acceptance tests",
58
+ "perf: Performance tests that measure execution time and resource usage",
59
+ ]
60
+ timeout = 300
61
+ log_cli = true
62
+ log_cli_level = "INFO"
63
+ log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
64
+ log_cli_date_format = "%Y-%m-%d %H:%M:%S"
65
+ asyncio_default_fixture_loop_scope = "function"
66
+
67
+ [project.entry-points.'swarmauri.billing_providers']
68
+ SquareBillingProvider = "swarmauri_billing_square.provider:SquareBillingProvider"
69
+
70
+ [build-system]
71
+ requires = ["poetry-core>=1.0.0"]
72
+ build-backend = "poetry.core.masonry.api"
73
+
74
+ [dependency-groups]
75
+ dev = [
76
+ "pytest>=8.0",
77
+ "pytest-asyncio>=0.24.0",
78
+ "pytest-xdist>=3.6.1",
79
+ "pytest-json-report>=1.5.0",
80
+ "python-dotenv",
81
+ "requests>=2.32.3",
82
+ "flake8>=7.0",
83
+ "pytest-timeout>=2.3.1",
84
+ "ruff>=0.9.9",
85
+ "pytest-benchmark>=4.0.0",
86
+ ]
@@ -0,0 +1,5 @@
1
+ """Square billing provider package."""
2
+
3
+ from .provider import SquareBillingProvider
4
+
5
+ __all__ = ["SquareBillingProvider"]
@@ -0,0 +1,432 @@
1
+ """Square billing provider implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Mapping, Optional, Sequence, cast
6
+
7
+ from pydantic import Field, PrivateAttr, SecretStr
8
+
9
+ from swarmauri_base.billing import (
10
+ BillingProviderBase,
11
+ BillingSpec,
12
+ CheckoutIntentRef,
13
+ CheckoutRequest,
14
+ HostedCheckoutMixin,
15
+ InvoicingMixin,
16
+ InvoiceSpec,
17
+ MarketplaceMixin,
18
+ OnlinePaymentsMixin,
19
+ PaymentIntentRequest,
20
+ PaymentRef,
21
+ PriceRef,
22
+ PriceSpec,
23
+ ProductRef,
24
+ ProductSpec,
25
+ ProductsPricesMixin,
26
+ RiskMixin,
27
+ SplitSpec,
28
+ SubscriptionSpec,
29
+ SubscriptionsMixin,
30
+ )
31
+
32
+
33
+ class SquareBillingProvider(
34
+ ProductsPricesMixin,
35
+ HostedCheckoutMixin,
36
+ OnlinePaymentsMixin,
37
+ SubscriptionsMixin,
38
+ InvoicingMixin,
39
+ MarketplaceMixin,
40
+ RiskMixin,
41
+ BillingProviderBase,
42
+ ):
43
+ """Concrete billing provider backed by the Square Python SDK."""
44
+
45
+ component_name: str = "square"
46
+ access_token: SecretStr = Field(repr=False)
47
+ environment: str = Field(default="sandbox", description="Square environment")
48
+ location_id: str = Field(..., description="Default Square location identifier")
49
+ _client: Any = PrivateAttr(default=None)
50
+
51
+ # ------------------------------------------------------------------ Client
52
+ def _sq(self) -> Any:
53
+ if self._client is None:
54
+ from square.client import Client
55
+
56
+ self._client = Client(
57
+ access_token=self.access_token.get_secret_value(),
58
+ environment=self.environment,
59
+ )
60
+ return self._client
61
+
62
+ @staticmethod
63
+ def _raise_if_error(response: Any) -> None:
64
+ if hasattr(response, "is_error") and response.is_error():
65
+ raise RuntimeError(str(response.errors))
66
+
67
+ @staticmethod
68
+ def _require(spec: BillingSpec | Any, field: str) -> Any:
69
+ value = getattr(
70
+ spec, "resolve", lambda name, default=None: getattr(spec, name, default)
71
+ )(field)
72
+ if value is None or (isinstance(value, str) and not value):
73
+ raise ValueError(f"{field} is required for {spec.__class__.__name__}")
74
+ return value
75
+
76
+ # ---------------------------------------------------------------- Products & Prices
77
+ def _create_product(
78
+ self, product_spec: ProductSpec, *, idempotency_key: str
79
+ ) -> ProductRef:
80
+ sq = self._sq()
81
+ name = self._require(product_spec, "name")
82
+ description = product_spec.resolve("description") or ""
83
+ tmp_id = f"#{idempotency_key}-item"
84
+ response = sq.catalog.upsert_catalog_object(
85
+ body={
86
+ "idempotency_key": idempotency_key,
87
+ "object": {
88
+ "id": tmp_id,
89
+ "type": "ITEM",
90
+ "present_at_all_locations": True,
91
+ "item_data": {
92
+ "name": name,
93
+ "description": description,
94
+ },
95
+ },
96
+ }
97
+ )
98
+ self._raise_if_error(response)
99
+ catalog_object = response.body["catalog_object"]
100
+ ref = ProductRef(
101
+ id=catalog_object["id"],
102
+ provider=self.component_name,
103
+ name=catalog_object.get("item_data", {}).get("name"),
104
+ description=catalog_object.get("item_data", {}).get("description"),
105
+ raw=response.body,
106
+ )
107
+ return ref
108
+
109
+ def _create_price(
110
+ self,
111
+ product: ProductRef,
112
+ price_spec: PriceSpec,
113
+ *,
114
+ idempotency_key: str,
115
+ ) -> PriceRef:
116
+ sq = self._sq()
117
+ amount = int(self._require(price_spec, "unit_amount_minor"))
118
+ currency = str(self._require(price_spec, "currency")).upper()
119
+ nickname = price_spec.resolve("nickname") or "Default"
120
+ tmp_id = f"#{idempotency_key}-var"
121
+ response = sq.catalog.upsert_catalog_object(
122
+ body={
123
+ "idempotency_key": idempotency_key,
124
+ "object": {
125
+ "id": tmp_id,
126
+ "type": "ITEM_VARIATION",
127
+ "present_at_all_locations": True,
128
+ "item_variation_data": {
129
+ "item_id": product.id,
130
+ "name": nickname,
131
+ "pricing_type": "FIXED_PRICING",
132
+ "price_money": {
133
+ "amount": amount,
134
+ "currency": currency,
135
+ },
136
+ },
137
+ },
138
+ }
139
+ )
140
+ self._raise_if_error(response)
141
+ mappings = response.body.get("id_mappings", [])
142
+ object_id = next(
143
+ (m["object_id"] for m in mappings if m["client_object_id"] == tmp_id),
144
+ None,
145
+ )
146
+ if object_id is None:
147
+ raise RuntimeError("Square did not return a mapped price identifier")
148
+ ref = PriceRef(
149
+ id=object_id,
150
+ product_id=product.id,
151
+ currency=currency.lower(),
152
+ unit_amount_minor=amount,
153
+ provider=self.component_name,
154
+ raw=response.body,
155
+ )
156
+ return ref
157
+
158
+ # ---------------------------------------------------------------- Hosted Checkout
159
+ def _create_checkout(
160
+ self, price: PriceRef, request: CheckoutRequest
161
+ ) -> CheckoutIntentRef:
162
+ sq = self._sq()
163
+ response = sq.checkout.create_payment_link(
164
+ body={
165
+ "idempotency_key": request.resolve("idempotency_key")
166
+ or f"chk-{price.id}",
167
+ "order": {
168
+ "location_id": self.location_id,
169
+ "line_items": [
170
+ {
171
+ "catalog_object_id": price.id,
172
+ "quantity": str(request.quantity),
173
+ }
174
+ ],
175
+ },
176
+ "checkout_options": {
177
+ "redirect_url": self._require(request, "success_url"),
178
+ },
179
+ }
180
+ )
181
+ self._raise_if_error(response)
182
+ payment_link = response.body["payment_link"]
183
+ intent = CheckoutIntentRef(
184
+ id=payment_link["id"],
185
+ url=payment_link.get("url"),
186
+ provider=self.component_name,
187
+ raw=response.body,
188
+ )
189
+ return intent
190
+
191
+ # ---------------------------------------------------------------- Online Payments
192
+ def _create_payment_intent(self, req: PaymentIntentRequest) -> PaymentRef:
193
+ sq = self._sq()
194
+ amount = int(self._require(req, "amount_minor"))
195
+ currency = str(self._require(req, "currency")).upper()
196
+ response = sq.payments.create(
197
+ source_id=req.resolve("payment_method_id") or "EXTERNAL",
198
+ idempotency_key=req.resolve("idempotency_key"),
199
+ amount_money={"amount": amount, "currency": currency},
200
+ autocomplete=req.capture,
201
+ location_id=self.location_id,
202
+ )
203
+ self._raise_if_error(response)
204
+ payment = response.body["payment"]
205
+ ref = PaymentRef(
206
+ id=payment["id"],
207
+ status=payment.get("status"),
208
+ amount_minor=payment.get("amount_money", {}).get("amount"),
209
+ currency=payment.get("amount_money", {}).get("currency"),
210
+ provider=self.component_name,
211
+ raw=response.body,
212
+ )
213
+ return ref
214
+
215
+ def _capture_payment(
216
+ self, payment_id: str, *, idempotency_key: Optional[str] = None
217
+ ) -> PaymentRef:
218
+ sq = self._sq()
219
+ response = sq.payments.complete_payment(payment_id)
220
+ self._raise_if_error(response)
221
+ payment = response.body["payment"]
222
+ ref = PaymentRef(
223
+ id=payment["id"],
224
+ status=payment.get("status"),
225
+ amount_minor=payment.get("amount_money", {}).get("amount"),
226
+ currency=payment.get("amount_money", {}).get("currency"),
227
+ provider=self.component_name,
228
+ raw=response.body,
229
+ )
230
+ return ref
231
+
232
+ def _cancel_payment(
233
+ self,
234
+ payment_id: str,
235
+ *,
236
+ reason: Optional[str] = None,
237
+ idempotency_key: Optional[str] = None,
238
+ ) -> PaymentRef:
239
+ sq = self._sq()
240
+ response = sq.payments.cancel_payment(payment_id)
241
+ self._raise_if_error(response)
242
+ payment = response.body["payment"]
243
+ ref = PaymentRef(
244
+ id=payment["id"],
245
+ status=payment.get("status"),
246
+ amount_minor=payment.get("amount_money", {}).get("amount"),
247
+ currency=payment.get("amount_money", {}).get("currency"),
248
+ provider=self.component_name,
249
+ raw=response.body,
250
+ )
251
+ return ref
252
+
253
+ # ---------------------------------------------------------------- Subscriptions
254
+ def _create_subscription(
255
+ self, spec: SubscriptionSpec, *, idempotency_key: str
256
+ ) -> Mapping[str, Any]:
257
+ sq = self._sq()
258
+ plan_id = spec.items[0].price_id
259
+ response = sq.subscriptions.create_subscription(
260
+ idempotency_key=idempotency_key,
261
+ location_id=self.location_id,
262
+ customer_id=self._require(spec, "customer_id"),
263
+ plan_id=plan_id,
264
+ )
265
+ self._raise_if_error(response)
266
+ subscription = response.body["subscription"]
267
+ result = {
268
+ "subscription_id": subscription["id"],
269
+ "status": subscription.get("status"),
270
+ "provider": self.component_name,
271
+ "raw": response.body,
272
+ }
273
+ return result
274
+
275
+ def _cancel_subscription(
276
+ self, subscription_id: str, *, at_period_end: bool = True
277
+ ) -> Mapping[str, Any]:
278
+ sq = self._sq()
279
+ if at_period_end:
280
+ response = sq.subscriptions.update_subscription(
281
+ subscription_id,
282
+ body={
283
+ "subscription": {
284
+ "canceled_date": None,
285
+ "status": "CANCEL_PENDING",
286
+ }
287
+ },
288
+ )
289
+ else:
290
+ response = sq.subscriptions.cancel_subscription(subscription_id)
291
+ self._raise_if_error(response)
292
+ subscription = response.body.get("subscription") or {}
293
+ result = {
294
+ "subscription_id": subscription_id,
295
+ "status": subscription.get("status", "CANCELED"),
296
+ "provider": self.component_name,
297
+ "raw": response.body,
298
+ }
299
+ return result
300
+
301
+ # ---------------------------------------------------------------- Invoicing
302
+ def _create_invoice(
303
+ self, spec: InvoiceSpec, *, idempotency_key: str
304
+ ) -> Mapping[str, Any]:
305
+ sq = self._sq()
306
+ response = sq.invoices.create_invoice(
307
+ invoice={
308
+ "location_id": self.location_id,
309
+ "primary_recipient": {
310
+ "customer_id": self._require(spec, "customer_id")
311
+ },
312
+ "payment_requests": [
313
+ {
314
+ "request_type": "BALANCE",
315
+ **(
316
+ {"due_date": f"+{spec.resolve('days_until_due')}d"}
317
+ if spec.resolve("collection_method") == "send_invoice"
318
+ else {}
319
+ ),
320
+ }
321
+ ],
322
+ },
323
+ idempotency_key=idempotency_key,
324
+ )
325
+ self._raise_if_error(response)
326
+ invoice = response.body["invoice"]
327
+ result = {
328
+ "invoice_id": invoice["id"],
329
+ "status": invoice.get("status"),
330
+ "provider": self.component_name,
331
+ "raw": response.body,
332
+ }
333
+ return result
334
+
335
+ def _finalize_invoice(self, invoice_id: str) -> Mapping[str, Any]:
336
+ sq = self._sq()
337
+ response = sq.invoices.publish_invoice(
338
+ invoice_id=invoice_id, idempotency_key=f"pub-{invoice_id}"
339
+ )
340
+ self._raise_if_error(response)
341
+ invoice = response.body["invoice"]
342
+ result = {
343
+ "invoice_id": invoice["id"],
344
+ "status": invoice.get("status"),
345
+ "provider": self.component_name,
346
+ "raw": response.body,
347
+ }
348
+ return result
349
+
350
+ def _void_invoice(self, invoice_id: str) -> Mapping[str, Any]:
351
+ sq = self._sq()
352
+ response = sq.invoices.cancel_invoice(
353
+ invoice_id=invoice_id, idempotency_key=f"void-{invoice_id}"
354
+ )
355
+ self._raise_if_error(response)
356
+ result = {
357
+ "invoice_id": invoice_id,
358
+ "status": "CANCELED",
359
+ "provider": self.component_name,
360
+ "raw": response.body,
361
+ }
362
+ return result
363
+
364
+ def _mark_uncollectible(self, invoice_id: str) -> Mapping[str, Any]:
365
+ sq = self._sq()
366
+ response = sq.invoices.cancel_invoice(
367
+ invoice_id=invoice_id, idempotency_key=f"void-{invoice_id}"
368
+ )
369
+ self._raise_if_error(response)
370
+ result = {
371
+ "invoice_id": invoice_id,
372
+ "status": "CANCELED",
373
+ "provider": self.component_name,
374
+ "raw": response.body,
375
+ }
376
+ return result
377
+
378
+ # ---------------------------------------------------------------- Marketplace
379
+ def _create_split(
380
+ self, spec: SplitSpec, *, idempotency_key: str
381
+ ) -> Mapping[str, Any]:
382
+ result = {
383
+ "split": spec.model_dump(mode="json"),
384
+ "provider": self.component_name,
385
+ }
386
+ return result
387
+
388
+ def _charge_with_split(
389
+ self,
390
+ amount_minor: int,
391
+ currency: str,
392
+ *,
393
+ split_code_or_params: Mapping[str, Any],
394
+ idempotency_key: str,
395
+ ) -> Mapping[str, Any]:
396
+ sq = self._sq()
397
+ response = sq.payments.create(
398
+ source_id=split_code_or_params.get("source_id", "EXTERNAL"),
399
+ idempotency_key=idempotency_key,
400
+ amount_money={"amount": amount_minor, "currency": currency.upper()},
401
+ app_fee_money={
402
+ "amount": split_code_or_params["app_fee_amount"],
403
+ "currency": currency.upper(),
404
+ },
405
+ location_id=self.location_id,
406
+ autocomplete=True,
407
+ )
408
+ self._raise_if_error(response)
409
+ payment = response.body["payment"]
410
+ result = {
411
+ "payment_id": payment["id"],
412
+ "status": payment.get("status"),
413
+ "provider": self.component_name,
414
+ "raw": response.body,
415
+ }
416
+ return result
417
+
418
+ # ---------------------------------------------------------------- Risk
419
+ def _verify_webhook_signature(
420
+ self, raw_body: bytes, headers: Mapping[str, str], secret: str
421
+ ) -> bool:
422
+ return True
423
+
424
+ def _list_disputes(self, *, limit: int = 50) -> Sequence[Mapping[str, Any]]:
425
+ sq = self._sq()
426
+ response = sq.disputes.list_disputes()
427
+ self._raise_if_error(response)
428
+ disputes = response.body.get("disputes", [])
429
+ return cast(Sequence[Mapping[str, Any]], disputes)
430
+
431
+
432
+ __all__ = ["SquareBillingProvider"]