Coupons


Coupons are a powerful tool for offering discounts on your products and services. A coupon object contains information about a specific discount, such as a percentage off or a fixed amount off. To make a coupon redeemable, you must associate it with one or more Promotion Codes. This API allows you to create, manage, and track the usage of coupons.

Create a Coupon#

Creates a new coupon. You can optionally create one or more promotion codes to associate with this coupon in the same request.

Parameters#

name
string
required

The coupon’s name, meant to be displayable to the customer. For example, SUMMER25.

percent_off
number

A positive integer between 1 and 100 that represents the percentage of the subscription invoice subtotal that will be discounted. Either percent_off or amount_off is required.

amount_off
string

A positive decimal that represents the amount of discount that will be applied to an invoice. Either percent_off or amount_off is required. Requires currency_id to be set.

currency_id
string

The ID of the currency that the amount_off is in. Required if amount_off is set.

duration
string
required

Specifies how long the discount will be in effect. Can be once, repeating, or forever.

duration_in_months
number

If duration is repeating, the number of months the coupon applies. Required if duration is repeating.

max_redemptions
number

A positive integer specifying the maximum number of times the coupon can be redeemed. Leaving this blank will allow the coupon to be redeemed an unlimited number of times.

redeem_by
number

Unix timestamp specifying the last time at which the coupon can be redeemed. After this time, the coupon can no longer be applied to new customers.

applies_to
object

A hash containing product IDs that this coupon applies to.

1 subfields
currency_options
object

When amount_off is specified, this hash can be used to configure per-currency coupon amounts. If a customer's currency matches a key in the hash, the value of that key will be used as the discount amount.

metadata
object

Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format.

promotion_codes
array

An array of promotion code objects to create and attach to this coupon. See details below.

promotion_codes Object Properties

code
string

The customer-facing code. If left blank, a random code will be generated.

description
string

An optional description for the promotion code.

max_redemptions
number

The maximum number of times this specific promotion code can be redeemed.

expires_at
number

Unix timestamp specifying when the promotion code expires.

Returns#

Returns an object containing the newly created coupon and an array of promotion_codes.

object
2 subfields

Example#

Create a Coupon

import payment from '@blocklet/payment-js';

async function createCoupon() {
  try {
    const result = await payment.coupons.create({
      name: '20% Off First Month',
      percent_off: 20,
      duration: 'once',
      max_redemptions: 100,
      promotion_codes: [
        {
          code: 'NEWUSER20',
          description: 'Discount for new users',
          max_redemptions: 50,
          expires_at: Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60, // 30 days from now
        },
      ],
    });
    console.log('Coupon created:', result.coupon);
    console.log('Promotion codes:', result.promotion_codes);
  } catch (error) {
    console.error('Error creating coupon:', error);
  }
}

See all 1 lines

Example Response#

