npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

coupan-code

v1.0.4

Published

Easy-to-use TypeScript/Node.js package for referral codes, coupon codes, promo codes, and discount codes. Create, verify, and manage discount codes with MongoDB. Supports percentage discounts, fixed amount discounts, usage limits, and custom codes. Zero c

Downloads

486

Readme

Coupan Code - Referral Code, Coupon Code & Promo Code Management SDK

The easiest way to manage referral codes, coupon codes, promo codes, and discount codes in your Node.js/TypeScript applications. Create, verify, and track discount codes with percentage or fixed amount discounts. Zero MongoDB configuration required - just API key and you're ready!

npm version TypeScript License

🚀 Quick Start

Step 1: Installation

npm install coupan-code

Step 2: Get Your API Key

Before using the package, you need an API key and Client ID.

To get your API key and Client ID, please email us at:

  • Email: [email protected]
  • Subject: "API Key Request for Coupan Code"
  • Include: Your name, company name (if applicable), and intended use case

We'll provide you with:

  • Your unique Client ID
  • Your API Key (format: sk_live_<random_string> or sk_test_<random_string>)

Note: Please store your API key securely. It cannot be retrieved again if lost.

Step 3: Use the Package

import { CoupanCodeSDK, DiscountType } from 'coupan-code';

// Initialize with your API key and Client ID
const sdk = new CoupanCodeSDK({
  apiKey: 'sk_live_your_api_key_here',
  clientId: 'your-client-id'
});

// Connect and validate (connects to our centralized database automatically)
await sdk.init();

// Create a referral code
const result = await sdk.createCode(
  DiscountType.PERCENTAGE,
  15,  // 15% discount
  10   // Can be used 10 times
);

if (result.success) {
  console.log('Code created:', result.code);
}

That's it! You're ready to use Coupan Code.


📖 Step-by-Step Guide

Step 1: Install the Package

npm install coupan-code

Step 2: Get Your Credentials

You need two things to use the package:

  1. API Key: A secret key that authenticates your requests

    • Format: sk_live_<random_string> or sk_test_<random_string>
    • Get it by emailing: [email protected]
  2. Client ID: Your unique client identifier

    • Provided when you get your API key via email

How to Request API Key: Send an email to [email protected] with:

  • Subject: "API Key Request for Coupan Code"
  • Your name and company (if applicable)
  • Brief description of your use case

Need Help? Contact us at [email protected] for:

  • Getting your API key
  • Resetting your credentials
  • Technical support
  • Any questions about the package

Step 3: Initialize the SDK

import { CoupanCodeSDK } from 'coupan-code';

// Initialize with your API key and Client ID
// MongoDB connection is handled automatically - no configuration needed!
const sdk = new CoupanCodeSDK({
  apiKey: 'sk_live_your_api_key_here',
  clientId: 'your-client-id'
});

// This validates your API key and connects to our centralized database
await sdk.init();

Note: The package automatically connects to our centralized MongoDB database. You don't need to configure MongoDB connection - it's all handled internally!

Step 5: Create Referral Codes

import { DiscountType } from 'coupan-code';

// Create a percentage discount code
const result = await sdk.createCode(
  DiscountType.PERCENTAGE,
  20,  // 20% off
  5    // Can be used 5 times
);

// Create a fixed amount discount code
const fixedResult = await sdk.createCode(
  DiscountType.AMOUNT,
  50,  // $50 off
  10   // Can be used 10 times
);

// Create with a custom code
const customResult = await sdk.createCode(
  DiscountType.PERCENTAGE,
  15,
  10,
  'SUMMER2024'  // Your custom code
);

Step 6: Verify Codes

// Check if a code is valid
const verification = await sdk.verifyCode('SUMMER2024');

if (verification.isValid) {
  console.log('Code is valid!');
  console.log('Discount:', verification.discountInfo?.discountValue);
}

// Verify and calculate discount amount
const verifyWithAmount = await sdk.verifyCode('SUMMER2024', 1000);

if (verifyWithAmount.isValid && verifyWithAmount.discountInfo) {
  console.log('Original amount: $1000');
  console.log('Discount: $' + verifyWithAmount.discountInfo.discountAmount);
  console.log('Final amount: $' + verifyWithAmount.discountInfo.finalAmount);
}

