vibes-plug 1.0.0 → 2.11.0

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 (183) hide show
  1. package/.claude/rules/vibes-plug-core.md +32 -0
  2. package/.cursor/rules/vibes-plug-core.mdc +51 -0
  3. package/.cursorrules +42 -0
  4. package/AGENTS.md +96 -0
  5. package/BLUEPRINT.md +309 -125
  6. package/CHANGELOG.md +183 -1
  7. package/CLAUDE.md +70 -0
  8. package/LICENSE +1 -1
  9. package/README.md +641 -263
  10. package/index.js +19 -0
  11. package/package.json +61 -25
  12. package/plugin.json +24 -7
  13. package/scripts/generate_swarm_gif.py +295 -0
  14. package/scripts/install.js +201 -0
  15. package/skills/accessibility-testing-expert/SKILL.md +116 -0
  16. package/skills/ai-cost-token-optimizer/SKILL.md +82 -0
  17. package/skills/ai-evals-benchmark-expert/SKILL.md +188 -0
  18. package/skills/ai-llm-integration-expert/SKILL.md +147 -122
  19. package/skills/ai-media-generation-expert/SKILL.md +172 -0
  20. package/skills/ai-prompt-engineering-expert/SKILL.md +84 -0
  21. package/skills/angular-expert/SKILL.md +148 -0
  22. package/skills/api-design-expert/SKILL.md +316 -309
  23. package/skills/api-gateway-proxy-expert/SKILL.md +81 -0
  24. package/skills/app-analyzer-optimizer/SKILL.md +195 -188
  25. package/skills/apple-ecosystem-expert/SKILL.md +145 -0
  26. package/skills/{asisten_ramah → asisten-ramah}/SKILL.md +7 -1
  27. package/skills/astro-framework-expert/SKILL.md +200 -0
  28. package/skills/async-queue-temporal-expert/SKILL.md +240 -0
  29. package/skills/authentication-identity-expert/SKILL.md +279 -45
  30. package/skills/auto-doc-updater/SKILL.md +219 -203
  31. package/skills/autonomous-chaos-monkey/SKILL.md +63 -0
  32. package/skills/autonomous-red-teamer/SKILL.md +203 -0
  33. package/skills/autonomous-tdd-debugger/SKILL.md +71 -0
  34. package/skills/background-jobs-queue-expert/SKILL.md +235 -0
  35. package/skills/biome-linter-formatter-expert/SKILL.md +89 -0
  36. package/skills/blockchain-web3-expert/SKILL.md +115 -0
  37. package/skills/bootstrap-to-modern/SKILL.md +93 -86
  38. package/skills/brainstorming/SKILL.md +381 -353
  39. package/skills/browser-automation-expert/SKILL.md +222 -0
  40. package/skills/bun-runtime-expert/SKILL.md +7 -1
  41. package/skills/chatbot-messaging-expert/SKILL.md +114 -0
  42. package/skills/ci-cd-devops-architect/SKILL.md +81 -45
  43. package/skills/cloud-hosting-expert/SKILL.md +249 -243
  44. package/skills/coderabbit/SKILL.md +197 -191
  45. package/skills/compliance-gdpr-privacy-expert/SKILL.md +85 -0
  46. package/skills/cron-scheduler-expert/SKILL.md +304 -0
  47. package/skills/data-pipeline-etl-expert/SKILL.md +84 -0
  48. package/skills/data-telemetry-expert/SKILL.md +218 -212
  49. package/skills/data-visualization-expert/SKILL.md +154 -0
  50. package/skills/database-migration-versioning-expert/SKILL.md +90 -0
  51. package/skills/database-orm-expert/SKILL.md +303 -293
  52. package/skills/dependency-upgrade-migrator/SKILL.md +301 -0
  53. package/skills/design-system-architect/SKILL.md +278 -242
  54. package/skills/desktop-electron-expert/SKILL.md +128 -0
  55. package/skills/documentation-site-expert/SKILL.md +59 -0
  56. package/skills/doku-mcp-server/SKILL.md +257 -0
  57. package/skills/doku-payment-gateway/SKILL.md +233 -0
  58. package/skills/domain-driven-design-expert/SKILL.md +82 -0
  59. package/skills/e2e-testing-expert/SKILL.md +320 -314
  60. package/skills/ecommerce-expert/SKILL.md +87 -0
  61. package/skills/edge-serverless-db-expert/SKILL.md +99 -0
  62. package/skills/email-notification-expert/SKILL.md +368 -0
  63. package/skills/error-resilience-expert/SKILL.md +486 -0
  64. package/skills/event-driven-architect/SKILL.md +86 -80
  65. package/skills/feature-flag-analytics-expert/SKILL.md +66 -0
  66. package/skills/file-upload-media-expert/SKILL.md +437 -0
  67. package/skills/firebase-security-expert/SKILL.md +7 -1
  68. package/skills/form-validation-expert/SKILL.md +407 -0
  69. package/skills/fullstack-expert/SKILL.md +260 -201
  70. package/skills/fullstack-expert/references/api_design_guide.md +466 -466
  71. package/skills/fullstack-expert/references/multi_language_backend.md +528 -528
  72. package/skills/fullstack-expert/scripts/api_contract_validator.py +253 -253
  73. package/skills/fullstack-expert/scripts/architecture_analyzer.py +326 -326
  74. package/skills/gemini-agent-booster/SKILL.md +142 -104
  75. package/skills/geospatial-maps-expert/SKILL.md +80 -0
  76. package/skills/global-a11y-i18n-expert/SKILL.md +86 -80
  77. package/skills/glsl-shader-expert/SKILL.md +107 -0
  78. package/skills/go-programming-expert/SKILL.md +300 -294
  79. package/skills/graph-rag-knowledge-expert/SKILL.md +159 -0
  80. package/skills/graphql-apollo-expert/SKILL.md +114 -0
  81. package/skills/headless-cms-expert/SKILL.md +181 -0
  82. package/skills/hig/SKILL.md +193 -187
  83. package/skills/js-backend-expert/SKILL.md +218 -191
  84. package/skills/legacy-code-translator/SKILL.md +71 -0
  85. package/skills/local-slm-edge-ai-expert/SKILL.md +167 -0
  86. package/skills/logging-error-tracking-expert/SKILL.md +344 -0
  87. package/skills/mcp-client-orchestrator/SKILL.md +76 -0
  88. package/skills/mcp-server-architect/SKILL.md +226 -126
  89. package/skills/micro-frontend-architect/SKILL.md +112 -0
  90. package/skills/mobile-expo-expert/SKILL.md +191 -185
  91. package/skills/mobile-push-notification-expert/SKILL.md +71 -0
  92. package/skills/modern-css-native-expert/SKILL.md +189 -0
  93. package/skills/monday-design-aesthetic/SKILL.md +72 -66
  94. package/skills/monorepo-architect/SKILL.md +232 -226
  95. package/skills/mpa-orchestrator/SKILL.md +120 -101
  96. package/skills/multi-agent-orchestration/SKILL.md +173 -153
  97. package/skills/multiple-entry-points/SKILL.md +91 -55
  98. package/skills/mvc-expert/SKILL.md +237 -231
  99. package/skills/n8n-automation-expert/SKILL.md +89 -0
  100. package/skills/nextjs-app-router-expert/SKILL.md +148 -0
  101. package/skills/openapi-swagger-codegen-expert/SKILL.md +67 -0
  102. package/skills/payment-gateway-expert/SKILL.md +129 -45
  103. package/skills/pdf-document-generation-expert/SKILL.md +91 -0
  104. package/skills/performance-web-vitals/SKILL.md +337 -331
  105. package/skills/post-quantum-crypto-migrator/SKILL.md +57 -0
  106. package/skills/prd-architect/SKILL.md +206 -190
  107. package/skills/proactive-background-watcher/SKILL.md +68 -0
  108. package/skills/production-ready-hardener/PRODUCTION_READINESS_REPORT.md +67 -0
  109. package/skills/production-ready-hardener/SKILL.md +461 -468
  110. package/skills/production-ready-hardener/references/production_checklist.md +161 -161
  111. package/skills/production-ready-hardener/scripts/production_readiness_scanner.py +881 -875
  112. package/skills/project-context-mapper/SKILL.md +85 -0
  113. package/skills/pwa-offline-first-expert/SKILL.md +185 -0
  114. package/skills/python-programming-expert/SKILL.md +407 -270
  115. package/skills/rate-limit-abuse-prevention/SKILL.md +377 -0
  116. package/skills/realtime-collaboration-expert/SKILL.md +99 -45
  117. package/skills/rich-text-editor-expert/SKILL.md +177 -0
  118. package/skills/rust-programming-expert/SKILL.md +240 -234
  119. package/skills/saas-billing/SKILL.md +382 -376
  120. package/skills/saas-multi-tenant/SKILL.md +256 -236
  121. package/skills/saas-mvp-launcher/SKILL.md +30 -1
  122. package/skills/saas-transformer/SKILL.md +499 -445
  123. package/skills/saas-transformer/references/billing_integration_guide.md +401 -401
  124. package/skills/saas-transformer/references/feature_gating_patterns.md +137 -137
  125. package/skills/saas-transformer/references/saas_transformation_checklist.md +121 -121
  126. package/skills/saas-transformer/scripts/saas_transformation_scanner.py +39 -29
  127. package/skills/scalability-clean-code/SKILL.md +234 -228
  128. package/skills/search-engine-expert/SKILL.md +89 -0
  129. package/skills/secure-fuzz-testing/SKILL.md +7 -1
  130. package/skills/self-evolving-memory-graph/SKILL.md +91 -0
  131. package/skills/self-healing-cloud-orchestrator/SKILL.md +57 -0
  132. package/skills/senior-frontend/SKILL.md +85 -105
  133. package/skills/seo/SKILL.md +258 -224
  134. package/skills/session-context-loader/SKILL.md +83 -0
  135. package/skills/session-handoff-resume/SKILL.md +163 -157
  136. package/skills/{skill_baru → skill-baru}/SKILL.md +177 -146
  137. package/skills/solidjs-expert/SKILL.md +80 -0
  138. package/skills/spa-orchestrator/SKILL.md +306 -287
  139. package/skills/sse-websocket-streaming-expert/SKILL.md +93 -0
  140. package/skills/state-management-expert/SKILL.md +277 -271
  141. package/skills/supabase-migration/SKILL.md +47 -1
  142. package/skills/supabase-security-expert/SKILL.md +248 -242
  143. package/skills/svelte-sveltekit-expert/SKILL.md +91 -0
  144. package/skills/svg-animation-motion-expert/SKILL.md +115 -0
  145. package/skills/tailwind-expert/SKILL.md +139 -187
  146. package/skills/tanstack-query-expert/SKILL.md +204 -198
  147. package/skills/tauri-expert/SKILL.md +7 -1
  148. package/skills/token-saver/SKILL.md +118 -110
  149. package/skills/typescript-expert/SKILL.md +329 -278
  150. package/skills/ui-components-expert/SKILL.md +166 -63
  151. package/skills/ui-ux-pro-max/SKILL.md +221 -200
  152. package/skills/vector-db-rag-expert/SKILL.md +208 -0
  153. package/skills/vibe-code-gardener/SKILL.md +180 -172
  154. package/skills/visual-qa-vision-agent/SKILL.md +71 -0
  155. package/skills/voice-ai-realtime-agent/SKILL.md +202 -0
  156. package/skills/vue-frontend-expert/SKILL.md +132 -0
  157. package/skills/wasm-edge-computing-expert/SKILL.md +97 -0
  158. package/skills/web-3d-graphics-expert/SKILL.md +137 -0
  159. package/skills/web-game-engine-expert/SKILL.md +102 -0
  160. package/skills/web-scraper/SKILL.md +98 -146
  161. package/skills/website-design-cloner/SKILL.md +180 -0
  162. package/skills/webxr-ar-vr-expert/SKILL.md +123 -0
  163. package/skills/wordpress-headless-expert/SKILL.md +144 -0
  164. package/skills/zero-to-prod-orchestrator/SKILL.md +231 -180
  165. package/skills/zero-trust-secret-vault/SKILL.md +88 -0
  166. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -20
  167. package/CONTRIBUTING.md +0 -199
  168. package/SECURITY.md +0 -21
  169. package/banner.png +0 -0
  170. package/skills/senior-fullstack/SKILL.md +0 -167
  171. package/skills/senior-fullstack/references/architecture_patterns.md +0 -160
  172. package/skills/senior-fullstack/references/development_workflows.md +0 -222
  173. package/skills/senior-fullstack/references/tech_stack_guide.md +0 -190
  174. package/skills/senior-fullstack/scripts/code_quality_analyzer.py +0 -114
  175. package/skills/senior-fullstack/scripts/fullstack_scaffolder.py +0 -114
  176. package/skills/senior-fullstack/scripts/project_scaffolder.py +0 -114
  177. package/skills/seo-aeo-landing-page-writer/SKILL.md +0 -97
  178. package/skills/seo-geo/SKILL.md +0 -188
  179. package/skills/ui-ux-pro-max/scripts/__pycache__/core.cpython-310.pyc +0 -0
  180. package/skills/ui-ux-pro-max/scripts/__pycache__/core.cpython-312.pyc +0 -0
  181. package/skills/ui-ux-pro-max/scripts/__pycache__/design_system.cpython-310.pyc +0 -0
  182. package/skills/ui-ux-pro-max/scripts/__pycache__/design_system.cpython-312.pyc +0 -0
  183. package/skills/ui_ux_expert/SKILL.md +0 -114
