From dc16d26f3734ee0bd727b7aa8b3e3a128873e119 Mon Sep 17 00:00:00 2001 From: doanbactam Date: Sun, 1 Feb 2026 11:50:01 +0700 Subject: [PATCH] feat(polar): Introduce Polar monetization platform with comprehensive documentation - Added Polar power to README.md, detailing its capabilities for managing products, subscriptions, payments, and customer billing. - Created mcp.json configuration for Polar MCP server setup. - Added extensive POWER.md documentation outlining features, best practices, and integration guidelines for using Polar. - Introduced polar-best-practices.md to provide integration strategies and error handling recommendations. --- README.md | 7 + polar/POWER.md | 392 +++++++++++++++++++++++++ polar/mcp.json | 13 + polar/steering/polar-best-practices.md | 314 ++++++++++++++++++++ 4 files changed, 726 insertions(+) create mode 100644 polar/POWER.md create mode 100644 polar/mcp.json create mode 100644 polar/steering/polar-best-practices.md diff --git a/README.md b/README.md index 03c7d25..df34718 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,13 @@ Documentation is available at https://kiro.dev/docs/powers/ --- +### polar +**Power Builder** - Build monetization platform for developers - manage products, subscriptions, payments, and customer billing. + +**MCP Servers:** polar + +--- + ### saas-builder **SaaS Builder** - Build production-ready multi-tenant SaaS applications with serverless architecture, integrated billing, and enterprise-grade security. diff --git a/polar/POWER.md b/polar/POWER.md new file mode 100644 index 0000000..57fbe9b --- /dev/null +++ b/polar/POWER.md @@ -0,0 +1,392 @@ +--- +name: "polar" +displayName: "Polar" +description: "Monetization platform for developers - manage products, subscriptions, payments, and customer billing" +keywords: ["polar","monetization","payments","subscriptions","products","customers","orders","billing","saas","revenue","checkout"] +author: "Polar" +--- + +# Polar Power + +## Overview + +Build monetization features with Polar's developer-first payment platform. Accept payments, manage subscriptions, handle customer billing, and track revenue. This power provides access to Polar's APIs through an MCP server, enabling you to build production-ready monetization systems. + +Use Polar Checkout for hosted payment pages, Products API for catalog management, or Subscriptions API for recurring billing. The platform handles payment processing via Stripe, provides customer portal, and supports multiple currencies. + +**Key capabilities:** + +- **Products**: Create digital products with flexible pricing models (one-time, recurring, usage-based) +- **Checkouts**: Hosted payment pages for seamless purchase flows +- **Subscriptions**: Recurring billing with automatic renewals and proration +- **Customers**: Manage customer data and payment methods +- **Orders**: Track purchases and fulfillment +- **Payments**: Monitor payment transactions +- **Metrics**: Revenue analytics and business insights +- **Benefits**: Grant features/perks when products are purchased + +**Authentication**: Requires Organization Access Token (OAT) for server-side operations. Never expose in client code. Customer Access Tokens are for customer-facing operations only. + +## Available MCP Servers + +### polar + +**Connection:** MCP server via npx +**Authorization:** Requires `POLAR_ACCESS_TOKEN` environment variable + +## Best Practices + +### Integration Approach + +**Always prefer Checkout Sessions** for standard payment flows: + +- One-time product purchases +- Subscription sign-ups +- Hosted checkout pages (Polar handles UI) + +**Use Products API** to: + +- Create and manage your product catalog +- Define pricing models (recurring, one-time, usage-based) +- Configure benefits and features +- Set up multiple price points per product + +**Use Subscriptions API** for: + +- Listing active subscriptions +- Updating subscription plans (upgrades/downgrades) +- Canceling subscriptions +- Checking subscription status for access control + +### Authentication + +**Organization Access Tokens (OAT)** for server-side: + +- Full API access to manage products, orders, subscriptions +- Create in Polar Dashboard → Settings → API +- Store securely in environment variables +- Never expose in browser/client code + +**Customer Access Tokens** for customer-facing: + +- Generate via `/v1/customer-sessions/` endpoint +- Scoped to individual customer data only +- Use with Customer Portal API +- Safe for client-side use (limited scope) + +### Environments + +**Sandbox** (`https://sandbox-api.polar.sh/v1`): + +- Safe testing environment +- Use during development +- Test all workflows before production + +**Production** (`https://api.polar.sh/v1`): + +- Real customers and live payments +- Switch after thorough testing +- Monitor carefully in Dashboard + +### Pricing Strategy + +**Use cents for all amounts**: + +- `price_amount: 2900` = $29.00 +- Avoids floating-point issues +- Consistent with Stripe conventions + +**Offer multiple pricing options**: + +- Monthly and annual plans (with discount) +- Good-Better-Best tiers +- Usage-based for APIs/metered services + +**Consider psychological pricing**: + +- $29 converts better than $30 +- Annual discounts (15-20%) encourage commitment +- Free trials to convert users + +### Subscription Management + +**Handle subscription lifecycle**: + +- Listen for webhook events (created, updated, canceled) +- Check subscription status before granting access +- Implement grace periods for failed payments +- Allow cancel at period end (customer keeps access) + +**Proration is automatic**: + +- Polar handles mid-cycle plan changes +- Credits/charges calculated automatically +- No manual proration logic needed + +### Customer Experience + +**Use hosted checkout**: + +- Fastest integration path +- Polar handles payment UI +- Mobile-optimized by default +- PCI compliance handled + +**Implement webhooks**: + +- Real-time subscription updates +- Payment success/failure notifications +- Order fulfillment triggers +- Critical for production apps + +**Provide customer portal**: + +- Let customers manage subscriptions +- Update payment methods +- View invoices and receipts +- Reduces support burden + +### Error Handling + +**Handle rate limits**: + +- 100 requests/minute (authenticated) +- 10 requests/minute (unauthenticated) +- Check `Retry-After` header on 429 responses +- Implement exponential backoff + +**Validate before API calls**: + +- Check product/price IDs exist +- Verify customer data format +- Ensure required fields present +- Log all API errors for debugging + +## Common Workflows + +### Workflow 1: Create Product and Accept Payment + +```typescript +// Step 1: Create product with pricing +const product = polar_products_create({ + name: "Pro Plan", + description: "Full access to all features", + is_recurring: true, + prices: [{ + type: "recurring", + recurring_interval: "month", + price_amount: 2900, // $29.00 + price_currency: "usd" + }] +}); + +// Step 2: Create checkout session +const checkout = polar_checkouts_create({ + product_id: product.id, + success_url: "https://yourapp.com/success", + customer_email: "customer@example.com" +}); + +// Step 3: Redirect customer to checkout.url +// Step 4: Handle webhook for subscription.created +``` + +### Workflow 2: Check Subscription Status for Access Control + +```typescript +// Step 1: List customer's subscriptions +const subscriptions = polar_subscriptions_list({ + customer_id: "cus_xxx", + active: true +}); + +// Step 2: Check if they have required subscription +const hasAccess = subscriptions.items.some( + sub => sub.status === 'active' && sub.product_id === 'prod_required' +); + +// Step 3: Grant or deny access based on status +if (hasAccess) { + // Allow access to premium features +} else { + // Show upgrade prompt +} +``` + +### Workflow 3: Upgrade/Downgrade Subscription + +```typescript +// Step 1: Update subscription with new product +const updated = polar_subscriptions_update({ + subscription_id: "sub_xxx", + product_id: "prod_new_plan" +}); + +// Polar automatically handles proration +// Customer charged/credited for difference +// Handle webhook for subscription.updated +``` + +### Workflow 4: Track Revenue Metrics + +```typescript +// Get monthly recurring revenue +const metrics = polar_metrics_get({ + start_date: "2024-01-01", + end_date: "2024-01-31", + interval: "month" +}); + +// Returns MRR, active subscriptions, churn rate, etc. +``` + +## Best Practices Summary + +### ✅ Do: + +- **Use Checkout Sessions** for standard payment flows +- **Store OAT securely** in environment variables +- **Test in Sandbox** before going live +- **Implement webhooks** for all async events +- **Use cents for pricing** (2900 = $29.00) +- **Handle rate limits** with exponential backoff +- **Check subscription status** before granting access +- **Provide customer portal** for self-service +- **Log all API interactions** for debugging +- **Validate webhook signatures** for security + +### ❌ Don't: + +- **Expose OAT in client code** - use Customer Access Tokens instead +- **Skip webhook handling** - critical for subscription updates +- **Hardcode product IDs** - fetch from API or use environment variables +- **Ignore rate limits** - implement proper retry logic +- **Skip Sandbox testing** - test all scenarios first +- **Forget error handling** - show clear messages to customers +- **Use floating-point for prices** - always use cents (integers) +- **Immediately revoke access** on payment failure - implement grace periods +- **Skip pagination** - handle large result sets properly +- **Ignore webhook events** - they contain critical state changes + +## Configuration + +**Authentication Required**: Polar Organization Access Token + +**Setup Steps:** + +1. Create Polar account at https://polar.sh +2. Navigate to Dashboard → Settings → API +3. Click "Create Access Token" +4. Copy your token (starts with `polar_oat_`) +5. For testing, use Sandbox environment +6. For production, switch to Production environment +7. Configure token in Kiro Powers UI when installing this power + +**Permissions**: OAT has full API access - keep secure and never expose client-side. + +**MCP Configuration:** + +```json +{ + "mcpServers": { + "polar": { + "command": "npx", + "args": ["-y", "@polar-sh/mcp-server-polar"], + "env": { + "POLAR_ACCESS_TOKEN": "${POLAR_ACCESS_TOKEN}", + "POLAR_ENVIRONMENT": "${POLAR_ENVIRONMENT:-sandbox}" + } + } + } +} +``` + +## Troubleshooting + +### Error: "Invalid API token" + +**Cause:** Incorrect or missing API token +**Solution:** + +1. Verify token starts with `polar_oat_` +2. Check token hasn't been deleted in Dashboard +3. Ensure using Organization Access Token, not Customer token +4. Regenerate token if compromised + +### Error: "Product not found" + +**Cause:** Invalid product ID or product deleted +**Solution:** + +1. Verify product ID format (starts with `prod_`) +2. Check product exists in Dashboard +3. Ensure using correct environment (sandbox vs production) +4. List products to verify ID + +### Error: "Subscription not found" + +**Cause:** Invalid subscription ID or subscription deleted +**Solution:** + +1. Verify subscription ID format (starts with `sub_`) +2. Check subscription exists in Dashboard +3. Ensure using correct environment +4. List subscriptions to verify ID + +### Checkout creation failed + +**Cause:** Missing required parameters or invalid product +**Solution:** + +1. Verify product ID exists and is active +2. Check success_url is valid HTTPS URL +3. Ensure product has at least one price +4. Review error message for specific issue + +### Webhook not received + +**Cause:** Webhook endpoint not configured or failing +**Solution:** + +1. Configure webhook endpoint in Dashboard → Settings → Webhooks +2. Verify endpoint is publicly accessible +3. Check endpoint returns 200 status +4. Review webhook logs in Dashboard +5. Validate webhook signature in your handler + +### Rate limit exceeded + +**Cause:** Too many requests in short time +**Solution:** + +1. Check `Retry-After` header in 429 response +2. Implement exponential backoff +3. Cache frequently accessed data +4. Batch operations where possible +5. Review rate limits (100/min authenticated) + +## Tips + +1. **Start with Sandbox** - Test all scenarios before going live +2. **Use hosted checkout** - Fastest way to accept payments +3. **Implement webhooks early** - Critical for subscription updates +4. **Cache subscription status** - Reduce API calls with short TTL (5-10 min) +5. **Offer annual discounts** - Encourage longer commitments +6. **Monitor Dashboard** - Review payments, subscriptions, and metrics +7. **Handle errors gracefully** - Show clear messages to customers +8. **Use pagination** - Handle large result sets properly +9. **Keep tokens secure** - Never commit to version control +10. **Test edge cases** - Failed payments, cancellations, upgrades + +## Resources + +- [Polar Documentation](https://polar.sh/docs) +- [API Reference](https://polar.sh/docs/api-reference) +- [Sandbox Environment](https://sandbox.polar.sh) +- [Webhook Events](https://polar.sh/docs/webhooks) +- [Customer Portal](https://polar.sh/docs/customer-portal) +- [Checkout Guide](https://polar.sh/docs/features/checkouts) + +--- + +**License:** Proprietary diff --git a/polar/mcp.json b/polar/mcp.json new file mode 100644 index 0000000..d0e666a --- /dev/null +++ b/polar/mcp.json @@ -0,0 +1,13 @@ +{ + "mcpServers": { + "polar": { + "command": "npx", + "args": ["-y", "@polar-sh/mcp-server-polar"], + "env": { + "POLAR_ACCESS_TOKEN": "${POLAR_ACCESS_TOKEN}", + "POLAR_ENVIRONMENT": "${POLAR_ENVIRONMENT:-sandbox}" + } + } + } +} + diff --git a/polar/steering/polar-best-practices.md b/polar/steering/polar-best-practices.md new file mode 100644 index 0000000..2a4d9ba --- /dev/null +++ b/polar/steering/polar-best-practices.md @@ -0,0 +1,314 @@ +# Polar Integration Best Practices + +## Integration Approach + +When designing a monetization integration with Polar, always prefer the documentation in [Polar's API Reference](https://polar.sh/docs/api-reference) and [Integration Guides](https://polar.sh/docs). + +The [Checkout Guide](https://polar.sh/docs/features/checkouts) provides a comprehensive overview of Polar's payment flows. + +You should always use the latest version of the API and SDK unless the user specifies otherwise. + +## Payment and Checkout APIs + +Polar's primary API for accepting payments is [Checkout Sessions](https://polar.sh/docs/features/checkouts/checkout-sessions). It supports one-time payments and subscriptions with hosted or embedded checkout pages. Prioritize Checkout Sessions for standard payment flows. + +For custom implementations, you can use the Products API to manage your catalog and the Subscriptions API for recurring billing. Integrations should primarily use Checkout Sessions combined with Products and Subscriptions APIs. + +## Product Management + +**Create products with clear pricing models**: + +- Use `is_recurring: true` for subscription products +- Use `is_recurring: false` for one-time purchases +- Define multiple prices per product (monthly, annual, etc.) +- Use cents for all price amounts (2900 = $29.00) + +**Product types to consider**: + +- **Recurring subscriptions**: SaaS plans, memberships +- **One-time products**: Digital downloads, courses, lifetime access +- **Usage-based**: APIs, metered services (combine with Customer Meters) + +## Subscription Management + +**For recurring revenue models**, use the Subscriptions API: + +- List subscriptions to check customer access +- Update subscriptions for plan changes (automatic proration) +- Cancel subscriptions with `cancel_at_period_end` option +- Monitor subscription status for access control + +**Subscription lifecycle**: + +- `active`: Customer has access, billing is current +- `canceled`: Subscription canceled but may still be active until period ends +- `past_due`: Payment failed, implement grace period +- `incomplete`: Initial payment not completed + +## Authentication and Security + +**Organization Access Tokens (OAT)**: + +- Use for all server-side API operations +- Create in Dashboard → Settings → API +- Store securely in environment variables +- Never expose in client-side code or public repositories + +**Customer Access Tokens**: + +- Generate via `/v1/customer-sessions/` endpoint +- Use for customer-facing operations (Customer Portal) +- Scoped to individual customer data only +- Safe for client-side use with limited scope + +## Environments + +**Always test in Sandbox first**: + +- Sandbox: `https://sandbox-api.polar.sh/v1` +- Use for development and integration testing +- Test all payment flows and edge cases +- Verify webhook handling + +**Production deployment**: + +- Production: `https://api.polar.sh/v1` +- Switch after thorough Sandbox testing +- Monitor Dashboard for issues +- Set up proper error logging + +## Webhooks + +**Implement webhook handlers for critical events**: + +- `subscription.created`: New subscription started +- `subscription.updated`: Plan changed or renewed +- `subscription.canceled`: Subscription canceled +- `order.created`: New order placed +- `payment.succeeded`: Payment completed successfully +- `payment.failed`: Payment failed, handle gracefully + +**Webhook best practices**: + +- Validate webhook signatures for security +- Return 200 status quickly (process async if needed) +- Handle idempotency (same event may be sent multiple times) +- Log all webhook events for debugging +- Configure in Dashboard → Settings → Webhooks + +## Access Control + +**Check subscription status before granting access**: + +```typescript +// List customer's active subscriptions +const subscriptions = await polar_subscriptions_list({ + customer_id: customerId, + active: true +}); + +// Verify they have required subscription +const hasAccess = subscriptions.items.some( + sub => sub.status === 'active' && sub.product_id === requiredProductId +); +``` + +**Implement caching**: + +- Cache subscription status with short TTL (5-10 minutes) +- Reduces API calls and improves performance +- Invalidate cache on webhook events +- Balance freshness vs API usage + +## Pricing Strategy + +**Use psychological pricing**: + +- $29 converts better than $30 (charm pricing) +- Offer annual discounts (15-20%) to encourage commitment +- Create Good-Better-Best tiers (3 options) +- Position middle tier as "most popular" + +**Pricing in cents**: + +- Always use integers for price amounts +- 2900 = $29.00 (avoids floating-point issues) +- Consistent with Stripe conventions +- Prevents rounding errors + +## Error Handling + +**Handle rate limits gracefully**: + +- 100 requests/minute for authenticated requests +- 10 requests/minute for unauthenticated requests +- Check `Retry-After` header on 429 responses +- Implement exponential backoff for retries + +**Validate before API calls**: + +- Check product IDs exist before creating checkouts +- Verify customer data format +- Ensure required fields are present +- Log all API errors with context + +**Common errors to handle**: + +- Invalid API token: Check token format and permissions +- Product not found: Verify product ID and environment +- Subscription not found: Check subscription ID and status +- Rate limit exceeded: Implement backoff and retry logic + +## Customer Experience + +**Use hosted checkout for fastest integration**: + +- Polar handles payment UI and PCI compliance +- Mobile-optimized by default +- Supports multiple payment methods +- Reduces development time significantly + +**Provide customer portal**: + +- Let customers manage their own subscriptions +- Update payment methods without support +- View invoices and receipts +- Reduces support burden + +**Handle failed payments gracefully**: + +- Don't immediately revoke access +- Send payment reminder emails +- Implement grace period (3-7 days) +- Polar retries failed payments automatically + +## Benefits and Features + +**Use Benefits to grant access**: + +- Define what customers get with each product +- Types: custom, discord, github_repo, downloadables, license_keys +- Automatically fulfilled by Polar where possible +- Check benefits in subscription object for access control + +## Pagination + +**Handle large result sets properly**: + +- Use `page` and `limit` parameters +- Default limit is 10, max is 100 +- Check `total_count` for total items +- Check `max_page` for total pages +- Implement pagination UI for better UX + +## Testing + +**Test thoroughly in Sandbox**: + +- Create test products and prices +- Complete test checkout flows +- Verify webhook delivery +- Test subscription updates and cancellations +- Test failed payment scenarios +- Verify access control logic + +**Use test payment methods**: + +- Polar uses Stripe for payment processing +- Use Stripe test cards in Sandbox +- Test card: 4242 4242 4242 4242 +- Test declined: 4000 0000 0000 0002 +- Test 3D Secure: 4000 0027 6000 3184 + +## Monitoring + +**Monitor key metrics in Dashboard**: + +- Monthly Recurring Revenue (MRR) +- Active subscriptions count +- Churn rate +- Failed payment rate +- Customer lifetime value (LTV) + +**Set up alerts**: + +- Failed payment spikes +- Unusual cancellation rates +- API error rates +- Webhook delivery failures + +## Migration from Other Platforms + +**If migrating from Stripe, Paddle, or others**: + +- Export customer and subscription data +- Create matching products in Polar +- Migrate customers with existing subscriptions +- Update payment methods if needed +- Test thoroughly before switching +- Communicate changes to customers + +## Performance Optimization + +**Reduce API calls**: + +- Cache frequently accessed data (products, prices) +- Use webhooks instead of polling +- Batch operations where possible +- Implement request deduplication + +**Database design**: + +- Store product IDs and subscription IDs locally +- Cache subscription status with TTL +- Index customer_id for fast lookups +- Log all API interactions for debugging + +## Compliance and Legal + +**Ensure compliance**: + +- Display clear pricing and terms +- Provide easy cancellation process +- Send receipts and invoices +- Handle refunds appropriately +- Follow local regulations (GDPR, etc.) + +**Tax handling**: + +- Polar integrates with Stripe Tax +- Configure tax settings in Dashboard +- Collect customer location for tax calculation +- Display tax-inclusive or exclusive pricing + +## Common Patterns + +**Freemium model**: + +- Create free product with limited features +- Offer paid tiers with more features +- Use free trials to convert users +- Track conversion metrics + +**Usage-based billing**: + +- Use Customer Meters API +- Track usage events (API calls, storage, etc.) +- Combine with base subscription fee +- Bill based on actual usage + +**Seat-based pricing**: + +- Store seat count in subscription metadata +- Charge per user/seat +- Allow adding/removing seats +- Prorate charges automatically + +## Resources + +- [Polar Documentation](https://polar.sh/docs) +- [API Reference](https://polar.sh/docs/api-reference) +- [Checkout Guide](https://polar.sh/docs/features/checkouts) +- [Webhook Events](https://polar.sh/docs/webhooks) +- [Customer Portal](https://polar.sh/docs/customer-portal) +- [Sandbox Dashboard](https://sandbox.polar.sh)