6.4 KiB
6.4 KiB
Billing and Payments
Overview
The Fotospiel platform supports multiple payment providers for package purchases: Stripe for one-time and subscription payments, and Paddle for orders and subscriptions. Billing is handled through a freemium model with endcustomer event packages and reseller subscriptions. All payments are processed via API integrations, with webhooks for asynchronous updates.
Stripe Integration
- One-time Payments: Use Stripe Checkout for endcustomer event packages. Create PaymentIntent via
StripeController@createPaymentIntent. - Subscriptions: Reseller subscriptions use Stripe Subscriptions API. Webhook handling in
StripeWebhookController@handleWebhookfor events likeinvoice.paid,customer.subscription.deleted. - Configuration: Keys in
config/services.phpunderstripe. Sandbox mode based onAPP_ENV. - Models:
PackagePurchaserecords all transactions withprovider_id(Stripe PI ID),status,metadata. - Frontend: PurchaseWizard.tsx handles client-side Stripe Elements for card input and confirmation.
- Webhook Matrix:
Event Purpose Internal handler payment_intent.succeededCompletes single-event package purchase StripeWebhookController@handlePaymentIntentSucceededpayment_intent.payment_failedLogs failure, triggers recovery emails handlePaymentIntentFailedinvoice.paidConfirms subscription renewal, extends package handleInvoicePaidinvoice.payment_failedFlags tenant for follow-up, sends alerts handleInvoicePaymentFailedcustomer.subscription.deletedFinalises cancellation/downgrade handleSubscriptionDeleted
Paddle Integration
- SDK: Migrated to Paddle Server SDK v1.0+ (
paypal/paypal-server-sdk). Uses Builder pattern for requests and Controllers for API calls. - Orders (One-time Payments): Endcustomer event packages via Orders API.
PaddleController@createOrderusesOrderRequestBuilderwithCheckoutPaymentIntent::CAPTURE, custom_id for metadata (tenant_id, package_id, type). Capture in@captureOrderusingOrdersController->captureOrder. DB creation inprocessPurchaseFromOrder. - Subscriptions (Recurring Payments): Reseller subscriptions via Orders API with StoredPaymentSource for recurring setup (no dedicated SubscriptionsController in SDK).
PaddleController@createSubscriptionusesOrderRequestBuilderwithStoredPaymentSource(payment_initiator: CUSTOMER, payment_type: RECURRING, usage: FIRST), custom_id including plan_id. Initial order capture sets up subscription; subsequent billing via Paddle dashboard or webhooks. DB records created on initial capture, with expires_at for annual billing. - Differences: One-time: Standard Order with payment_type ONE_TIME (default). Recurring: Order with StoredPaymentSource RECURRING to enable future charges without new approvals. plan_id stored in metadata for reference; no separate subscription ID from SDK.
- Client Setup: OAuth2 Client Credentials flow. Builder:
PaypalServerSdkClientBuilder::init()->clientCredentialsAuthCredentials(ClientCredentialsAuthCredentialsBuilder::init(client_id, secret))->environment(Environment::SANDBOX/PRODUCTION)->build(). - Webhooks:
PaddleWebhookController@verifyhandles events likePAYMENT.CAPTURE.COMPLETED(process initial/renewal purchase),BILLING.SUBSCRIPTION.CANCELLEDor equivalent order events (deactivate package). Simplified signature verification (TODO: ImplementVerifyWebhookSignature). - Webhook Matrix:
Event Purpose Internal handler PAYMENT.CAPTURE.COMPLETEDConfirms one-time order, activates tenant package handleCaptureBILLING.SUBSCRIPTION.ACTIVATED,BILLING.SUBSCRIPTION.UPDATEDSyncs reseller subscription status/expiry handleSubscriptionBILLING.SUBSCRIPTION.CANCELLED,BILLING.SUBSCRIPTION.EXPIREDMarks package inactive and downgrades tenant handleSubscriptionBILLING.SUBSCRIPTION.SUSPENDEDPauses package benefits pending review handleSubscription - Idempotency: Check
provider_idinPackagePurchasebefore creation. Transactions for DB safety. - Configuration: Keys in
config/services.phpunderpaypal. Sandbox mode viapaypal.sandbox. - Migration Notes: Replaced old Checkout SDK (
PaddleCheckoutSdk). Updated imports, requests (e.g., OrdersCreateRequest -> OrderRequestBuilder, Subscriptions -> StoredPaymentSource in Orders). Responses: UsegetStatusCode()andgetResult(). Tests mocked new structures. No breaking changes in auth or metadata handling; recurring flows now unified under Orders API.
Database Models
- PackagePurchase: Records purchases with
tenant_id,package_id,provider_id(Stripe PI/Paddle Order ID),price,type(endcustomer_event/reseller_subscription),status(completed/refunded),metadata(JSON with provider details). - TenantPackage: Active packages with
tenant_id,package_id,price,purchased_at,expires_at,activeflag. Updated on purchase/cancellation. - Constraints:
typeCHECK (endcustomer_event, reseller_subscription),priceNOT NULL.
Flows
- Purchase Initiation: User selects package in PurchaseWizard. For free: direct assignment. Paid: Redirect to provider (Stripe Checkout or Paddle approve link).
- Completion: Provider callback/webhook triggers capture/confirmation. Create
PackagePurchaseandTenantPackage. Update tenantsubscription_statusto 'active'. - Cancellation/Refund: Webhook updates status to 'cancelled', deactivates
TenantPackage. - Trial: First reseller subscription gets 14-day trial (
expires_at = now() + 14 days).
Error Handling
- Validation: Request validation for IDs, consent.
- API Errors: Catch exceptions, log, return 400/500 JSON.
- Idempotency: Prevent duplicate processing.
- Webhook: Verify signature, handle unhandled events with logging.
Testing
- Unit: Mock providers in
PurchaseTest.phpfor order creation, capture, webhooks. - Integration: Sandbox keys for end-to-end. Assertions on DB state, responses.
- Edge Cases: Failures, idempotency, trials, limits.
Security & Compliance
- GDPR: No PII in logs/metadata beyond necessary (tenant_id anonymous).
- Auth: Sanctum tokens for API, CSRF for web.
- Webhooks: IP whitelisting (Paddle IPs), signature verification.
- Retention: Purchases retained per Privacy policy; update on changes.