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

# Purchase Grant

> Create an ad-hoc invoice with a payment session for a grant purchase. The customer pays via the returned payment URL; the grant is created automatically on payment completion. If payment expires, the invoice is cancelled and no grant is created.

To confirm payment completion, subscribe to the `invoice.paid.v0` webhook. The payload includes the original `invoiceId` and the created `grantId`, so you can correlate the purchase response with downstream fulfilment without an extra fetch. As a fallback if you cannot consume webhooks, poll `GET /v2/invoices/{invoiceId}` (interval 2s, timeout 60s) and check for `status === "PAID"`.



## OpenAPI

````yaml /openapi.json post /v1/entitlements/{entitlementId}/grants/purchase
openapi: 3.1.0
info:
  title: Paygentic API
  version: 0.1.0
  description: >
    The Paygentic API provides a comprehensive platform for building and scaling
    monetization infrastructure.


    ## Authentication

    All API requests require authentication using an API key passed in the
    `Authorization` header:

    ```

    Authorization: Bearer YOUR_API_KEY

    ```


    ## Base URL

    All API requests should be made to:

    ```

    https://api.paygentic.io/v0

    ```
  contact:
    name: Paygentic Support
    email: support@paygentic.io
  license:
    name: Proprietary
servers:
  - url: https://api.paygentic.io
    description: Production API
  - url: https://api.sandbox.paygentic.io
    description: Sandbox API
security:
  - BearerAuth: []
tags:
  - name: Customers
    description: >-
      A `Customer` is an entity connected to a `Merchant` via a `Subscription`.
      This represents the merchant-facing perspective of `Consumers` who
      purchase their `Products`.
  - name: Billable Metrics
    description: >-
      A `Billable Metric` defines a measurable quantity tied to a `Product`'s
      consumption. Each metric stores details including its label, an
      explanatory description, and measurement units.
  - name: Grants
    description: >-
      Grants credit a customer's metered entitlement balance. Merchants can
      create grants directly or void existing ones.


      Use `GET /v1/entitlements?customerId={id}` or `GET
      /v1/entitlements?subscriptionId={id}` to find the metered entitlement `id`
      needed for these endpoints.
  - name: Features
    description: >-
      A `Feature` represents a specific capability or functionality provided by
      a `Product`. Features can be metered (usage-based), static (fixed
      allocation), or boolean (enabled/disabled).
  - name: Fees
    description: >-
      A `Fee` defines a recurring or one-time charge tied to a `Product`. Fees
      are linked to prices, and cadence is defined on the Price.
  - name: Plans
    description: >-
      A `Plan` links a collection of `Prices` to a `Product`. It functions as a
      pricing structure document for a particular feature set or service
      offering.
  - name: Prices
    description: >-
      A `Price` determines the monetary value for a single unit of a `Billable
      Metric`. Prices are exclusively grouped within a `Plan`.
  - name: Products
    description: >-
      A `Product` is an offering sold by a `Merchant`. It includes product
      metadata like title, summary, and pricing details. `Plans`, `Prices`, and
      `Subscriptions` are all associated with products.
  - name: Sources
    description: >-
      A `Source` is an external data provider capable of automatically creating
      usage events. Configuration occurs at the plan level, enabling data
      retrieval from third-party platforms such as Stripe to produce billable
      events.
  - name: Subscriptions
    description: >-
      A `Subscription` is a customer's commitment to purchase a `Product`
      following the terms of a `Plan` and its linked `Prices`.
  - name: Users
    description: >-
      A `User` is an entity granted access to an Organization's resources. All
      operations are performed by users.
  - name: Invoices V2
    description: >-
      Invoice V2 operations supporting billing cycles organized by time periods.
      Warning: v0 invoice endpoints are no longer supported.
  - name: Revenue
    description: Revenue data from invoices and payments
  - name: Profitability
    description: Per-customer profitability summaries
  - name: Test Clocks
    description: >-
      Test clocks provide programmable time control to simulate subscription and
      billing scenarios during testing.
  - name: Events
    description: Ingest raw metering events that are processed by the meters service.
  - name: Payments
    description: >-
      Create and manage one-off payments. A payment represents a single charge
      that a merchant wants to collect from a customer.
  - name: Payment Sessions
    description: >-
      Handle payment session lifecycle and processing across various entity
      types including invoices and subscriptions
  - name: Costs
    description: >-
      A Cost represents the operational or infrastructure expense of serving
      customers for a given product. Costs are metered (driven by event-based
      usage) and are tracked in parallel with billable metrics to give merchants
      visibility into both revenue and cost per customer.
  - name: ExternalReferences
    description: >-
      An `ExternalReference` links a Paygentic entity (e.g. an `Item`) to a
      record in an external system such as Salesforce or NetSuite. Multiple
      external records may map to the same Paygentic entity, but each external
      id is the *primary* reference of at most one entity per merchant.
  - name: Items
    description: >-
      An `Item` is the canonical "thing you sell" that external-system mappings
      point at. It is fully decoupled from the billing `Product` and holds no
      pricing/plan/metering, and it is CRM/ERP agnostic — which providers map to
      it lives entirely in its `ExternalReference` rows.
  - name: MerchantIntegrations
    description: >-
      A `MerchantIntegration` records a merchant's connection to an external
      provider. One connection per `(merchant, provider)` — re-connecting
      upserts in place.
  - name: Approvals
    description: Submit, decide, cancel, and read maker-checker approvals.
  - name: Orders
    description: Manage Orders, their line items, and billing schedules.
  - name: Billing Schedules
    description: >-
      Owner-polymorphic billing schedules with intervals and staged invoice
      projections. A BillingSchedule belongs to exactly one Order or one
      Subscription (XOR). Cadence lives on ScheduleIntervals
      (cadence-on-the-line).
