@sylix/coworker 2.0.11 → 2.0.12

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.
Files changed (169) hide show
  1. package/dist/commands/slash/config.d.ts.map +1 -1
  2. package/dist/commands/slash/config.js +22 -4
  3. package/dist/commands/slash/config.js.map +1 -1
  4. package/dist/core/CoWorkerAgent.d.ts.map +1 -1
  5. package/dist/core/CoWorkerAgent.js +6 -3
  6. package/dist/core/CoWorkerAgent.js.map +1 -1
  7. package/dist/skills/defaults/accessibility/screen-reader-testing.md +545 -0
  8. package/dist/skills/defaults/accessibility/wcag-audit-patterns.md +555 -0
  9. package/dist/skills/defaults/ai-ml/rag.md +276 -0
  10. package/dist/skills/defaults/backend-development/api-design-principles.md +528 -0
  11. package/dist/skills/defaults/backend-development/api-design.md +285 -0
  12. package/dist/skills/defaults/backend-development/architecture-patterns.md +494 -0
  13. package/dist/skills/defaults/backend-development/async-python.md +237 -0
  14. package/dist/skills/defaults/backend-development/auth-implementation-patterns.md +638 -0
  15. package/dist/skills/defaults/backend-development/bazel-build-optimization.md +387 -0
  16. package/dist/skills/defaults/backend-development/billing-automation/SKILL.md +566 -0
  17. package/dist/skills/defaults/backend-development/code-review-excellence.md +538 -0
  18. package/dist/skills/defaults/backend-development/cqrs-implementation.md +554 -0
  19. package/dist/skills/defaults/backend-development/database-design.md +305 -0
  20. package/dist/skills/defaults/backend-development/debugging-strategies.md +536 -0
  21. package/dist/skills/defaults/backend-development/e2e-testing-patterns.md +544 -0
  22. package/dist/skills/defaults/backend-development/error-handling-patterns.md +641 -0
  23. package/dist/skills/defaults/backend-development/fastapi-templates.md +559 -0
  24. package/dist/skills/defaults/backend-development/fastapi.md +309 -0
  25. package/dist/skills/defaults/backend-development/git-advanced-workflows.md +405 -0
  26. package/dist/skills/defaults/backend-development/microservices-patterns.md +595 -0
  27. package/dist/skills/defaults/backend-development/microservices.md +284 -0
  28. package/dist/skills/defaults/backend-development/monorepo-management.md +623 -0
  29. package/dist/skills/defaults/backend-development/nodejs-backend-patterns.md +1048 -0
  30. package/dist/skills/defaults/backend-development/nx-workspace-patterns.md +457 -0
  31. package/dist/skills/defaults/backend-development/paypal-integration/SKILL.md +478 -0
  32. package/dist/skills/defaults/backend-development/pci-compliance/SKILL.md +480 -0
  33. package/dist/skills/defaults/backend-development/python-anti-patterns.md +349 -0
  34. package/dist/skills/defaults/backend-development/python-background-jobs.md +364 -0
  35. package/dist/skills/defaults/backend-development/python-code-style.md +360 -0
  36. package/dist/skills/defaults/backend-development/python-configuration.md +368 -0
  37. package/dist/skills/defaults/backend-development/python-design-patterns.md +296 -0
  38. package/dist/skills/defaults/backend-development/python-error-handling.md +323 -0
  39. package/dist/skills/defaults/backend-development/python-packaging.md +887 -0
  40. package/dist/skills/defaults/backend-development/python-performance-optimization.md +874 -0
  41. package/dist/skills/defaults/backend-development/python-project-structure.md +252 -0
  42. package/dist/skills/defaults/backend-development/python-resilience.md +376 -0
  43. package/dist/skills/defaults/backend-development/python-resource-management.md +421 -0
  44. package/dist/skills/defaults/backend-development/python-type-safety.md +428 -0
  45. package/dist/skills/defaults/backend-development/sql-optimization-patterns.md +509 -0
  46. package/dist/skills/defaults/backend-development/stripe-integration/SKILL.md +522 -0
  47. package/dist/skills/defaults/backend-development/turborepo-caching.md +376 -0
  48. package/dist/skills/defaults/blockchain/defi-protocol-templates.md +430 -0
  49. package/dist/skills/defaults/blockchain/nft-standards.md +364 -0
  50. package/dist/skills/defaults/blockchain/solidity-security.md +514 -0
  51. package/dist/skills/defaults/blockchain/web3-testing.md +360 -0
  52. package/dist/skills/defaults/business/competitive-landscape/SKILL.md +527 -0
  53. package/dist/skills/defaults/business/market-sizing-analysis/SKILL.md +451 -0
  54. package/dist/skills/defaults/business/startup-financial-modeling/SKILL.md +494 -0
  55. package/dist/skills/defaults/business/startup-metrics-framework/SKILL.md +564 -0
  56. package/dist/skills/defaults/business/team-composition-analysis.md +437 -0
  57. package/dist/skills/defaults/compliance/employment-contract-templates/SKILL.md +527 -0
  58. package/dist/skills/defaults/compliance/gdpr-data-handling/SKILL.md +630 -0
  59. package/dist/skills/defaults/data-engineering/airflow-dag-patterns.md +436 -0
  60. package/dist/skills/defaults/data-engineering/airflow.md +519 -0
  61. package/dist/skills/defaults/data-engineering/data-quality.md +583 -0
  62. package/dist/skills/defaults/data-engineering/dbt-transformation-patterns.md +482 -0
  63. package/dist/skills/defaults/data-engineering/dbt.md +556 -0
  64. package/dist/skills/defaults/data-engineering/ml-pipeline-workflow/SKILL.md +247 -0
  65. package/dist/skills/defaults/data-engineering/spark-optimization.md +348 -0
  66. package/dist/skills/defaults/data-engineering/spark.md +411 -0
  67. package/dist/skills/defaults/database/postgresql.md +202 -0
  68. package/dist/skills/defaults/debugging/systematic-debugging.md +249 -0
  69. package/dist/skills/defaults/devops/architecture-decision-records.md +448 -0
  70. package/dist/skills/defaults/devops/changelog-automation.md +580 -0
  71. package/dist/skills/defaults/devops/cicd.md +314 -0
  72. package/dist/skills/defaults/devops/cloud.md +263 -0
  73. package/dist/skills/defaults/devops/code-review-excellence.md +299 -0
  74. package/dist/skills/defaults/devops/cost-optimization.md +295 -0
  75. package/dist/skills/defaults/devops/deployment-pipeline-design.md +356 -0
  76. package/dist/skills/defaults/devops/docker.md +281 -0
  77. package/dist/skills/defaults/devops/git-workflows.md +205 -0
  78. package/dist/skills/defaults/devops/github-actions.md +311 -0
  79. package/dist/skills/defaults/devops/gitlab-ci-patterns.md +266 -0
  80. package/dist/skills/defaults/devops/hybrid-cloud-networking.md +241 -0
  81. package/dist/skills/defaults/devops/istio-traffic-management.md +327 -0
  82. package/dist/skills/defaults/devops/kubernetes.md +339 -0
  83. package/dist/skills/defaults/devops/linkerd-patterns.md +311 -0
  84. package/dist/skills/defaults/devops/multi-cloud-architecture.md +181 -0
  85. package/dist/skills/defaults/devops/observability.md +243 -0
  86. package/dist/skills/defaults/devops/openapi-spec-generation.md +1024 -0
  87. package/dist/skills/defaults/devops/postmortem-writing.md +396 -0
  88. package/dist/skills/defaults/devops/prometheus-configuration.md +265 -0
  89. package/dist/skills/defaults/devops/secrets-management.md +341 -0
  90. package/dist/skills/defaults/devops/service-mesh-observability.md +385 -0
  91. package/dist/skills/defaults/devops/terraform-module-library.md +244 -0
  92. package/dist/skills/defaults/finance/backtesting-frameworks/SKILL.md +663 -0
  93. package/dist/skills/defaults/finance/risk-metrics-calculation/SKILL.md +557 -0
  94. package/dist/skills/defaults/frontend/accessibility-compliance.md +420 -0
  95. package/dist/skills/defaults/frontend/design-system-patterns.md +337 -0
  96. package/dist/skills/defaults/frontend/interaction-design.md +327 -0
  97. package/dist/skills/defaults/frontend/javascript.md +311 -0
  98. package/dist/skills/defaults/frontend/modern-javascript-patterns.md +927 -0
  99. package/dist/skills/defaults/frontend/react-native-design.md +440 -0
  100. package/dist/skills/defaults/frontend/react.md +345 -0
  101. package/dist/skills/defaults/frontend/responsive-design.md +472 -0
  102. package/dist/skills/defaults/frontend/tailwind-design-system.md +337 -0
  103. package/dist/skills/defaults/frontend/typescript-advanced-types.md +724 -0
  104. package/dist/skills/defaults/frontend/typescript.md +334 -0
  105. package/dist/skills/defaults/frontend/visual-design-foundations.md +326 -0
  106. package/dist/skills/defaults/frontend/web-component-design.md +279 -0
  107. package/dist/skills/defaults/game-development/godot-gdscript-patterns.md +188 -0
  108. package/dist/skills/defaults/game-development/unity-ecs-patterns.md +594 -0
  109. package/dist/skills/defaults/kubernetes/gitops-workflow.md +285 -0
  110. package/dist/skills/defaults/kubernetes/gitops.md +280 -0
  111. package/dist/skills/defaults/kubernetes/helm-chart-scaffolding.md +553 -0
  112. package/dist/skills/defaults/kubernetes/helm.md +343 -0
  113. package/dist/skills/defaults/kubernetes/k8s-manifest-generator.md +501 -0
  114. package/dist/skills/defaults/kubernetes/k8s-security-policies.md +342 -0
  115. package/dist/skills/defaults/kubernetes/manifests.md +330 -0
  116. package/dist/skills/defaults/kubernetes/security.md +337 -0
  117. package/dist/skills/defaults/llm-application/embedding-strategies.md +608 -0
  118. package/dist/skills/defaults/llm-application/hybrid-search-implementation.md +570 -0
  119. package/dist/skills/defaults/llm-application/hybrid-search.md +570 -0
  120. package/dist/skills/defaults/llm-application/langchain-architecture.md +666 -0
  121. package/dist/skills/defaults/llm-application/langchain.md +259 -0
  122. package/dist/skills/defaults/llm-application/llm-evaluation.md +695 -0
  123. package/dist/skills/defaults/llm-application/prompt-engineering-patterns.md +449 -0
  124. package/dist/skills/defaults/llm-application/prompt-engineering.md +219 -0
  125. package/dist/skills/defaults/llm-application/rag-implementation.md +434 -0
  126. package/dist/skills/defaults/llm-application/similarity-search-patterns.md +560 -0
  127. package/dist/skills/defaults/llm-application/similarity-search.md +560 -0
  128. package/dist/skills/defaults/llm-application/vector-index-tuning.md +523 -0
  129. package/dist/skills/defaults/mobile/mobile-android-design.md +440 -0
  130. package/dist/skills/defaults/mobile/mobile-ios-design.md +266 -0
  131. package/dist/skills/defaults/monitoring/distributed-tracing.md +436 -0
  132. package/dist/skills/defaults/monitoring/grafana-dashboards.md +370 -0
  133. package/dist/skills/defaults/monitoring/prometheus-configuration.md +379 -0
  134. package/dist/skills/defaults/monitoring/slo-implementation.md +323 -0
  135. package/dist/skills/defaults/refactoring/code-refactoring.md +349 -0
  136. package/dist/skills/defaults/security/anti-reversing-techniques/SKILL.md +559 -0
  137. package/dist/skills/defaults/security/auditor.md +168 -0
  138. package/dist/skills/defaults/security/binary-analysis-patterns/SKILL.md +438 -0
  139. package/dist/skills/defaults/security/memory-forensics/SKILL.md +483 -0
  140. package/dist/skills/defaults/security/mtls-configuration.md +349 -0
  141. package/dist/skills/defaults/security/protocol-reverse-engineering/SKILL.md +520 -0
  142. package/dist/skills/defaults/security/sast-configuration.md +182 -0
  143. package/dist/skills/defaults/security/security.md +313 -0
  144. package/dist/skills/defaults/security/stride-analysis.md +273 -0
  145. package/dist/skills/defaults/security/threat-mitigation-mapping.md +290 -0
  146. package/dist/skills/defaults/systems/bash-defensive-patterns/SKILL.md +539 -0
  147. package/dist/skills/defaults/systems/bats-testing-patterns/SKILL.md +631 -0
  148. package/dist/skills/defaults/systems/go-concurrency-patterns.md +657 -0
  149. package/dist/skills/defaults/systems/memory-safety-patterns.md +605 -0
  150. package/dist/skills/defaults/systems/rust-async-patterns.md +519 -0
  151. package/dist/skills/defaults/systems/shellcheck-configuration/SKILL.md +456 -0
  152. package/dist/skills/defaults/team-collaboration/multi-reviewer-patterns.md +126 -0
  153. package/dist/skills/defaults/team-collaboration/parallel-feature-development.md +151 -0
  154. package/dist/skills/defaults/testing/javascript-testing-patterns.md +1021 -0
  155. package/dist/skills/defaults/testing/python-testing-patterns.md +351 -0
  156. package/dist/skills/defaults/testing/testing.md +332 -0
  157. package/dist/skills/defaults/workflows/context-driven-development.md +384 -0
  158. package/dist/skills/defaults/workflows/track-management.md +592 -0
  159. package/dist/skills/defaults/workflows/workflow-patterns.md +622 -0
  160. package/dist/skills/index.d.ts +11 -0
  161. package/dist/skills/index.d.ts.map +1 -0
  162. package/dist/skills/index.js +129 -0
  163. package/dist/skills/index.js.map +1 -0
  164. package/dist/utils/character.js +4 -4
  165. package/dist/utils/character.js.map +1 -1
  166. package/dist/utils/inputbar.d.ts.map +1 -1
  167. package/dist/utils/inputbar.js +7 -0
  168. package/dist/utils/inputbar.js.map +1 -1
  169. package/package.json +1 -1