@@ -1,377 +1,383 @@
1
- ---
2
- name: saas-billing
3
- description: "Implement and audit SaaS billing systems, subscription state machines, secure webhooks, and local database synchronization / Implementasi dan audit sistem billing SaaS, state machine langganan, webhook aman, dan sinkronisasi database lokal."
1
+ ---
2
+ name: saas-billing
3
+ description: "Implement and audit SaaS billing systems, subscription state machines, secure webhooks, and local database synchronization / Implementasi dan audit sistem billing SaaS, state machine langganan, webhook aman, dan sinkronisasi database lokal."
4
4
  author: "Roedy Rustam"
5
- ---
6
-
7
- # SaaS Billing Expert (2026 Edition)
8
-
9
- [English](#english) | [Bahasa Indonesia](#bahasa-indonesia)
10
-
11
- ---
12
-
13
- <a name="english"></a>
14
- ## English
15
-
16
- ### Description
17
- Expert guide for implementing and auditing SaaS billing systems. Covers subscription state machines, secure webhook handling, database synchronization, and the 2026 billing landscape including Stripe, **Polar.sh** (open-source, developer-first), **LemonSqueezy**, PayPal, and Midtrans (for Southeast Asia).
18
-
19
- ### Trigger Conditions
20
- - Integrating any payment gateway (Stripe, Polar.sh, LemonSqueezy, Midtrans, PayPal) into a SaaS application.
21
- - Using a Static-to-Dynamic QRIS alternative (with unique nominals and mutation webhooks) for local developers without PG accounts.
22
- - Implementing subscription state machines (active → past_due → canceled → reactivated).
23
- - Building secure webhook handlers with signature verification and idempotency.
24
- - Syncing external subscription status to a local database.
25
- - Implementing usage-based billing or metered API pricing.
26
- - Building the customer billing portal (manage subscription, download invoices).
27
- - Auditing an existing billing system for security gaps.
28
-
29
- ### 2026 Billing Provider Landscape
30
-
31
- | Provider | Best For | Open Source | Merchant of Record |
32
- |---|---|---|---|
33
- | **Stripe** | Enterprise, global, complex billing | ❌ | ❌ |
34
- | **Polar.sh** | Developer-first, open-source products | ✅ | ✅ (optional) |
35
- | **LemonSqueezy** | Indie hackers, simple pricing, global | ❌ | ✅ |
36
- | **Paddle** | B2B SaaS, EU VAT compliance | ❌ | ✅ |
37
- | **Midtrans** | Southeast Asia / Indonesia | ❌ | ❌ |
38
- | **PayPal** | Global, consumer trust | ❌ | ❌ |
39
-
40
- > **Merchant of Record (MoR)**: The provider handles tax compliance (VAT, GST), chargebacks, and legal liability — ideal for small teams without a finance department.
41
-
42
- ### Polar.sh — Developer-First Billing (2026 Rising Star)
43
- Polar.sh is the modern, open-source alternative to Gumroad/LemonSqueezy, purpose-built for developers and open-source projects:
44
- ```typescript
45
- import { Polar } from "@polar-sh/sdk";
46
-
47
- const polar = new Polar({ accessToken: process.env.POLAR_ACCESS_TOKEN });
48
-
49
- // Create a checkout session
50
- const checkout = await polar.checkouts.custom.create({
51
- productId: "prod_xxxx",
52
- successUrl: "https://myapp.com/success?checkout={CHECKOUT_ID}",
53
- customerEmail: user.email,
54
- metadata: { userId: user.id },
55
- });
56
-
57
- // Redirect to checkout
58
- return redirect(checkout.url);
59
- ```
60
-
61
- ```typescript
62
- // Webhook handler (Next.js App Router)
63
- import { validateEvent, WebhookVerificationError } from "@polar-sh/sdk/webhooks";
64
-
65
- export async function POST(req: Request) {
66
- const body = await req.text();
67
- const signature = req.headers.get("webhook-signature") ?? "";
68
-
69
- try {
70
- const event = validateEvent(body, req.headers, process.env.POLAR_WEBHOOK_SECRET!);
71
-
72
- switch (event.type) {
73
- case "subscription.created":
74
- case "subscription.updated":
75
- await syncSubscription(event.data);
76
- break;
77
- case "subscription.canceled":
78
- await cancelSubscription(event.data.id);
79
- break;
80
- }
81
- return new Response(null, { status: 200 });
82
- } catch (e) {
83
- if (e instanceof WebhookVerificationError) {
84
- return new Response("Invalid signature", { status: 403 });
85
- }
86
- throw e;
87
- }
88
- }
89
- ```
90
-
91
- ### Stripe — Production Patterns
92
-
93
- #### Subscription State Machine
94
- ```
95
- FREE ──subscribe──> TRIALING ──trial_ends──> ACTIVE
96
- │
97
- ┌───────────────┤
98
- │ │
99
- payment fails cancel
100
- │ │
101
- PAST_DUE CANCELED
102
- │
103
- 3 failed retries
104
- │
105
- CANCELED
106
- ```
107
-
108
- #### Idempotent Webhook Handler
109
- ```typescript
110
- // app/api/webhooks/stripe/route.ts
111
- import Stripe from 'stripe';
112
- import { db } from '@/lib/db';
113
-
114
- const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
115
-
116
- export async function POST(req: Request) {
117
- const body = await req.text();
118
- const sig = req.headers.get('stripe-signature')!;
119
-
120
- let event: Stripe.Event;
121
- try {
122
- event = stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET!);
123
- } catch {
124
- return new Response('Invalid signature', { status: 400 });
125
- }
126
-
127
- // Idempotency: skip already-processed events
128
- const processed = await db.webhookEvent.findUnique({ where: { stripeEventId: event.id } });
129
- if (processed) return new Response(null, { status: 200 });
130
-
131
- // Process event
132
- switch (event.type) {
133
- case 'customer.subscription.created':
134
- case 'customer.subscription.updated': {
135
- const sub = event.data.object as Stripe.Subscription;
136
- await db.subscription.upsert({
137
- where: { stripeSubId: sub.id },
138
- create: { stripeSubId: sub.id, status: sub.status, userId: sub.metadata.userId },
139
- update: { status: sub.status, currentPeriodEnd: new Date(sub.current_period_end * 1000) },
140
- });
141
- break;
142
- }
143
- case 'invoice.payment_failed': {
144
- const invoice = event.data.object as Stripe.Invoice;
145
- await sendDunningEmail(invoice.customer_email!);
146
- break;
147
- }
148
- }
149
-
150
- // Mark as processed
151
- await db.webhookEvent.create({ data: { stripeEventId: event.id } });
152
- return new Response(null, { status: 200 });
153
- }
154
- ```
155
-
156
- #### Usage-Based Billing (Metered)
157
- ```typescript
158
- // Report usage at end of billing period
159
- await stripe.subscriptionItems.createUsageRecord(subscriptionItemId, {
160
- quantity: apiCallsThisMonth,
161
- timestamp: Math.floor(Date.now() / 1000),
162
- action: 'set', // 'set' or 'increment'
163
- });
164
- ```
165
-
166
- ### PayPal — Checkout Integration
167
-
168
- PayPal remains a trusted global standard for one-off payments and subscriptions.
169
-
170
- #### Create Order (Server-Side)
171
- ```typescript
172
- // app/api/paypal/create-order/route.ts
173
- import { paypalClient } from '@/lib/paypal';
174
- import paypal from '@paypal/checkout-server-sdk';
175
-
176
- export async function POST() {
177
- const request = new paypal.orders.OrdersCreateRequest();
178
- request.prefer("return=representation");
179
- request.requestBody({
180
- intent: 'CAPTURE',
181
- purchase_units: [{ amount: { currency_code: 'USD', value: '29.99' } }]
182
- });
183
-
184
- const response = await paypalClient().execute(request);
185
- return Response.json({ id: response.result.id });
186
- }
187
- ```
188
-
189
- #### Capture Payment (Server-Side)
190
- ```typescript
191
- // app/api/paypal/capture-order/route.ts
192
- import { db } from '@/lib/db';
193
- import { paypalClient } from '@/lib/paypal';
194
- import paypal from '@paypal/checkout-server-sdk';
195
-
196
- export async function POST(req: Request) {
197
- const { orderID, userId } = await req.json();
198
- const request = new paypal.orders.OrdersCaptureRequest(orderID);
199
- request.requestBody({});
200
-
201
- const response = await paypalClient().execute(request);
202
- if (response.result.status === 'COMPLETED') {
203
- // Grant access or update subscription in DB
204
- await db.subscription.create({
205
- data: { userId, provider: 'paypal', status: 'active' }
206
- });
207
- return Response.json({ success: true });
208
- }
209
- return Response.json({ success: false }, { status: 400 });
210
- }
211
- ```
212
-
213
- ### QRIS Static-to-Dynamic (Indonesia Alternative)
214
-
215
- For Indonesian developers without an official Payment Gateway account, you can create a "Dynamic" QRIS experience using a single Static QRIS combined with unique payment amounts and a bank mutation checking service (e.g., Moota, Cekmutasi) via webhook.
216
-
217
- #### 1. Generate Unique Amount (Server-Side)
218
- ```typescript
219
- // Add a unique 3-digit code to the base price
220
- export async function createQrisTransaction(userId: string, basePrice: number) {
221
- // Generate a random code between 1 and 999
222
- const uniqueCode = Math.floor(Math.random() * 999) + 1;
223
- const totalAmount = basePrice + uniqueCode;
224
-
225
- const transaction = await db.transaction.create({
226
- data: {
227
- userId, basePrice, uniqueCode, totalAmount,
228
- status: 'pending', provider: 'qris_static',
229
- expiresAt: new Date(Date.now() + 15 * 60 * 1000) // 15 mins expiry
230
- }
231
- });
232
-
233
- return {
234
- transactionId: transaction.id,
235
- totalAmount,
236
- qrisUrl: "https://myapp.com/static-qris.png" // User must manually input totalAmount
237
- };
238
- }
239
- ```
240
-
241
- #### 2. Mutation Webhook Handler & Real-Time Notification
242
- ```typescript
243
- // app/api/webhooks/mutation/route.ts
244
- import { db } from '@/lib/db';
245
- import { pusherServer } from '@/lib/pusher';
246
-
247
- export async function POST(req: Request) {
248
- const signature = req.headers.get("signature");
249
- // TODO: Verify signature from mutation service (e.g., Moota)
250
-
251
- const mutations = await req.json();
252
-
253
- for (const mutation of mutations) {
254
- if (mutation.type === 'CR' && mutation.amount > 0) {
255
- // Find pending transaction matching the exact unique amount
256
- const tx = await db.transaction.findFirst({
257
- where: {
258
- totalAmount: mutation.amount,
259
- status: 'pending',
260
- provider: 'qris_static',
261
- expiresAt: { gt: new Date() }
262
- }
263
- });
264
-
265
- if (tx) {
266
- // Mark as paid and activate subscription
267
- await db.transaction.update({ where: { id: tx.id }, data: { status: 'paid' } });
268
- await db.subscription.create({
269
- data: { userId: tx.userId, provider: 'qris_static', status: 'active' }
270
- });
271
-
272
- // Trigger real-time notification to frontend
273
- await pusherServer.trigger(`payment-${tx.id}`, 'payment-success', { success: true });
274
- }
275
- }
276
- }
277
-
278
- return new Response("OK", { status: 200 });
279
- }
280
- ```
281
-
282
- ### Database Schema for Multi-Provider Billing
283
- ```typescript
284
- // Drizzle ORM — supports Stripe, Polar, LemonSqueezy, PayPal, QRIS Static
285
- export const subscriptions = pgTable('subscriptions', {
286
- id: text('id').primaryKey(),
287
- workspaceId: text('workspace_id').references(() => workspaces.id).notNull(),
288
- provider: text('provider').$type<'stripe' | 'polar' | 'lemonsqueezy' | 'paypal' | 'qris_static'>().notNull(),
289
- externalCustomerId: text('external_customer_id').notNull(),
290
- externalSubId: text('external_sub_id').notNull().unique(),
291
- status: text('status').$type<'active' | 'trialing' | 'past_due' | 'canceled' | 'paused'>().notNull(),
292
- plan: text('plan').$type<'free' | 'pro' | 'enterprise'>().default('free').notNull(),
293
- currentPeriodEnd: timestamp('current_period_end'),
294
- cancelAtPeriodEnd: boolean('cancel_at_period_end').default(false),
295
- createdAt: timestamp('created_at').defaultNow().notNull(),
296
- updatedAt: timestamp('updated_at').defaultNow().notNull(),
297
- });
298
- ```
299
-
300
- ### Billing Security Checklist
301
- - [ ] Webhook signature verified on every request — reject without valid signature.
302
- - [ ] Webhook idempotency implemented — never process the same event twice.
303
- - [ ] Session Management Optimization: Secure the billing portal route with strict session validation and CSRF protection. Do not cache session-dependent billing states.
304
- - [ ] Use Stripe CLI / Polar.sh test webhooks for local development.
305
- - [ ] All billing API calls use server-side code only — never expose secret keys to frontend.
306
- - [ ] Plan limits enforced on every protected route (not just at checkout).
307
- - [ ] Failed payment dunning flow configured (email sequence, grace period).
308
- - [ ] Customer portal link available from within the app.
309
-
310
- ---
311
-
312
- <a name="bahasa-indonesia"></a>
313
- ## Bahasa Indonesia
314
-
315
- ### Deskripsi
316
- Panduan ahli untuk mengimplementasikan dan mengaudit sistem billing SaaS. Mencakup state machine langganan, penanganan webhook aman, sinkronisasi database, dan lanskap billing 2026 termasuk Stripe, **Polar.sh** (open-source, developer-first), **LemonSqueezy**, PayPal, dan Midtrans (untuk Asia Tenggara).
317
-
318
- ### Kondisi Pemicu
319
- - Mengintegrasikan payment gateway (Stripe, Polar.sh, LemonSqueezy, Midtrans, PayPal) ke aplikasi SaaS.
320
- - Menggunakan alternatif QRIS Statis menjadi Dinamis (dengan nominal unik dan webhook mutasi) untuk developer lokal tanpa akun PG.
321
- - Mengimplementasikan state machine langganan.
322
- - Membangun webhook handler aman dengan verifikasi tanda tangan dan idempotency.
323
- - Menyinkronkan status langganan eksternal ke database lokal.
324
- - Mengimplementasikan billing berbasis penggunaan (metered pricing).
325
- - Membangun portal billing pelanggan.
326
- - Mengaudit sistem billing yang ada untuk celah keamanan.
327
-
328
- ### Lanskap Provider Billing 2026
329
-
330
- | Provider | Terbaik Untuk | Open Source | Merchant of Record |
331
- |---|---|---|---|
332
- | **Stripe** | Enterprise, global, billing kompleks | ❌ | ❌ |
333
- | **Polar.sh** | Developer-first, produk open-source | ✅ | ✅ (opsional) |
334
- | **LemonSqueezy** | Indie hackers, harga sederhana | ❌ | ✅ |
335
- | **Paddle** | B2B SaaS, kepatuhan PPN EU | ❌ | ✅ |
336
- | **Midtrans** | Asia Tenggara / Indonesia | ❌ | ❌ |
337
- | **PayPal** | Global, kepercayaan konsumen (consumer trust) | ❌ | ❌ |
338
-
339
- > **Merchant of Record (MoR)**: Provider menangani kepatuhan pajak (PPN, GST), chargeback, dan tanggung jawab hukum — ideal untuk tim kecil tanpa departemen keuangan.
340
-
341
- ### Polar.sh — Billing Developer-First
342
- Polar.sh adalah alternatif open-source modern untuk Gumroad/LemonSqueezy, dirancang khusus untuk developer dan proyek open-source. Mendukung checkout, webhook, dan manajemen langganan dengan SDK TypeScript yang bersih.
343
-
344
- ### PayPal — Integrasi Checkout
345
- PayPal sering digunakan sebagai gateway alternatif atau utama karena tingginya kepercayaan konsumen global.
346
- - **Server-Side Checkout**: Gunakan `create-order` dan `capture-order` di backend (menggunakan `@paypal/checkout-server-sdk`) untuk memastikan keamanan dan mencegah manipulasi harga di sisi klien.
347
- - **Webhook**: Verifikasi webhook dari PayPal untuk langganan yang diperbarui atau dibatalkan.
348
-
349
- ### Stripe — Pola Produksi
350
-
351
- #### State Machine Langganan
352
- Kelola transisi status: `FREE → TRIALING → ACTIVE → PAST_DUE → CANCELED → (reaktivasi)`.
353
-
354
- #### Webhook Handler Idempoten
355
- Selalu verifikasi tanda tangan webhook, tandai event sebagai diproses di database untuk mencegah duplikasi.
356
-
357
- #### Billing Berbasis Penggunaan (Metered)
358
- Laporkan penggunaan API dengan `stripe.subscriptionItems.createUsageRecord()` di akhir periode billing.
359
-
360
- ### Alternatif Lokal: QRIS Statis Rasa Dinamis (Tanpa Akun Payment Gateway)
361
- Bagi pengguna/developer di Indonesia yang belum memiliki Payment Gateway (seperti Midtrans), Anda dapat membuat pengalaman QRIS "Dinamis" menggunakan satu gambar QRIS statis biasa.
362
- - **Generate Nominal Unik (Endpoint)**: Tambahkan angka unik (misalnya 3 digit acak) ke harga dasar (contoh: Rp 100.000 menjadi Rp 100.123). Simpan ke database sebagai transaksi `pending` dengan batas waktu kadaluarsa (misal 15 menit). Tampilkan gambar QRIS beserta instruksi transfer sesuai nominal unik.
363
- - **Webhook Mutasi Bank**: Gunakan layanan pihak ketiga (seperti Moota, Cekmutasi) yang mengirimkan notifikasi webhook (ke `/api/webhooks/mutation`) setiap kali ada uang masuk.
364
- - **Validasi Otomatis**: Saat webhook menerima payload mutasi kredit (`CR`), sistem mencari transaksi `pending` yang jumlahnya sama persis (`totalAmount`). Jika cocok, sistem menandai tagihan sebagai lunas (`paid`) dan mengaktifkan langganan.
365
- - **Notifikasi Klien**: Gunakan WebSocket (seperti Pusher atau Socket.io) di backend untuk melakukan *trigger event* "pembayaran berhasil". Di frontend, *listen* ke event tersebut dan tampilkan notifikasi *real-time* kepada pengguna secara instan tanpa perlu me-refresh halaman.
366
-
367
- ### Skema Database Multi-Provider
368
- Rancang tabel `subscriptions` yang mendukung beberapa provider (`stripe`, `polar`, `lemonsqueezy`, `paypal`, `qris_static`) dengan kolom `provider` dan ID eksternal yang terpisah.
369
-
370
- ### Checklist Keamanan Billing
371
- - [ ] Tanda tangan webhook diverifikasi pada setiap permintaan.
372
- - [ ] Idempotency webhook diimplementasikan.
373
- - [ ] Optimasi Session Management: Amankan rute portal billing dengan validasi sesi yang ketat dan perlindungan CSRF. Jangan gunakan cache untuk state billing yang bergantung pada sesi pengguna.
374
- - [ ] Semua panggilan API billing menggunakan kode sisi server saja.
375
- - [ ] Batas plan diterapkan pada setiap rute yang dilindungi.
376
- - [ ] Alur dunning pembayaran gagal dikonfigurasi.
377
- - [ ] Tautan portal pelanggan tersedia dari dalam aplikasi.
5
+ ---
6
+
7
+ # SaaS Billing Expert (2026 Edition)
8
+
9
+ [English](#english) | [Bahasa Indonesia](#bahasa-indonesia)
10
+
11
+ ---
12
+
13
+ <a name="english"></a>
14
+ ## English
15
+
16
+ ### Orchestration & Integration
17
+ Connects and orchestrates with relevant domain skills like `brainstorming`, `zero-to-prod-orchestrator`, and `project-context-mapper` to ensure cohesive execution.
18
+
19
+ ### Description
20
+ Expert guide for implementing and auditing SaaS billing systems. Covers subscription state machines, secure webhook handling, database synchronization, and the 2026 billing landscape including Stripe, **Polar.sh** (open-source, developer-first), **LemonSqueezy**, PayPal, and Midtrans (for Southeast Asia).
21
+
22
+ ### Trigger Conditions
23
+ - Integrating any payment gateway (Stripe, Polar.sh, LemonSqueezy, Midtrans, PayPal) into a SaaS application.
24
+ - Using a Static-to-Dynamic QRIS alternative (with unique nominals and mutation webhooks) for local developers without PG accounts.
25
+ - Implementing subscription state machines (active → past_due → canceled → reactivated).
26
+ - Building secure webhook handlers with signature verification and idempotency.
27
+ - Syncing external subscription status to a local database.
28
+ - Implementing usage-based billing or metered API pricing.
29
+ - Building the customer billing portal (manage subscription, download invoices).
30
+ - Auditing an existing billing system for security gaps.
31
+
32
+ ### 2026 Billing Provider Landscape
33
+
34
+ | Provider | Best For | Open Source | Merchant of Record |
35
+ |---|---|---|---|
36
+ | **Stripe** | Enterprise, global, complex billing | ❌ | ❌ |
37
+ | **Polar.sh** | Developer-first, open-source products | ✅ | ✅ (optional) |
38
+ | **LemonSqueezy** | Indie hackers, simple pricing, global | ❌ | ✅ |
39
+ | **Paddle** | B2B SaaS, EU VAT compliance | ❌ | ✅ |
40
+ | **Midtrans** | Southeast Asia / Indonesia | ❌ | ❌ |
41
+ | **PayPal** | Global, consumer trust | ❌ | ❌ |
42
+
43
+ > **Merchant of Record (MoR)**: The provider handles tax compliance (VAT, GST), chargebacks, and legal liability — ideal for small teams without a finance department.
44
+
45
+ ### Polar.sh — Developer-First Billing (2026 Rising Star)
46
+ Polar.sh is the modern, open-source alternative to Gumroad/LemonSqueezy, purpose-built for developers and open-source projects:
47
+ ```typescript
48
+ import { Polar } from "@polar-sh/sdk";
49
+
50
+ const polar = new Polar({ accessToken: process.env.POLAR_ACCESS_TOKEN });
51
+
52
+ // Create a checkout session
53
+ const checkout = await polar.checkouts.custom.create({
54
+ productId: "prod_xxxx",
55
+ successUrl: "https://myapp.com/success?checkout={CHECKOUT_ID}",
56
+ customerEmail: user.email,
57
+ metadata: { userId: user.id },
58
+ });
59
+
60
+ // Redirect to checkout
61
+ return redirect(checkout.url);
62
+ ```
63
+
64
+ ```typescript
65
+ // Webhook handler (Next.js App Router)
66
+ import { validateEvent, WebhookVerificationError } from "@polar-sh/sdk/webhooks";
67
+
68
+ export async function POST(req: Request) {
69
+ const body = await req.text();
70
+ const signature = req.headers.get("webhook-signature") ?? "";
71
+
72
+ try {
73
+ const event = validateEvent(body, req.headers, process.env.POLAR_WEBHOOK_SECRET!);
74
+
75
+ switch (event.type) {
76
+ case "subscription.created":
77
+ case "subscription.updated":
78
+ await syncSubscription(event.data);
79
+ break;
80
+ case "subscription.canceled":
81
+ await cancelSubscription(event.data.id);
82
+ break;
83
+ }
84
+ return new Response(null, { status: 200 });
85
+ } catch (e) {
86
+ if (e instanceof WebhookVerificationError) {
87
+ return new Response("Invalid signature", { status: 403 });
88
+ }
89
+ throw e;
90
+ }
91
+ }
92
+ ```
93
+
94
+ ### Stripe — Production Patterns
95
+
96
+ #### Subscription State Machine
97
+ ```
98
+ FREE ──subscribe──> TRIALING ──trial_ends──> ACTIVE
99
+ │
100
+ ┌───────────────┤
101
+ │ │
102
+ payment fails cancel
103
+ │ │
104
+ PAST_DUE CANCELED
105
+ │
106
+ 3 failed retries
107
+ │
108
+ CANCELED
109
+ ```
110
+
111
+ #### Idempotent Webhook Handler
112
+ ```typescript
113
+ // app/api/webhooks/stripe/route.ts
114
+ import Stripe from 'stripe';
115
+ import { db } from '@/lib/db';
116
+
117
+ const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
118
+
119
+ export async function POST(req: Request) {
120
+ const body = await req.text();
121
+ const sig = req.headers.get('stripe-signature')!;
122
+
123
+ let event: Stripe.Event;
124
+ try {
125
+ event = stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET!);
126
+ } catch {
127
+ return new Response('Invalid signature', { status: 400 });
128
+ }
129
+
130
+ // Idempotency: skip already-processed events
131
+ const processed = await db.webhookEvent.findUnique({ where: { stripeEventId: event.id } });
132
+ if (processed) return new Response(null, { status: 200 });
133
+
134
+ // Process event
135
+ switch (event.type) {
136
+ case 'customer.subscription.created':
137
+ case 'customer.subscription.updated': {
138
+ const sub = event.data.object as Stripe.Subscription;
139
+ await db.subscription.upsert({
140
+ where: { stripeSubId: sub.id },
141
+ create: { stripeSubId: sub.id, status: sub.status, userId: sub.metadata.userId },
142
+ update: { status: sub.status, currentPeriodEnd: new Date(sub.current_period_end * 1000) },
143
+ });
144
+ break;
145
+ }
146
+ case 'invoice.payment_failed': {
147
+ const invoice = event.data.object as Stripe.Invoice;
148
+ await sendDunningEmail(invoice.customer_email!);
149
+ break;
150
+ }
151
+ }
152
+
153
+ // Mark as processed
154
+ await db.webhookEvent.create({ data: { stripeEventId: event.id } });
155
+ return new Response(null, { status: 200 });
156
+ }
157
+ ```
158
+
159
+ #### Usage-Based Billing (Metered)
160
+ ```typescript
161
+ // Report usage at end of billing period
162
+ await stripe.subscriptionItems.createUsageRecord(subscriptionItemId, {
163
+ quantity: apiCallsThisMonth,
164
+ timestamp: Math.floor(Date.now() / 1000),
165
+ action: 'set', // 'set' or 'increment'
166
+ });
167
+ ```
168
+
169
+ ### PayPal — Checkout Integration
170
+
171
+ PayPal remains a trusted global standard for one-off payments and subscriptions.
172
+
173
+ #### Create Order (Server-Side)
174
+ ```typescript
175
+ // app/api/paypal/create-order/route.ts
176
+ import { paypalClient } from '@/lib/paypal';
177
+ import paypal from '@paypal/checkout-server-sdk';
178
+
179
+ export async function POST() {
180
+ const request = new paypal.orders.OrdersCreateRequest();
181
+ request.prefer("return=representation");
182
+ request.requestBody({
183
+ intent: 'CAPTURE',
184
+ purchase_units: [{ amount: { currency_code: 'USD', value: '29.99' } }]
185
+ });
186
+
187
+ const response = await paypalClient().execute(request);
188
+ return Response.json({ id: response.result.id });
189
+ }
190
+ ```
191
+
192
+ #### Capture Payment (Server-Side)
193
+ ```typescript
194
+ // app/api/paypal/capture-order/route.ts
195
+ import { db } from '@/lib/db';
196
+ import { paypalClient } from '@/lib/paypal';
197
+ import paypal from '@paypal/checkout-server-sdk';
198
+
199
+ export async function POST(req: Request) {
200
+ const { orderID, userId } = await req.json();
201
+ const request = new paypal.orders.OrdersCaptureRequest(orderID);
202
+ request.requestBody({});
203
+
204
+ const response = await paypalClient().execute(request);
205
+ if (response.result.status === 'COMPLETED') {
206
+ // Grant access or update subscription in DB
207
+ await db.subscription.create({
208
+ data: { userId, provider: 'paypal', status: 'active' }
209
+ });
210
+ return Response.json({ success: true });
211
+ }
212
+ return Response.json({ success: false }, { status: 400 });
213
+ }
214
+ ```
215
+
216
+ ### QRIS Static-to-Dynamic (Indonesia Alternative)
217
+
218
+ For Indonesian developers without an official Payment Gateway account, you can create a "Dynamic" QRIS experience using a single Static QRIS combined with unique payment amounts and a bank mutation checking service (e.g., Moota, Cekmutasi) via webhook.
219
+
220
+ #### 1. Generate Unique Amount (Server-Side)
221
+ ```typescript
222
+ // Add a unique 3-digit code to the base price
223
+ export async function createQrisTransaction(userId: string, basePrice: number) {
224
+ // Generate a random code between 1 and 999
225
+ const uniqueCode = Math.floor(Math.random() * 999) + 1;
226
+ const totalAmount = basePrice + uniqueCode;
227
+
228
+ const transaction = await db.transaction.create({
229
+ data: {
230
+ userId, basePrice, uniqueCode, totalAmount,
231
+ status: 'pending', provider: 'qris_static',
232
+ expiresAt: new Date(Date.now() + 15 * 60 * 1000) // 15 mins expiry
233
+ }
234
+ });
235
+
236
+ return {
237
+ transactionId: transaction.id,
238
+ totalAmount,
239
+ qrisUrl: "https://myapp.com/static-qris.png" // User must manually input totalAmount
240
+ };
241
+ }
242
+ ```
243
+
244
+ #### 2. Mutation Webhook Handler & Real-Time Notification
245
+ ```typescript
246
+ // app/api/webhooks/mutation/route.ts
247
+ import { db } from '@/lib/db';
248
+ import { pusherServer } from '@/lib/pusher';
249
+
250
+ export async function POST(req: Request) {
251
+ const signature = req.headers.get("signature");
252
+ // TODO: Verify signature from mutation service (e.g., Moota)
253
+
254
+ const mutations = await req.json();
255
+
256
+ for (const mutation of mutations) {
257
+ if (mutation.type === 'CR' && mutation.amount > 0) {
258
+ // Find pending transaction matching the exact unique amount
259
+ const tx = await db.transaction.findFirst({
260
+ where: {
261
+ totalAmount: mutation.amount,
262
+ status: 'pending',
263
+ provider: 'qris_static',
264
+ expiresAt: { gt: new Date() }
265
+ }
266
+ });
267
+
268
+ if (tx) {
269
+ // Mark as paid and activate subscription
270
+ await db.transaction.update({ where: { id: tx.id }, data: { status: 'paid' } });
271
+ await db.subscription.create({
272
+ data: { userId: tx.userId, provider: 'qris_static', status: 'active' }
273
+ });
274
+
275
+ // Trigger real-time notification to frontend
276
+ await pusherServer.trigger(`payment-${tx.id}`, 'payment-success', { success: true });
277
+ }
278
+ }
279
+ }
280
+
281
+ return new Response("OK", { status: 200 });
282
+ }
283
+ ```
284
+
285
+ ### Database Schema for Multi-Provider Billing
286
+ ```typescript
287
+ // Drizzle ORM — supports Stripe, Polar, LemonSqueezy, PayPal, QRIS Static
288
+ export const subscriptions = pgTable('subscriptions', {
289
+ id: text('id').primaryKey(),
290
+ workspaceId: text('workspace_id').references(() => workspaces.id).notNull(),
291
+ provider: text('provider').$type<'stripe' | 'polar' | 'lemonsqueezy' | 'paypal' | 'qris_static'>().notNull(),
292
+ externalCustomerId: text('external_customer_id').notNull(),
293
+ externalSubId: text('external_sub_id').notNull().unique(),
294
+ status: text('status').$type<'active' | 'trialing' | 'past_due' | 'canceled' | 'paused'>().notNull(),
295
+ plan: text('plan').$type<'free' | 'pro' | 'enterprise'>().default('free').notNull(),
296
+ currentPeriodEnd: timestamp('current_period_end'),
297
+ cancelAtPeriodEnd: boolean('cancel_at_period_end').default(false),
298
+ createdAt: timestamp('created_at').defaultNow().notNull(),
299
+ updatedAt: timestamp('updated_at').defaultNow().notNull(),
300
+ });
301
+ ```
302
+
303
+ ### Billing Security Checklist
304
+ - [ ] Webhook signature verified on every request — reject without valid signature.
305
+ - [ ] Webhook idempotency implemented — never process the same event twice.
306
+ - [ ] Session Management Optimization: Secure the billing portal route with strict session validation and CSRF protection. Do not cache session-dependent billing states.
307
+ - [ ] Use Stripe CLI / Polar.sh test webhooks for local development.
308
+ - [ ] All billing API calls use server-side code only — never expose secret keys to frontend.
309
+ - [ ] Plan limits enforced on every protected route (not just at checkout).
310
+ - [ ] Failed payment dunning flow configured (email sequence, grace period).
311
+ - [ ] Customer portal link available from within the app.
312
+
313
+ ---
314
+
315
+ <a name="bahasa-indonesia"></a>
316
+ ## Bahasa Indonesia
317
+
318
+ ### Integrasi Orkestrasi
319
+ Terhubung dan mengorkestrasi skill domain yang relevan seperti `brainstorming`, `zero-to-prod-orchestrator`, dan `project-context-mapper` untuk memastikan eksekusi yang kohesif.
320
+
321
+ ### Deskripsi
322
+ Panduan ahli untuk mengimplementasikan dan mengaudit sistem billing SaaS. Mencakup state machine langganan, penanganan webhook aman, sinkronisasi database, dan lanskap billing 2026 termasuk Stripe, **Polar.sh** (open-source, developer-first), **LemonSqueezy**, PayPal, dan Midtrans (untuk Asia Tenggara).
323
+
324
+ ### Kondisi Pemicu
325
+ - Mengintegrasikan payment gateway (Stripe, Polar.sh, LemonSqueezy, Midtrans, PayPal) ke aplikasi SaaS.
326
+ - Menggunakan alternatif QRIS Statis menjadi Dinamis (dengan nominal unik dan webhook mutasi) untuk developer lokal tanpa akun PG.
327
+ - Mengimplementasikan state machine langganan.
328
+ - Membangun webhook handler aman dengan verifikasi tanda tangan dan idempotency.
329
+ - Menyinkronkan status langganan eksternal ke database lokal.
330
+ - Mengimplementasikan billing berbasis penggunaan (metered pricing).
331
+ - Membangun portal billing pelanggan.
332
+ - Mengaudit sistem billing yang ada untuk celah keamanan.
333
+
334
+ ### Lanskap Provider Billing 2026
335
+
336
+ | Provider | Terbaik Untuk | Open Source | Merchant of Record |
337
+ |---|---|---|---|
338
+ | **Stripe** | Enterprise, global, billing kompleks | ❌ | ❌ |
339
+ | **Polar.sh** | Developer-first, produk open-source | ✅ | ✅ (opsional) |
340
+ | **LemonSqueezy** | Indie hackers, harga sederhana | ❌ | ✅ |
341
+ | **Paddle** | B2B SaaS, kepatuhan PPN EU | ❌ | ✅ |
342
+ | **Midtrans** | Asia Tenggara / Indonesia | ❌ | ❌ |
343
+ | **PayPal** | Global, kepercayaan konsumen (consumer trust) | ❌ | ❌ |
344
+
345
+ > **Merchant of Record (MoR)**: Provider menangani kepatuhan pajak (PPN, GST), chargeback, dan tanggung jawab hukum — ideal untuk tim kecil tanpa departemen keuangan.
346
+
347
+ ### Polar.sh — Billing Developer-First
348
+ Polar.sh adalah alternatif open-source modern untuk Gumroad/LemonSqueezy, dirancang khusus untuk developer dan proyek open-source. Mendukung checkout, webhook, dan manajemen langganan dengan SDK TypeScript yang bersih.
349
+
350
+ ### PayPal — Integrasi Checkout
351
+ PayPal sering digunakan sebagai gateway alternatif atau utama karena tingginya kepercayaan konsumen global.
352
+ - **Server-Side Checkout**: Gunakan `create-order` dan `capture-order` di backend (menggunakan `@paypal/checkout-server-sdk`) untuk memastikan keamanan dan mencegah manipulasi harga di sisi klien.
353
+ - **Webhook**: Verifikasi webhook dari PayPal untuk langganan yang diperbarui atau dibatalkan.
354
+
355
+ ### Stripe — Pola Produksi
356
+
357
+ #### State Machine Langganan
358
+ Kelola transisi status: `FREE → TRIALING → ACTIVE → PAST_DUE → CANCELED → (reaktivasi)`.
359
+
360
+ #### Webhook Handler Idempoten
361
+ Selalu verifikasi tanda tangan webhook, tandai event sebagai diproses di database untuk mencegah duplikasi.
362
+
363
+ #### Billing Berbasis Penggunaan (Metered)
364
+ Laporkan penggunaan API dengan `stripe.subscriptionItems.createUsageRecord()` di akhir periode billing.
365
+
366
+ ### Alternatif Lokal: QRIS Statis Rasa Dinamis (Tanpa Akun Payment Gateway)
367
+ Bagi pengguna/developer di Indonesia yang belum memiliki Payment Gateway (seperti Midtrans), Anda dapat membuat pengalaman QRIS "Dinamis" menggunakan satu gambar QRIS statis biasa.
368
+ - **Generate Nominal Unik (Endpoint)**: Tambahkan angka unik (misalnya 3 digit acak) ke harga dasar (contoh: Rp 100.000 menjadi Rp 100.123). Simpan ke database sebagai transaksi `pending` dengan batas waktu kadaluarsa (misal 15 menit). Tampilkan gambar QRIS beserta instruksi transfer sesuai nominal unik.
369
+ - **Webhook Mutasi Bank**: Gunakan layanan pihak ketiga (seperti Moota, Cekmutasi) yang mengirimkan notifikasi webhook (ke `/api/webhooks/mutation`) setiap kali ada uang masuk.
370
+ - **Validasi Otomatis**: Saat webhook menerima payload mutasi kredit (`CR`), sistem mencari transaksi `pending` yang jumlahnya sama persis (`totalAmount`). Jika cocok, sistem menandai tagihan sebagai lunas (`paid`) dan mengaktifkan langganan.
371
+ - **Notifikasi Klien**: Gunakan WebSocket (seperti Pusher atau Socket.io) di backend untuk melakukan *trigger event* "pembayaran berhasil". Di frontend, *listen* ke event tersebut dan tampilkan notifikasi *real-time* kepada pengguna secara instan tanpa perlu me-refresh halaman.
372
+
373
+ ### Skema Database Multi-Provider
374
+ Rancang tabel `subscriptions` yang mendukung beberapa provider (`stripe`, `polar`, `lemonsqueezy`, `paypal`, `qris_static`) dengan kolom `provider` dan ID eksternal yang terpisah.
375
+
376
+ ### Checklist Keamanan Billing
377
+ - [ ] Tanda tangan webhook diverifikasi pada setiap permintaan.
378
+ - [ ] Idempotency webhook diimplementasikan.
379
+ - [ ] Optimasi Session Management: Amankan rute portal billing dengan validasi sesi yang ketat dan perlindungan CSRF. Jangan gunakan cache untuk state billing yang bergantung pada sesi pengguna.
380
+ - [ ] Semua panggilan API billing menggunakan kode sisi server saja.
381
+ - [ ] Batas plan diterapkan pada setiap rute yang dilindungi.
382
+ - [ ] Alur dunning pembayaran gagal dikonfigurasi.
383
+ - [ ] Tautan portal pelanggan tersedia dari dalam aplikasi.