> ## Documentation Index
> Fetch the complete documentation index at: https://www.referly.so/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Create a Promotional Code

> Creates a promotional code against an existing coupon. `couponId` is always required — the coupon supplies the discount.

There are two ways to create a code:

- **Give it yourself.** Send `code` with the exact string you want. It must be unique within the program.
- **Have it generated.** Set `isAutoGenerated` to `true` and send `codeStructure` describing which pieces to combine — the affiliate's first name, last name, email prefix, the discount value, the coupon name, and/or random characters. An affiliate is required in this mode, and you can shape the result further with `prefix`, `randomCharsLength` and `randomCharsCase`.

Assign the code to an affiliate with `affiliateId` or `affiliateEmail` so their redemptions are tracked. Assigned codes are also connected to that affiliate's links automatically in the background.

Fires the `promotional_code.created` webhook.

## Creating Promotional Codes

Create promotional codes that customers can use at checkout. Each promotional code must be linked to an existing coupon.

### Manual vs Auto-Generated Codes

#### Manual Codes

Specify the exact code string you want to create:

```json theme={null}
{
  "couponId": "coupon_123",
  "code": "SAVE20",
  "affiliateId": "affiliate_456"
}
```

#### Auto-Generated Codes

Let the system generate codes based on a structure:

```json theme={null}
{
  "couponId": "coupon_123",
  "affiliateId": "affiliate_456",
  "isAutoGenerated": true,
  "codeStructure": {
    "firstName": true,
    "randomChars": true
  },
  "prefix": "SAVE",
  "randomCharsLength": 4,
  "randomCharsCase": "uppercase"
}
```

This would generate a code like: `SAVEJOHN8X4Z`

### Code Structure Options

When using auto-generated codes, you can combine:

* **firstName**: Include affiliate's first name
* **lastName**: Include affiliate's last name
* **email**: Include part of affiliate's email (before @)
* **discountAmount**: Include the discount value
* **couponName**: Include the coupon name
* **randomChars**: Add random characters

### Additional Settings

* **active**: Whether the code is currently active
* **expiresAt**: Expiration date for the code
* **maxRedemptions**: Maximum number of times the code can be used
* **firstTimeOrder**: Limit to first-time customers only
* **minimumAmount**: Minimum purchase amount required
* **limitToAffiliate**: Only the affiliate can use this code
* **limitToCustomers**: Restrict to specific customers

<Note>
  The coupon must exist before creating promotional codes. The promotional code
  inherits its discount properties from the parent coupon.
</Note>


## OpenAPI

````yaml POST /promotional-codes
openapi: 3.0.1
info:
  title: Referly API
  description: >-
    REST API for managing affiliates, referrals, sales, affiliate links, coupons
    and promotional codes in your Referly affiliate program.


    Every request must send `Authorization: Bearer <YOUR_API_KEY>`. The token is
    scoped to a single affiliate program, so no program ID is ever required in
    the request — every read and write is automatically limited to that program.


    Requests are rate limited per token, per endpoint and per method.
  version: 1.0.0
servers:
  - url: https://www.referly.so/api/v1
security:
  - bearerAuth: []
paths:
  /promotional-codes:
    post:
      summary: Create a promotional code
      description: >-
        Creates a promotional code against an existing coupon. `couponId` is
        always required — the coupon supplies the discount.


        There are two ways to create a code:


        - **Give it yourself.** Send `code` with the exact string you want. It
        must be unique within the program.

        - **Have it generated.** Set `isAutoGenerated` to `true` and send
        `codeStructure` describing which pieces to combine — the affiliate's
        first name, last name, email prefix, the discount value, the coupon
        name, and/or random characters. An affiliate is required in this mode,
        and you can shape the result further with `prefix`, `randomCharsLength`
        and `randomCharsCase`.


        Assign the code to an affiliate with `affiliateId` or `affiliateEmail`
        so their redemptions are tracked. Assigned codes are also connected to
        that affiliate's links automatically in the background.


        Fires the `promotional_code.created` webhook.
      requestBody:
        description: The promotional code to create
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/NewPromotionalCode'
        required: true
      responses:
        '200':
          description: >-
            The created promotional code, with its parent coupon and assigned
            affiliate.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PromotionalCode'
        '400':
          description: >-
            `couponId` was missing; `code` was missing and `isAutoGenerated` was
            not set; `isAutoGenerated` was set without an affiliate; or the
            resulting code already exists in this program.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: >-
            The coupon was not found in this program, or the affiliate was not
            found.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          description: The promotional code could not be created.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
