Subscription counter plugin
A starter for Medusa plugins.
Features
- Subscription Management: Convert carts to subscriptions
- Credit System: Use credits when visiting products
- Customer Authentication: Secure access to subscription features
- TypeScript Support: Full type safety and IntelliSense support
Compatibility
This plugin is compatible with versions >= 2.4.0 of .
Installation
npm install medusa-subscription-counter-plugin# oryarn add medusa-subscription-counter-plugin
Getting Started
1. Import the Plugin Functions
import {createSubscriptionFromCart,useCredit} from 'medusa-subscription-counter-plugin';
2. Using the Functions
Create Subscription from Cart
Converts an existing cart into a subscription for authenticated customers.
import { createSubscriptionFromCart } from 'medusa-subscription-counter-plugin';// In your API route handlerexport const POST = async (req, res) => {try {const cartId = req.params.id; // or req.body.cartIdconst result = await createSubscriptionFromCart(req, cartId);res.json({type: "subscription",subscription: result});} catch (error) {res.status(500).json({type: "error",message: error.message});}};
Use Credits
Processes credit usage when a customer visits a product.
import { useCredit } from 'medusa-subscription-counter-plugin';// In your API route handlerexport const POST = async (req, res) => {try {const result = await useCredit(req);res.json({type: "credit_usage",result: result});} catch (error) {res.status(500).json({type: "error",message: error.message});}};
API Reference
Creates a subscription from an existing cart.
Parameters:
- (AuthenticatedMedusaRequest): The authenticated request object
- (string): The ID of the cart to convert to subscription
Returns: Promise that resolves to the created subscription object
Throws: Error if customer is not authenticated or cart conversion fails
Processes credit usage when a customer visits a product.
Parameters:
- (AuthenticatedMedusaRequest): The authenticated request object
Returns: Promise that resolves to the credit usage result
Throws: Error if customer is not authenticated or credit processing fails
Authentication Requirements
Both functions require customer authentication. The plugin automatically validates:
- Customer session validity
- Authentication token presence
- Customer permissions
Unauthenticated requests will result in an authentication error.
Example Implementation
Complete API Route Example
// /src/api/store/subscriptions/route.tsimport {AuthenticatedMedusaRequest,MedusaResponse,} from "@medusajs/framework";import {createSubscriptionFromCart,useCredit} from 'medusa-subscription-counter-plugin';export const POST = async (req: AuthenticatedMedusaRequest,res: MedusaResponse) => {try {const { action, cartId } = req.body;let result;switch (action) {case 'create_subscription':result = await createSubscriptionFromCart(req, cartId);break;case 'use_credit':result = await useCredit(req);break;default:return res.status(400).json({type: "error",message: "Invalid action"});}res.json({success: true,data: result});} catch (error) {console.error("Subscription operation error:", error);res.status(500).json({type: "error",message: error.message});}};
Frontend Usage Example
// Frontend code to create subscriptionconst createSubscription = async (cartId: string) => {const response = await fetch('/store/subscriptions', {method: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${customerToken}`},body: JSON.stringify({action: 'create_subscription',cartId: cartId})});const result = await response.json();return result.data;};// Frontend code to use creditsconst useCreditForProduct = async () => {const response = await fetch('/store/subscriptions', {method: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${customerToken}`},body: JSON.stringify({action: 'use_credit'})});const result = await response.json();return result.data;};
Error Handling
The plugin provides comprehensive error handling:
- Authentication Errors: When customer is not authenticated
- Validation Errors: When required parameters are missing
- Business Logic Errors: When subscription or credit operations fail
Always wrap function calls in try-catch blocks and handle errors appropriately.
Development
Visit the Quickstart Guide to set up a Medusa server.
Visit the Plugins documentation to learn more about plugins and how to create them.
What is Medusa
Medusa is a set of commerce modules and tools that allow you to build rich, reliable, and performant commerce applications without reinventing core commerce logic. The modules can be customized and used to build advanced ecommerce stores, marketplaces, or any product that needs foundational commerce primitives. All modules are open-source and freely available on npm.
Learn more about Medusa's architecture and commerce modules in the Docs.
Community & Contributions
The community and core team are available in GitHub Discussions, where you can ask for support, discuss roadmap, and share ideas.
Join our Discord server to meet other community members.