paths:
  /v1/entitlements/{entitlementId}/grants/purchase:
    parameters:
      - name: entitlementId
        in: path
        required: true
        description: The unique identifier of the entitlement
        schema:
          type: string
          pattern: ^ent_[a-zA-Z0-9]+$
    post:
      tags:
        - Grants
      summary: Purchase Grant
      description: >-
        Create an ad-hoc invoice with a payment session for a grant purchase.
        The customer pays via the returned payment URL; the grant is created
        automatically on payment completion. If payment expires, the invoice is
        cancelled and no grant is created.


        To confirm payment completion, subscribe to the `invoice.paid.v0`
        webhook. The payload includes the original `invoiceId` and the created
        `grantId`, so you can correlate the purchase response with downstream
        fulfilment without an extra fetch. As a fallback if you cannot consume
        webhooks, poll `GET /v2/invoices/{invoiceId}` (interval 2s, timeout 60s)
        and check for `status === "PAID"`.
      operationId: purchaseEntitlementGrant
      parameters:
        - name: entitlementId
          in: path
          required: true
          schema:
            type: string
            pattern: ^ent_[a-zA-Z0-9]+$
          description: The unique identifier of the entitlement to purchase credits for.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PurchaseGrantRequest'
            examples:
              basic:
                summary: Basic grant purchase
                description: Purchase 1000 credits for $5.00 with a unique idempotency key.
                value:
                  amount: 1000
                  price: '5.00'
                  idempotencyKey: purchase-march-2026-topup
              withOptions:
                summary: Grant purchase with all options
                description: >-
                  Purchase with redirect URLs, payment expiry, and grant
                  expiration.
                value:
                  amount: 500
                  price: '2.50'
                  idempotencyKey: purchase-promo-500
                  effectiveAt: '2026-03-14T00:00:00Z'
                  expiresAt: '2026-04-14T00:00:00Z'
                  successUrl: https://example.com/success
                  cancelUrl: https://example.com/cancel
                  paymentExpiresAt: '2026-03-15T00:00:00Z'
      responses:
        '201':
          description: Grant purchase invoice created with payment session.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PurchaseGrantResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '500':
          $ref: '#/components/responses/InternalServerError'