Step 7: Track Usage

// When a customer uses the code, increment usage
const usage = await sdk.incrementUsage('SUMMER2024');

if (usage.success) {
  console.log('Usage count:', usage.usedCount);
  console.log('Still active:', usage.isActive);
}

💡 Common Use Cases

Use Case 1: Create a Simple Discount Code

const sdk = new CoupanCodeSDK({
  apiKey: 'sk_live_your_key',
  clientId: 'your-client-id'
});

await sdk.init();

// Create 10% off code, unlimited uses
const code = await sdk.createCode(
  DiscountType.PERCENTAGE,
  10
);

console.log('Your code:', code.code);

Use Case 2: Create Limited-Time Promo Code

// Create code with usage limit
const promo = await sdk.createCode(
  DiscountType.PERCENTAGE,
  25,  // 25% off
  100  // Only 100 uses allowed
);

console.log('Promo code:', promo.code);

Use Case 3: Verify Code at Checkout

// Customer enters code at checkout
const customerCode = 'SUMMER2024';
const cartTotal = 500;

const check = await sdk.verifyCode(customerCode, cartTotal);

if (check.isValid && check.discountInfo) {
  const finalPrice = check.discountInfo.finalAmount;
  console.log(`Total after discount: $${finalPrice}`);
  
  // Apply the discount and increment usage
  await sdk.incrementUsage(customerCode);
} else {
  console.log('Invalid code:', check.error);
}

📚 Complete Example

Here's a full example showing all features:

import { CoupanCodeSDK, DiscountType } from 'coupan-code';

async function main() {
  try {
    // 1. Initialize SDK
    const sdk = new CoupanCodeSDK({
      apiKey: 'sk_live_your_api_key',
      clientId: 'your-client-id'
    });

    await sdk.init();
    console.log('✅ SDK initialized');

    // 2. Create a referral code
    const createResult = await sdk.createCode(
      DiscountType.PERCENTAGE,
      20,  // 20% discount
      5    // 5 uses allowed
    );

    if (!createResult.success) {
      throw new Error(createResult.error);
    }

    const code = createResult.code!;
    console.log(`✅ Created code: ${code}`);

    // 3. Verify the code
    const verifyResult = await sdk.verifyCode(code, 1000);
    
    if (verifyResult.isValid && verifyResult.discountInfo) {
      console.log('✅ Code is valid');
      console.log(`   Original: $1000`);
      console.log(`   Discount: $${verifyResult.discountInfo.discountAmount}`);
      console.log(`   Final: $${verifyResult.discountInfo.finalAmount}`);
    }

    // 4. Use the code
    const usage = await sdk.incrementUsage(code);
    console.log(`✅ Usage count: ${usage.usedCount}`);

  } catch (error) {
    console.error('❌ Error:', error);
  }
}

main();

🔑 API Reference

CoupanCodeSDK

Constructor

new CoupanCodeSDK(config: {
  apiKey: string;    // Your API key
  clientId: string; // Your client ID
})

Methods

init()

Initializes the SDK. Must be called before using any other methods.

await sdk.init();
createCode(discountType, discountValue, usageLimit?, customCode?)

Creates a new referral code.

Parameters:

  • discountType: DiscountType.PERCENTAGE or DiscountType.AMOUNT
  • discountValue: Discount value (0-100 for percentage, any number for amount)
  • usageLimit (optional): Maximum number of uses
  • customCode (optional): Your custom code string

Returns:

{
  success: boolean;
  code?: string;
  error?: string;
  message?: string;
}

Example:

// Auto-generated code
const result = await sdk.createCode(DiscountType.PERCENTAGE, 15, 10);

// Custom code
const custom = await sdk.createCode(DiscountType.PERCENTAGE, 15, 10, 'MYCODE');
verifyCode(code, originalAmount?)

Verifies a referral code and calculates discount.

Parameters:

  • code: The referral code to verify
  • originalAmount (optional): Original amount for discount calculation

Returns:

{
  isValid: boolean;
  discountInfo?: {
    discountType: DiscountType;
    discountValue: number;
    discountAmount?: number;
    finalAmount?: number;
  };
  error?: string;
}

Example:

// Just verify
const check = await sdk.verifyCode('MYCODE');