components:
  schemas:
    NewPromotionalCode:
      type: object
      required:
        - couponId
      properties:
        couponId:
          type: string
          format: uuid
          description: The coupon ID this promotional code belongs to
        code:
          type: string
          description: >-
            The exact code string customers will type. Required unless
            `isAutoGenerated` is `true`. Must be unique within the program.
          example: JANE20
        affiliateId:
          type: string
          format: uuid
          description: >-
            Assign the code to this affiliate so their redemptions are credited.
            Required when `isAutoGenerated` is `true` unless `affiliateEmail` is
            supplied.
        affiliateEmail:
          type: string
          format: email
          description: >-
            Assign the code to the affiliate with this email address.
            Alternative to `affiliateId`.
        externalId:
          type: string
          description: >-
            The code's ID in the connected billing provider, for example a
            Stripe promotion code ID
        active:
          type: boolean
          description: 'Whether the code is active (default: true)'
        expiresAt:
          type: string
          format: date-time
          description: Expiration date
        maxRedemptions:
          type: integer
          description: Maximum redemptions
        firstTimeOrder:
          type: boolean
          description: 'Limit to first-time orders (default: false)'
        minimumAmount:
          type: number
          format: float
          description: Minimum purchase amount
        minimumAmountCurrency:
          type: string
          description: Currency for minimum amount
        limitToCustomers:
          type: boolean
          description: 'Limit to specific customers (default: false)'
        customerId:
          type: string
          description: Specific customer ID
        limitToAffiliate:
          type: boolean
          description: 'Only affiliate can use (default: false)'
        isAutoGenerated:
          type: boolean
          description: >-
            Generate the code from `codeStructure` instead of using `code`.
            Requires an affiliate.
        codeStructure:
          type: object
          description: >-
            Which pieces to combine into the generated code, in this order:
            first name, last name, email prefix, discount value, coupon name,
            then random characters. Required when `isAutoGenerated` is `true`.
          properties:
            firstName:
              type: boolean
              description: Include affiliate's first name
            lastName:
              type: boolean
              description: Include affiliate's last name
            email:
              type: boolean
              description: Include part of affiliate's email
            discountAmount:
              type: boolean
              description: Include discount value
            couponName:
              type: boolean
              description: Include coupon name
            randomChars:
              type: boolean
              description: Add random characters
        prefix:
          type: string
          description: String placed at the front of a generated code
        randomCharsLength:
          type: integer
          description: 'Length of random characters (default: 4)'
          default: 4
        randomCharsCase:
          type: string
          enum:
            - uppercase
            - lowercase
            - mixed
          description: 'Case for random characters (default: mixed)'
          default: mixed
    PromotionalCode:
      type: object
      properties:
        id:
          type: string
          format: uuid
          description: The promotional code ID
        code:
          type: string
          description: The actual promotional code string
        couponId:
          type: string
          format: uuid
          description: The parent coupon ID
        affiliateId:
          type: string
          format: uuid
          nullable: true
          description: The affiliate ID this code is assigned to
        externalId:
          type: string
          nullable: true
          description: External ID (e.g., Stripe promotion code ID)
        active:
          type: boolean
          description: Whether the promotional code is active
        expiresAt:
          type: string
          format: date-time
          nullable: true
          description: Expiration date for the code
        maxRedemptions:
          type: integer
          nullable: true
          description: >-
            How many times this code can be redeemed. `null` means unlimited.
            Redemptions are also capped by the parent coupon's own limit.
        timesRedeemed:
          type: integer
          description: Number of times this code has been redeemed
        firstTimeOrder:
          type: boolean
          description: Whether this code is limited to first-time orders
        minimumAmount:
          type: number
          format: float
          nullable: true
          description: Minimum purchase amount required
        minimumAmountCurrency:
          type: string
          nullable: true
          description: Currency for minimum amount
        limitToCustomers:
          type: boolean
          description: Whether code is limited to specific customers
        customerId:
          type: string
          nullable: true
          description: Specific customer ID this code is limited to
        limitToAffiliate:
          type: boolean
          description: Whether only the assigned affiliate may redeem this code
        isAutoGenerated:
          type: boolean
          description: >-
            Whether this code was generated from a `codeStructure` rather than
            supplied by hand
        createdAt:
          type: string
          format: date-time
          description: Timestamp when the code was created
        updatedAt:
          type: string
          format: date-time
          description: Timestamp when the code was last updated
        coupon:
          description: The coupon this code takes its discount from
          allOf:
            - $ref: '#/components/schemas/Coupon'
        affiliate:
          type: object
          nullable: true
          properties:
            id:
              type: string
              format: uuid
            firstName:
              type: string
            lastName:
              type: string
            email:
              type: string
              format: email
          description: Affiliate details
        isAffiliateGenerated:
          type: boolean
          description: Whether the affiliate created this code themselves from their portal
      description: >-
        A code customers enter at checkout. Its discount comes from the coupon
        it belongs to.
    Error:
      type: object
      properties:
        error:
          type: string
          description: Human readable description of what went wrong
    Coupon:
      type: object
      description: >-
        A discount definition. Promotional codes point at a coupon for their
        value.
      properties:
        id:
          type: string
          format: uuid
          description: The coupon ID
        name:
          type: string
          nullable: true
          description: Name of the coupon
        externalId:
          type: string
          nullable: true
          description: >-
            The coupon's ID in the connected billing provider, for example a
            Stripe coupon ID
        couponType:
          type: string
          enum:
            - PERCENTAGE
            - FLAT
          description: Whether the discount is a percentage or a fixed amount
        percentOff:
          type: number
          format: float
          nullable: true
          description: Percentage taken off, 1–100. Used when `couponType` is `PERCENTAGE`.
        amountOff:
          type: number
          format: float
          nullable: true
          description: Fixed amount taken off. Used when `couponType` is `FLAT`.
        currency:
          type: string
          nullable: true
          description: Currency for `amountOff`, for example `USD`
        duration:
          type: string
          enum:
            - once
            - forever
            - repeating
          description: How long the discount keeps applying to a subscription
        durationInMonths:
          type: integer
          nullable: true
          description: >-
            Number of months the discount repeats for. Only set when `duration`
            is `repeating`.
        maxRedemptions:
          type: integer
          nullable: true
          description: >-
            Total redemptions allowed across every promotional code on this
            coupon. `null` means unlimited.
        timesRedeemed:
          type: integer
          description: How many times this coupon has been redeemed so far
        couponCategory:
          type: string
          enum:
            - CUSTOMER
            - PAYOUT
          description: >-
            Whether the coupon discounts customers or is used to pay affiliates
            as a non-cash reward
        limitToProducts:
          type: boolean
          description: Whether the coupon only applies to `productIds`
        productIds:
          type: array
          items:
            type: string
          description: Products the coupon is restricted to
        collectionIds:
          type: array
          items:
            type: string
          description: Collections the coupon is restricted to
        valid:
          type: boolean
          description: Whether the coupon can currently be redeemed
        redeemBy:
          type: string
          format: date-time
          nullable: true
          description: Last date the coupon can be redeemed
        integrationType:
          type: string
          enum:
            - NONE
            - STRIPE
            - CHARGEBEE
            - PADDLE
            - SHOPIFY
            - WOOCOMMERCE
            - ZYLVIE
            - POLAR
          nullable: true
          description: The billing provider this coupon is synced with
        affiliateProgramId:
          type: string
          format: uuid
          description: The affiliate program this coupon belongs to
        createdAt:
          type: string
          format: date-time
          description: When the coupon was created
        updatedAt:
          type: string
          format: date-time
          description: When the coupon was last updated
        promotionalCodes:
          type: array
          items:
            $ref: '#/components/schemas/PromotionalCode'
          description: Promotional codes that point at this coupon
        autoCouponRule:
          type: object
          nullable: true
          description: >-
            Rule used to generate codes automatically for affiliates, if
            configured
  responses:
    Unauthorized:
      description: >-
        The `Authorization` header is missing, is not a `Bearer` header, or the
        token is not valid.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Forbidden:
      description: API access is not enabled for this account.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    RateLimited:
      description: Too many requests for this token on this endpoint. Please slow down.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer

````