components:
  schemas:
    PurchaseGrantRequest:
      type: object
      required:
        - amount
        - price
        - idempotencyKey
      properties:
        amount:
          type: number
          exclusiveMinimum: 0
          exclusiveMaximum: 1000000000000
          multipleOf: 1.e-8
          description: The number of credits to grant upon payment completion.
        price:
          type: string
          pattern: ^\d+(\.\d{1,9})?$
          description: >-
            The price in decimal format (e.g., '5.00' for $5.00 USD). A
            non-negative decimal with at most 9 fractional digits (nanodollar
            precision). Must be at least $0.50 and must not exceed 4503599.62
            (the maximum supported grant purchase amount).
        idempotencyKey:
          type: string
          minLength: 1
          maxLength: 255
          description: >-
            Caller-provided deduplication key. Retrying with the same key
            returns the existing invoice.
        effectiveAt:
          type: string
          format: date-time
          description: When the grant becomes effective. Defaults to now.
        expiresAt:
          type: string
          format: date-time
          nullable: true
          description: When the grant expires. If omitted, the grant does not expire.
        successUrl:
          type: string
          format: uri
          description: URL to redirect the customer to after successful payment.
        cancelUrl:
          type: string
          format: uri
          description: URL to redirect the customer to if payment is cancelled.
        paymentExpiresAt:
          type: string
          format: date-time
          description: >-
            When the payment session expires. If omitted, uses the default
            expiry.
        resetMaxRollover:
          type: number
          minimum: 0
          maximum: 999999999999
          description: >-
            Maximum balance carried over at the entitlement's reset boundary. If
            omitted, the purchased grant balance rolls over until consumed or
            expired. Set to 0 to discard any remaining balance at each reset.
            Ignored when the target entitlement has no `usagePeriod` (one-time
            entitlement) — one-time entitlements have no reset boundary, so this
            field has no effect.
        resetMinRollover:
          type: number
          minimum: 0
          maximum: 999999999999
          description: >-
            Minimum balance at the entitlement's reset boundary; balances below
            this are floored up. Defaults to 0 (no floor). Ignored when the
            target entitlement has no `usagePeriod` (one-time entitlement).
    PurchaseGrantResponse:
      type: object
      required:
        - object
        - invoiceId
        - entitlementId
        - grantAmount
        - price
        - currency
        - paymentSessions
      properties:
        object:
          type: string
          enum:
            - grant_purchase
          default: grant_purchase
        invoiceId:
          type: string
          pattern: ^inv_[a-f0-9]+$
          description: The invoice ID for this grant purchase.
        entitlementId:
          type: string
          pattern: ^ent_[a-zA-Z0-9]+$
          description: The entitlement that will receive the grant.
        grantAmount:
          type: number
          exclusiveMinimum: 0
          description: The number of credits that will be granted on payment.
        price:
          type: string
          description: The price in decimal format (e.g., '5.00').
        currency:
          type: string
          description: The three-letter ISO 4217 currency code (e.g., 'usd').
        paymentSessions:
          type: array
          items:
            type: object
            required:
              - url
            properties:
              url:
                type: string
                format: uri
                description: The Stripe checkout URL for the customer to complete payment.
              expiresAt:
                type: string
                format: date-time
                nullable: true
                description: When the payment session expires.
              amount:
                type: number
                description: The payment amount in the currency's minor unit (e.g., cents).
          description: Payment session(s) for the customer to complete the purchase.
    Error:
      type: object
      required:
        - message
      properties:
        error:
          type: string
          description: >-
            Coarse HTTP error category (e.g. 'bad_request', 'forbidden'). Maps
            to the HTTP status code.
        message:
          type: string
          description: >-
            Human-readable error message. Clients must not parse this field
            programmatically.
        code:
          type: string
          examples:
            - TAX_NOT_ENABLED
            - PAYMENT_SESSION_EXPIRED
          description: >-
            Optional semantic business error code for machine-readable
            discrimination (e.g. 'TAX_NOT_ENABLED'). UPPER_SNAKE_CASE. Clients
            should check this field, not message.
        details:
          type: object
          description: Additional error details
          additionalProperties: true
      example:
        message: The requested resource was not found
        error: not_found
    ValidationError:
      type: object
      required:
        - message
        - errors
      properties:
        error:
          type: string
          enum:
            - validation_error
          default: validation_error
          description: Error type indicating validation failure
        message:
          type: string
          description: Human-readable error message
        errors:
          type: array
          items:
            type: object
            properties:
              field:
                type: string
                description: The field that failed validation
              message:
                type: string
                description: Validation error message for this field
              code:
                type: string
                description: Validation error code
            required:
              - field
              - message
          description: Array of field-specific validation errors
      example:
        message: Validation failed
        error: validation_error
        errors:
          - field: email
            message: Invalid email format
            code: invalid_format
  responses:
    BadRequest:
      description: >-
        Bad Request - The request could not be understood or was missing
        required parameters
      content:
        application/json:
          schema:
            oneOf:
              - $ref: '#/components/schemas/Error'
              - $ref: '#/components/schemas/ValidationError'
    Forbidden:
      description: Forbidden - Request is understood but refused
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    NotFound:
      description: Not Found - The requested resource could not be found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Conflict:
      description: Conflict - The request conflicts with the current state of the resource
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    InternalServerError:
      description: Internal Server Error - Something went wrong on the server side
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      description: API key authentication

````