// Verify and calculate
const checkWithAmount = await sdk.verifyCode('MYCODE', 1000);
incrementUsage(code)

Increments the usage count. Automatically deactivates when limit is reached.

Parameters:

  • code: The referral code

Returns:

{
  success: boolean;
  usedCount?: number;
  isActive?: boolean;
  error?: string;
}

Example:

const usage = await sdk.incrementUsage('MYCODE');

🎯 Discount Types

Percentage Discount

// 15% off
await sdk.createCode(DiscountType.PERCENTAGE, 15);

Fixed Amount Discount

// $50 off
await sdk.createCode(DiscountType.AMOUNT, 50);

🔒 Custom Codes

You can create codes with your own custom string:

// Create with custom code
const result = await sdk.createCode(
  DiscountType.PERCENTAGE,
  20,
  10,
  'SUMMER2024'  // Your custom code
);

// If code already exists and is available, it returns the existing code
// If code is fully used or inactive, it returns an error

⚙️ Configuration

Environment Variables

Database Connection

The SDK automatically connects to our centralized MongoDB database when you call init(). No configuration needed! All data is stored securely in our database.

Connection Troubleshooting:

If you get a connection error:

  1. Check your API Key and Client ID:

    • Make sure they're correct and active
    • Contact support if you need to reset them
  2. Network Issues:

    • Check your internet connection
    • Ensure your firewall allows outbound connections
    • Try again - connection errors are usually temporary
  3. Common Error Messages:

    • "Invalid API key or client ID": Check your credentials
    • "MongoDB connection failed": This is an internal error - contact support
    • "SDK not initialized": Make sure you called await sdk.init() first

❓ Need Help?

Get API Key

To get your API key and Client ID, email us at:

Include in your email:

  • Your name
  • Company name (if applicable)
  • Brief description of your use case

Support

For any questions, issues, or help with:

  • Getting API keys
  • Setting up your account
  • Technical support
  • Feature requests
  • Resetting credentials

Contact us: [email protected]


📝 Error Handling

Always check the success or isValid flag:

const result = await sdk.createCode(DiscountType.PERCENTAGE, 15);

if (result.success) {
  // Use result.code
  console.log('Code:', result.code);
} else {
  // Handle error
  console.error('Error:', result.error);
}

🔧 Advanced Usage

Direct Controller Access

For advanced use cases, you can use the controller directly:

import { connectDB, ReferralController, DiscountType } from 'coupan-code';

// Connect to centralized database (handled automatically)
await connectDB();

const result = await ReferralController.createCode(
  'client-id',
  DiscountType.PERCENTAGE,
  15,
  10
);

Note: connectDB() connects to our centralized database automatically. No MongoDB URI needed!


📦 Package Structure

coupan-code/
├── src/
│   ├── models/        # Database models
│   ├── services/      # Business logic
│   ├── controllers/   # API controllers
│   └── sdk.ts        # Main SDK class
└── dist/             # Compiled JavaScript

🧪 Testing

Run the test suite:

npm test

📄 License

ISC


🙏 Support & Contact

  • Email: [email protected]
  • For API Key Requests: Email us with subject "API Key Request for Coupan Code"

🔍 Why Choose Coupan Code?

  • Zero Configuration - No MongoDB setup needed, connects automatically
  • TypeScript Ready - Full TypeScript support with type definitions
  • Simple API - Easy-to-use SDK similar to AWS SDK pattern
  • Flexible Discounts - Percentage or fixed amount discounts
  • Usage Limits - Set maximum usage per code
  • Custom Codes - Use your own code strings
  • Production Ready - Connection pooling, retry logic, error handling
  • Well Documented - Comprehensive docs and examples

📦 Install

npm install coupan-code

🎯 Perfect For

  • E-commerce platforms
  • Shopping cart systems
  • Marketing campaigns
  • Affiliate programs
  • Loyalty programs
  • Reward systems
  • Promotional campaigns
  • Discount management

🔑 Keywords

This package helps with: referral codes, coupon codes, promo codes, discount codes, voucher codes, promotional codes, discount management, coupon management, referral system, promo code generator, discount generator, ecommerce discounts, shopping cart discounts, checkout discounts, marketing tools, affiliate tracking, loyalty rewards.


Made with ❤️ for easy referral code management