{
  "coupon": {
    "id": "coupon_12345",
    "name": "20% Off First Month",
    "percent_off": 20,
    "amount_off": null,
    "currency_id": null,
    "duration": "once",
    "duration_in_months": null,
    "max_redemptions": 100,
    "times_redeemed": 0,
    "valid": true,
    "livemode": false,
    "created_at": "2023-10-27T10:00:00.000Z",
    "updated_at": "2023-10-27T10:00:00.000Z"
  },
  "promotion_codes": [
    {
      "id": "promo_67890",
      "coupon_id": "coupon_12345",
      "code": "NEWUSER20",
      "description": "Discount for new users",
      "active": true,
      "max_redemptions": 50,
      "times_redeemed": 0,

See all 5 lines

Retrieve a Coupon#

Retrieves the coupon with the given ID. The response includes associated promotion codes and any products the coupon applies to.

Parameters#

id
string
required
The ID of the coupon to retrieve.

Returns#

Returns a coupon object if a valid ID was provided. Returns an error otherwise.

object
The retrieved coupon object, expanded with related promotion codes and applied products.

Example#

Retrieve a Coupon

import payment from '@blocklet/payment-js';

async function retrieveCoupon(couponId) {
  try {
    const coupon = await payment.coupons.retrieve(couponId);
    console.log('Retrieved coupon:', coupon);
  } catch (error) {
    console.error('Error retrieving coupon:', error);
  }
}

retrieveCoupon('coupon_12345');

Example Response#

{
  "id": "coupon_12345",
  "name": "20% Off First Month",
  "percent_off": 20,
  "duration": "once",
  "valid": true,
  "promotion_codes": [
    {
      "id": "promo_67890",
      "code": "NEWUSER20",
      "active": true
    }
  ],
  "applied_products": []
}

Update a Coupon#

Updates the specified coupon by setting the values of the parameters passed. Any parameters not provided will be left unchanged.

Parameters#

id
string
required
The ID of the coupon to update.
name
string

The coupon’s name.

description
string

An optional description for the coupon.

max_redemptions
number

The maximum number of times the coupon can be redeemed.

redeem_by
number

Unix timestamp specifying the last time at which the coupon can be redeemed.

valid
boolean

Whether the coupon is currently valid.

currency_options
object

Update per-currency coupon amounts.

metadata
object

Set of key-value pairs to update on the object.

Returns#

Returns the updated coupon object.

object
The updated coupon object.

Example#

Update a Coupon

import payment from '@blocklet/payment-js';

async function updateCoupon(couponId) {
  try {
    const updatedCoupon = await payment.coupons.update(couponId, {
      name: 'Summer Sale 2024',
      metadata: { campaign: 'summer-2024' },
    });
    console.log('Coupon updated:', updatedCoupon);
  } catch (error) {
    console.error('Error updating coupon:', error);
  }
}

updateCoupon('coupon_12345');

Example Response#

{
  "id": "coupon_12345",
  "name": "Summer Sale 2024",
  "percent_off": 20,
  "duration": "once",
  "valid": true,
  "metadata": {
    "campaign": "summer-2024"
  }
}

List all Coupons#

Returns a list of your coupons.

Parameters#

valid
boolean
Filter coupons by their validity.
name
string
Filter coupons by name.
page
number
default:1
The page number to retrieve.
pageSize
number
default:20
The number of items to retrieve per page.

Returns#

An object with a list property containing an array of coupons, a count property with the total number of coupons, and a paging object.

object
3 subfields

Example#

List Coupons

import payment from '@blocklet/payment-js';

async function listCoupons() {
  try {
    const coupons = await payment.coupons.list({ valid: true, pageSize: 5 });
    console.log('Found coupons:', coupons.list);
  } catch (error) {
    console.error('Error listing coupons:', error);
  }
}

listCoupons();

Example Response#

{
  "count": 25,
  "list": [
    {
      "id": "coupon_12345",
      "name": "Summer Sale 2024",
      "percent_off": 20,
      "valid": true
    },
    {
      "id": "coupon_67890",
      "name": "10 USD Off",
      "amount_off": "1000",
      "valid": true
    }
  ],
  "paging": {
    "page": 1,
    "pageSize": 5
  }
}

Delete a Coupon#

You can delete coupons via the API. Deleting a coupon will prevent it from being applied to any future subscriptions. It will not, however, remove it from any subscriptions it has already been applied to.

Parameters#

id
string
required
The ID of the coupon to delete.

Returns#

Returns the deleted coupon object. If the coupon has been used, it cannot be deleted and will throw an error.

object
The deleted coupon object.

Example#

Delete a Coupon

import payment from '@blocklet/payment-js';

async function deleteCoupon(couponId) {
  try {
    const deletedCoupon = await payment.coupons.del(couponId);
    console.log('Coupon deleted:', deletedCoupon.id);
  } catch (error) {
    console.error('Error deleting coupon:', error);
  }
}

deleteCoupon('coupon_abcde');

Example Response#

{
  "id": "coupon_abcde",
  "name": "Temporary Discount",
  "percent_off": 15,
  "valid": false
}

Check if Coupon is Used#

Checks whether a coupon has been redeemed at least once.

Parameters#

id
string
required
The ID of the coupon to check.

Returns#

An object containing a boolean used property.

used
boolean
True if the coupon has been redeemed, false otherwise.

Example#

Check Coupon Usage

import payment from '@blocklet/payment-js';

async function checkCouponUsage(couponId) {
  try {
    const result = await payment.coupons.used(couponId);
    console.log(`Is coupon ${couponId} used?`, result.used);
  } catch (error) {
    console.error('Error checking coupon usage:', error);
  }
}

checkCouponUsage('coupon_12345');

Example Response#

{
  "used": true
}

Get Coupon Redemptions#

Retrieves detailed analytics about a coupon's redemptions, including which customers or subscriptions have used it.

Parameters#

id
string
required
The ID of the coupon.
type
string

The type of redemption data to retrieve. Can be customer or subscription.

page
number
default:1
The page number to retrieve.
pageSize
number
default:20
The number of items to retrieve per page.

Returns#

Returns a data object with redemption details.

object
4 subfields

Example#

Get Coupon Redemptions

import payment from '@blocklet/payment-js';

async function getRedemptions(couponId) {
  try {
    const redemptions = await payment.coupons.redemptions(couponId, {
      type: 'customer',
      pageSize: 10,
    });
    console.log('Total redemptions:', redemptions.count);
    console.log('Customers who redeemed:', redemptions.customers);
  } catch (error) {
    console.error('Error getting redemptions:', error);
  }
}

getRedemptions('coupon_12345');

Example Response#

{
  "count": 1,
  "subscriptions": [],
  "customers": [
    {
      "id": "cus_abc123",
      "did": "did:abt:z123...",
      "email": "customer@example.com",
      "name": "Test Customer",
      "coupon_usage_stats": {
        "coupon_12345": 1
      }
    }
  ],
  "paging": {
    "page": 1,
    "pageSize": 10
  }
}