@@ -0,0 +1,522 @@
1
+ ---
2
+ name: stripe-integration
3
+ description: Implement Stripe payment processing for robust, PCI-compliant payment flows including checkout, subscriptions, and webhooks. Use when integrating Stripe payments, building subscription systems, or implementing secure checkout flows.
4
+ ---
5
+
6
+ # Stripe Integration
7
+
8
+ Master Stripe payment processing integration for robust, PCI-compliant payment flows including checkout, subscriptions, webhooks, and refunds.
9
+
10
+ ## When to Use This Skill
11
+
12
+ - Implementing payment processing in web/mobile applications
13
+ - Setting up subscription billing systems
14
+ - Handling one-time payments and recurring charges
15
+ - Processing refunds and disputes
16
+ - Managing customer payment methods
17
+ - Implementing SCA (Strong Customer Authentication) for European payments
18
+ - Building marketplace payment flows with Stripe Connect
19
+
20
+ ## Core Concepts
21
+
22
+ ### 1. Payment Flows
23
+
24
+ **Checkout Sessions**
25
+
26
+ - Recommended for most integrations
27
+ - Supports all UI paths:
28
+ - Stripe-hosted checkout page
29
+ - Embedded checkout form
30
+ - Custom UI with Elements (Payment Element, Express Checkout Element) using `ui_mode='custom'`
31
+ - Provides built-in checkout capabilities (line items, discounts, tax, shipping, address collection, saved payment methods, and checkout lifecycle events)
32
+ - Lower integration and maintenance burden than Payment Intents
33
+
34
+ **Payment Intents (Bespoke control)**
35
+
36
+ - You calculate the final amount with taxes, discounts, subscriptions, and currency conversion yourself.
37
+ - More complex implementation and long-term maintenance burden
38
+ - Requires Stripe.js for PCI compliance
39
+
40
+ **Setup Intents (Save Payment Methods)**
41
+
42
+ - Collect payment method without charging
43
+ - Used for subscriptions and future payments
44
+ - Requires customer confirmation
45
+
46
+ ### 2. Webhooks
47
+
48
+ **Critical Events:**
49
+
50
+ - `payment_intent.succeeded`: Payment completed
51
+ - `payment_intent.payment_failed`: Payment failed
52
+ - `customer.subscription.updated`: Subscription changed
53
+ - `customer.subscription.deleted`: Subscription canceled
54
+ - `charge.refunded`: Refund processed
55
+ - `invoice.payment_succeeded`: Subscription payment successful
56
+
57
+ ### 3. Subscriptions
58
+
59
+ **Components:**
60
+
61
+ - **Product**: What you're selling
62
+ - **Price**: How much and how often
63
+ - **Subscription**: Customer's recurring payment
64
+ - **Invoice**: Generated for each billing cycle
65
+
66
+ ### 4. Customer Management
67
+
68
+ - Create and manage customer records
69
+ - Store multiple payment methods
70
+ - Track customer metadata
71
+ - Manage billing details
72
+
73
+ ## Quick Start
74
+
75
+ ```python
76
+ import stripe
77
+
78
+ stripe.api_key = "sk_test_..."
79
+
80
+ # Create a checkout session
81
+ session = stripe.checkout.Session.create(
82
+ line_items=[{
83
+ 'price_data': {
84
+ 'currency': 'usd',
85
+ 'product_data': {
86
+ 'name': 'Premium Subscription',
87
+ },
88
+ 'unit_amount': 2000, # $20.00
89
+ 'recurring': {
90
+ 'interval': 'month',
91
+ },
92
+ },
93
+ 'quantity': 1,
94
+ }],
95
+ mode='subscription',
96
+ success_url='https://yourdomain.com/success?session_id={CHECKOUT_SESSION_ID}',
97
+ cancel_url='https://yourdomain.com/cancel'
98
+ )
99
+
100
+ # Redirect user to session.url
101
+ print(session.url)
102
+ ```
103
+
104
+ ## Payment Implementation Patterns
105
+
106
+ ### Pattern 1: One-Time Payment (Hosted Checkout)
107
+
108
+ ```python
109
+ def create_checkout_session(amount, currency='usd'):
110
+ """Create a one-time payment checkout session."""
111
+ try:
112
+ session = stripe.checkout.Session.create(
113
+ line_items=[{
114
+ 'price_data': {
115
+ 'currency': currency,
116
+ 'product_data': {
117
+ 'name': 'Blue T-shirt',
118
+ 'images': ['https://example.com/product.jpg'],
119
+ },
120
+ 'unit_amount': amount, # Amount in cents
121
+ },
122
+ 'quantity': 1,
123
+ }],
124
+ mode='payment',
125
+ success_url='https://yourdomain.com/success?session_id={CHECKOUT_SESSION_ID}',
126
+ cancel_url='https://yourdomain.com/cancel',
127
+ metadata={
128
+ 'order_id': 'order_123',
129
+ 'user_id': 'user_456'
130
+ }
131
+ )
132
+ return session
133
+ except stripe.error.StripeError as e:
134
+ # Handle error
135
+ print(f"Stripe error: {e.user_message}")
136
+ raise
137
+ ```
138
+
139
+ ### Pattern 2: Elements with Checkout Sessions
140
+
141
+ ```python
142
+ def create_checkout_session_for_elements(amount, currency='usd'):
143
+ """Create a checkout session configured for Payment Element."""
144
+ session = stripe.checkout.Session.create(
145
+ mode='payment',
146
+ ui_mode='custom',
147
+ line_items=[{
148
+ 'price_data': {
149
+ 'currency': currency,
150
+ 'product_data': {'name': 'Blue T-shirt'},
151
+ 'unit_amount': amount,
152
+ },
153
+ 'quantity': 1,
154
+ }],
155
+ return_url='https://yourdomain.com/complete?session_id={CHECKOUT_SESSION_ID}'
156
+ )
157
+ return session.client_secret # Send to frontend
158
+ ```
159
+
160
+ ```javascript
161
+ const stripe = Stripe("pk_test_...");
162
+ const appearance = { theme: "stripe" };
163
+
164
+ const checkout = stripe.initCheckout({
165
+ clientSecret,
166
+ elementsOptions: { appearance },
167
+ });
168
+ const loadActionsResult = await checkout.loadActions();
169
+
170
+ if (loadActionsResult.type === "success") {
171
+ const { actions } = loadActionsResult;
172
+ const session = actions.getSession();
173
+
174
+ const button = document.getElementById("pay-button");
175
+ const checkoutContainer = document.getElementById("checkout-container");
176
+ const emailInput = document.getElementById("email");
177
+ const emailErrors = document.getElementById("email-errors");
178
+ const errors = document.getElementById("confirm-errors");
179
+
180
+ // Display a formatted string representing the total amount
181
+ checkoutContainer.append(`Total: ${session.total.total.amount}`);
182
+
183
+ // Mount Payment Element
184
+ const paymentElement = checkout.createPaymentElement();
185
+ paymentElement.mount("#payment-element");
186
+
187
+ // Store email for submission
188
+ emailInput.addEventListener("blur", () => {
189
+ actions.updateEmail(emailInput.value).then((result) => {
190
+ if (result.error) emailErrors.textContent = result.error.message;
191
+ });
192
+ });
193
+
194
+ // Handle form submission
195
+ button.addEventListener("click", () => {
196
+ actions.confirm().then((result) => {
197
+ if (result.type === "error") errors.textContent = result.error.message;
198
+ });
199
+ });
200
+ }
201
+ ```
202
+
203
+ ### Pattern 3: Elements with Payment Intents
204
+
205
+ Pattern 2 (Elements with Checkout Sessions) is Stripe's recommended approach, but you can also use Payment Intents as an alternative.
206
+
207
+ ```python
208
+ def create_payment_intent(amount, currency='usd', customer_id=None):
209
+ """Create a payment intent for bespoke checkout UI with Payment Element."""
210
+ intent = stripe.PaymentIntent.create(
211
+ amount=amount,
212
+ currency=currency,
213
+ customer=customer_id,
214
+ automatic_payment_methods={
215
+ 'enabled': True,
216
+ },
217
+ metadata={
218
+ 'integration_check': 'accept_a_payment'
219
+ }
220
+ )
221
+ return intent.client_secret # Send to frontend
222
+ ```
223
+
224
+ ```javascript
225
+ // Mount Payment Element and confirm via Payment Intents
226
+ const stripe = Stripe("pk_test_...");
227
+ const appearance = { theme: "stripe" };
228
+ const elements = stripe.elements({ appearance, clientSecret });
229
+
230
+ const paymentElement = elements.create("payment");
231
+ paymentElement.mount("#payment-element");
232
+
233
+ document.getElementById("pay-button").addEventListener("click", async () => {
234
+ const { error } = await stripe.confirmPayment({
235
+ elements,
236
+ confirmParams: {
237
+ return_url: "https://yourdomain.com/complete",
238
+ },
239
+ });
240
+
241
+ if (error) {
242
+ document.getElementById("errors").textContent = error.message;
243
+ }
244
+ });
245
+ ```
246
+
247
+ ### Pattern 4: Subscription Creation
248
+
249
+ ```python
250
+ def create_subscription(customer_id, price_id):
251
+ """Create a subscription for a customer."""
252
+ try:
253
+ subscription = stripe.Subscription.create(
254
+ customer=customer_id,
255
+ items=[{'price': price_id}],
256
+ payment_behavior='default_incomplete',
257
+ payment_settings={'save_default_payment_method': 'on_subscription'},
258
+ expand=['latest_invoice.payment_intent'],
259
+ )
260
+
261
+ return {
262
+ 'subscription_id': subscription.id,
263
+ 'client_secret': subscription.latest_invoice.payment_intent.client_secret
264
+ }
265
+ except stripe.error.StripeError as e:
266
+ print(f"Subscription creation failed: {e}")
267
+ raise
268
+ ```
269
+
270
+ ### Pattern 5: Customer Portal
271
+
272
+ ```python
273
+ def create_customer_portal_session(customer_id):
274
+ """Create a portal session for customers to manage subscriptions."""
275
+ session = stripe.billing_portal.Session.create(
276
+ customer=customer_id,
277
+ return_url='https://yourdomain.com/account',
278
+ )
279
+ return session.url # Redirect customer here
280
+ ```
281
+
282
+ ## Webhook Handling
283
+
284
+ ### Secure Webhook Endpoint
285
+
286
+ ```python
287
+ from flask import Flask, request
288
+ import stripe
289
+
290
+ app = Flask(__name__)
291
+
292
+ endpoint_secret = 'whsec_...'
293
+
294
+ @app.route('/webhook', methods=['POST'])
295
+ def webhook():
296
+ payload = request.data
297
+ sig_header = request.headers.get('Stripe-Signature')
298
+
299
+ try:
300
+ event = stripe.Webhook.construct_event(
301
+ payload, sig_header, endpoint_secret
302
+ )
303
+ except ValueError:
304
+ # Invalid payload
305
+ return 'Invalid payload', 400
306
+ except stripe.error.SignatureVerificationError:
307
+ # Invalid signature
308
+ return 'Invalid signature', 400
309
+
310
+ # Handle the event
311
+ if event['type'] == 'payment_intent.succeeded':
312
+ payment_intent = event['data']['object']
313
+ handle_successful_payment(payment_intent)
314
+ elif event['type'] == 'payment_intent.payment_failed':
315
+ payment_intent = event['data']['object']
316
+ handle_failed_payment(payment_intent)
317
+ elif event['type'] == 'customer.subscription.deleted':
318
+ subscription = event['data']['object']
319
+ handle_subscription_canceled(subscription)
320
+
321
+ return 'Success', 200
322
+
323
+ def handle_successful_payment(payment_intent):
324
+ """Process successful payment."""
325
+ customer_id = payment_intent.get('customer')
326
+ amount = payment_intent['amount']
327
+ metadata = payment_intent.get('metadata', {})
328
+
329
+ # Update your database
330
+ # Send confirmation email
331
+ # Fulfill order
332
+ print(f"Payment succeeded: {payment_intent['id']}")
333
+
334
+ def handle_failed_payment(payment_intent):
335
+ """Handle failed payment."""
336
+ error = payment_intent.get('last_payment_error', {})
337
+ print(f"Payment failed: {error.get('message')}")
338
+ # Notify customer
339
+ # Update order status
340
+
341
+ def handle_subscription_canceled(subscription):
342
+ """Handle subscription cancellation."""
343
+ customer_id = subscription['customer']
344
+ # Update user access
345
+ # Send cancellation email
346
+ print(f"Subscription canceled: {subscription['id']}")
347
+ ```
348
+
349
+ ### Webhook Best Practices
350
+
351
+ ```python
352
+ import hashlib
353
+ import hmac
354
+
355
+ def verify_webhook_signature(payload, signature, secret):
356
+ """Manually verify webhook signature."""
357
+ expected_sig = hmac.new(
358
+ secret.encode('utf-8'),
359
+ payload,
360
+ hashlib.sha256
361
+ ).hexdigest()
362
+
363
+ return hmac.compare_digest(signature, expected_sig)
364
+
365
+ def handle_webhook_idempotently(event_id, handler):
366
+ """Ensure webhook is processed exactly once."""
367
+ # Check if event already processed
368
+ if is_event_processed(event_id):
369
+ return
370
+
371
+ # Process event
372
+ try:
373
+ handler()
374
+ mark_event_processed(event_id)
375
+ except Exception as e:
376
+ log_error(e)
377
+ # Stripe will retry failed webhooks
378
+ raise
379
+ ```
380
+
381
+ ## Customer Management
382
+
383
+ ```python
384
+ def create_customer(email, name, payment_method_id=None):
385
+ """Create a Stripe customer."""
386
+ customer = stripe.Customer.create(
387
+ email=email,
388
+ name=name,
389
+ payment_method=payment_method_id,
390
+ invoice_settings={
391
+ 'default_payment_method': payment_method_id
392
+ } if payment_method_id else None,
393
+ metadata={
394
+ 'user_id': '12345'
395
+ }
396
+ )
397
+ return customer
398
+
399
+ def attach_payment_method(customer_id, payment_method_id):
400
+ """Attach a payment method to a customer."""
401
+ stripe.PaymentMethod.attach(
402
+ payment_method_id,
403
+ customer=customer_id
404
+ )
405
+
406
+ # Set as default
407
+ stripe.Customer.modify(
408
+ customer_id,
409
+ invoice_settings={
410
+ 'default_payment_method': payment_method_id
411
+ }
412
+ )
413
+
414
+ def list_customer_payment_methods(customer_id):
415
+ """List all payment methods for a customer."""
416
+ payment_methods = stripe.PaymentMethod.list(
417
+ customer=customer_id,
418
+ type='card'
419
+ )
420
+ return payment_methods.data
421
+ ```
422
+
423
+ ## Refund Handling
424
+
425
+ ```python
426
+ def create_refund(payment_intent_id, amount=None, reason=None):
427
+ """Create a refund."""
428
+ refund_params = {
429
+ 'payment_intent': payment_intent_id
430
+ }
431
+
432
+ if amount:
433
+ refund_params['amount'] = amount # Partial refund
434
+
435
+ if reason:
436
+ refund_params['reason'] = reason # 'duplicate', 'fraudulent', 'requested_by_customer'
437
+
438
+ refund = stripe.Refund.create(**refund_params)
439
+ return refund
440
+
441
+ def handle_dispute(charge_id, evidence):
442
+ """Update dispute with evidence."""
443
+ stripe.Dispute.modify(
444
+ charge_id,
445
+ evidence={
446
+ 'customer_name': evidence.get('customer_name'),
447
+ 'customer_email_address': evidence.get('customer_email'),
448
+ 'shipping_documentation': evidence.get('shipping_proof'),
449
+ 'customer_communication': evidence.get('communication'),
450
+ }
451
+ )
452
+ ```
453
+
454
+ ## Testing
455
+
456
+ ```python
457
+ # Use test mode keys
458
+ stripe.api_key = "sk_test_..."
459
+
460
+ # Test card numbers
461
+ TEST_CARDS = {
462
+ 'success': '4242424242424242',
463
+ 'declined': '4000000000000002',
464
+ '3d_secure': '4000002500003155',
465
+ 'insufficient_funds': '4000000000009995'
466
+ }
467
+
468
+ def test_payment_flow():
469
+ """Test complete payment flow."""
470
+ # Create test customer
471
+ customer = stripe.Customer.create(
472
+ email="test@example.com"
473
+ )
474
+
475
+ # Create payment intent
476
+ intent = stripe.PaymentIntent.create(
477
+ amount=1000,
478
+ automatic_payment_methods={
479
+ 'enabled': True
480
+ },
481
+ currency='usd',
482
+ customer=customer.id
483
+ )
484
+
485
+ # Confirm with test card
486
+ confirmed = stripe.PaymentIntent.confirm(
487
+ intent.id,
488
+ payment_method='pm_card_visa' # Test payment method
489
+ )
490
+
491
+ assert confirmed.status == 'succeeded'
492
+ ```
493
+
494
+ ## Resources
495
+
496
+ - **references/checkout-flows.md**: Detailed checkout implementation
497
+ - **references/webhook-handling.md**: Webhook security and processing
498
+ - **references/subscription-management.md**: Subscription lifecycle
499
+ - **references/customer-management.md**: Customer and payment method handling
500
+ - **references/invoice-generation.md**: Invoicing and billing
501
+ - **assets/stripe-client.py**: Production-ready Stripe client wrapper
502
+ - **assets/webhook-handler.py**: Complete webhook processor
503
+ - **assets/checkout-config.json**: Checkout configuration templates
504
+
505
+ ## Best Practices
506
+
507
+ 1. **Always Use Webhooks**: Don't rely solely on client-side confirmation
508
+ 2. **Idempotency**: Handle webhook events idempotently
509
+ 3. **Error Handling**: Gracefully handle all Stripe errors
510
+ 4. **Test Mode**: Thoroughly test with test keys before production
511
+ 5. **Metadata**: Use metadata to link Stripe objects to your database
512
+ 6. **Monitoring**: Track payment success rates and errors
513
+ 7. **PCI Compliance**: Never handle raw card data on your server
514
+ 8. **SCA Ready**: Implement 3D Secure for European payments
515
+
516
+ ## Common Pitfalls
517
+
518
+ - **Not Verifying Webhooks**: Always verify webhook signatures
519
+ - **Missing Webhook Events**: Handle all relevant webhook events
520
+ - **Hardcoded Amounts**: Use cents/smallest currency unit
521
+ - **No Retry Logic**: Implement retries for API calls
522
+ - **Ignoring Test Mode**: Test all edge cases with test cards