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

# Get subscription contract analytics and revenue metrics

> Retrieves comprehensive analytics for a specific subscription contract, including total revenue generated, number of successful orders, and formatted revenue display. This endpoint provides key performance metrics for understanding the financial impact of individual subscriptions.

**What This Endpoint Returns:**
Financial and operational analytics for a single subscription contract, calculated from all successful billing attempts throughout the subscription's lifetime. Unlike realtime contract queries, this provides historical aggregated data.

**Metrics Included:**

**Revenue Metrics:**
- **totalOrderAmount**: Total revenue in decimal format (e.g., 299.95)
- **totalOrderRevenue**: Formatted currency string (e.g., "$299.95")
- Calculated from all SUCCESS status billing attempts
- Includes taxes, shipping, and discounts
- Does NOT include failed or pending payments

**Order Count:**
- **totalOrders**: Count of successful billing attempts
- Represents number of orders generated by subscription
- Does NOT include failed billing attempts
- Starts at 0 for brand new subscriptions

**Currency Formatting:**
- Uses shop's configured money_format
- Respects shop's currency code (USD, EUR, GBP, etc.)
- Handles currency symbols and decimal places correctly
- Falls back to USD if currency unknown

**Calculation Logic:**

**Data Source:**
```sql
SELECT 
  COUNT(*) as totalOrders,
  SUM(order_amount) as totalOrderAmount
FROM subscription_billing_attempt
WHERE shop = ? 
  AND contract_id = ?
  AND status = 'SUCCESS'
```

**What Gets Counted:**
- ✅ Initial subscription order
- ✅ All successful recurring orders
- ✅ Manual billing attempts that succeeded
- ✅ Retry attempts that eventually succeeded
- ❌ Failed payment attempts
- ❌ Skipped billing cycles
- ❌ Cancelled/voided orders
- ❌ Pending/in-progress billing

**Use Cases:**

**1. Customer Lifetime Value:**
- Calculate total revenue from specific customer
- Measure subscription ROI
- Identify high-value subscriptions
- Track revenue growth over time

**2. Subscription Performance:**
- Analyze revenue per subscription
- Compare subscriptions by total value
- Identify most profitable subscription types
- Calculate average order value

**3. Customer Portal:**
- Display "You've saved $XXX" messaging
- Show "X orders delivered" stats
- Celebrate subscription milestones
- Build customer loyalty through transparency

**4. Reporting & Analytics:**
- Build subscription revenue dashboards
- Generate customer value reports
- Track subscription health metrics
- Forecast future revenue

**5. Business Intelligence:**
- Segment customers by subscription value
- Identify churn risk (low order count)
- Calculate retention rates
- Measure subscription program success

**Response Format:**
```json
{
  "totalOrders": 12,
  "totalOrderAmount": 599.88,
  "totalOrderRevenue": "$599.88"
}
```

**Response Fields:**
- `totalOrders` (integer): Count of successful billing attempts
- `totalOrderAmount` (decimal): Numeric revenue total
- `totalOrderRevenue` (string): Formatted currency display

**Example Scenarios:**

**Brand New Subscription:**
```json
{
  "totalOrders": 0,
  "totalOrderAmount": 0.00,
  "totalOrderRevenue": "$0.00"
}
```

**After First Successful Order:**
```json
{
  "totalOrders": 1,
  "totalOrderAmount": 49.99,
  "totalOrderRevenue": "$49.99"
}
```

**Established Subscription (EUR):**
```json
{
  "totalOrders": 24,
  "totalOrderAmount": 1199.76,
  "totalOrderRevenue": "€1.199,76"
}
```

**Integration Examples:**

**Customer Portal - Loyalty Display:**
```javascript
const analytics = await fetch(
  `/api/external/v2/subscription-contract-details/analytics/${contractId}`,
  { headers: { 'X-API-Key': 'your-key' } }
).then(r => r.json());

const loyaltyMessage = `
  <div class="loyalty-badge">
    <h3>Thank you for your loyalty!</h3>
    <p>You've received ${analytics.totalOrders} orders</p>
    <p>Total value: ${analytics.totalOrderRevenue}</p>
  </div>
`;
```

**Revenue Dashboard:**
```javascript
// Fetch analytics for multiple subscriptions
const contractIds = [123, 456, 789];
const analyticsPromises = contractIds.map(id => 
  getContractAnalytics(id)
);

const allAnalytics = await Promise.all(analyticsPromises);
const totalRevenue = allAnalytics.reduce(
  (sum, a) => sum + a.totalOrderAmount, 0
);

console.log(`Total subscription revenue: $${totalRevenue.toFixed(2)}`);
```

**Important Considerations:**

**Data Accuracy:**
- Based on Appstle's billing attempt records
- May differ slightly from Shopify order totals
- Includes only what Appstle successfully billed
- Updated after each billing attempt completes

**Currency Handling:**
- Formatting uses shop's money_format setting
- Different shops may have different decimal separators
- Currency symbol placement varies by locale
- Always use totalOrderAmount for calculations

**Performance:**
- Fast database aggregation query
- Typical response time: 100-300ms
- Indexed by shop and contract ID
- Suitable for real-time display

**Best Practices:**

1. **Use for Display**: Use totalOrderRevenue for customer-facing display
2. **Calculate with Amount**: Use totalOrderAmount for mathematical operations
3. **Cache Strategically**: Cache for dashboards, fetch real-time for critical displays
4. **Handle Zero**: Gracefully handle new subscriptions with 0 orders
5. **Validate Contract**: Ensure contract exists before querying analytics

**Limitations:**

**What's NOT Included:**
- Future projected revenue
- Failed payment attempt counts
- Refunds or chargebacks
- Pending/processing orders
- Orders from other subscriptions

**Related Calculations:**

**Average Order Value:**
```javascript
const aov = analytics.totalOrderAmount / analytics.totalOrders;
console.log(`Average order value: $${aov.toFixed(2)}`);
```

**Customer Lifetime Value (projected):**
```javascript
const monthsActive = calculateMonthsActive(contract.createdAt);
const monthlyRevenue = analytics.totalOrderAmount / monthsActive;
const projectedLTV = monthlyRevenue * 12; // Annual LTV
```

**Authentication:** Requires valid X-API-Key header



## OpenAPI

````yaml /subscription/admin-api-swagger.json get /api/external/v2/subscription-contract-details/analytics/{contractId}
openapi: 3.0.1
info:
  description: >-
    Comprehensive API documentation for managing subscriptions, payments, and
    related operations. These APIs allow you to programmatically manage
    subscription lifecycles, handle payments, configure products, and integrate
    subscription functionality into your applications.
  title: Admin APIs
  version: 0.0.1
servers:
  - url: https://subscription-admin.appstle.com
security: []
tags:
  - description: >-
      Core APIs for managing the complete subscription lifecycle including
      creation, updates, pausing, resuming, and cancellation of subscriptions.
    name: Subscription Management
  - description: >-
      APIs for managing subscription payment methods, processing payments,
      handling payment retries, and updating billing information.
    name: Subscription Payments
  - description: >-
      APIs for managing subscription contracts including delivery schedules,
      pricing, order notes, billing cycles, and shipping addresses.
    name: Subscription Contracts
  - description: >-
      APIs for managing products within subscriptions including adding,
      removing, updating quantities, and swapping products.
    name: Subscription Products
  - description: >-
      APIs for handling billing operations, payment processing, and financial
      transactions related to subscriptions.
    name: Billing & Payments
  - description: >-
      APIs for managing discounts and promotional codes applied to
      subscriptions.
    name: Subscription Discounts
  - description: >-
      APIs for managing one-time add-on products that can be purchased alongside
      recurring subscription items.
    name: Subscription One-Time Products
  - description: >-
      APIs for managing subscription plans, pricing tiers, and plan
      configurations.
    name: Subscription Plans
  - description: >-
      APIs for managing customizable product boxes and bundles where customers
      can select multiple items.
    name: Build-a-Box & Bundles
  - description: >-
      APIs for managing the product catalog including product information,
      variants, and inventory.
    name: Product Catalog
  - description: >-
      APIs for managing operational settings, configurations, and administrative
      functions.
    name: Operations & Settings
  - description: >-
      APIs powering the customer-facing portal where subscribers can manage
      their own subscriptions.
    name: Customer Portal
  - description: APIs for managing customer information, profiles, and account details.
    name: Customers
  - description: >-
      APIs for retrieving aggregated subscription data, customer subscription
      history, and account-level subscription information.
    name: Subscription Data
  - description: >-
      APIs for managing delivery profiles, shipping rates, free shipping
      configuration, and delivery method options on subscriptions.
    name: Delivery & Shipping
  - description: >-
      APIs for managing storefront customization including custom CSS, theme
      settings, label translations, and merchant-defined widget configuration.
    name: Customization
  - description: >-
      APIs for configuring cancellation flows, retention offers, cancellation
      reason management, and win-back automation.
    name: Customer Retention
paths:
  /api/external/v2/subscription-contract-details/analytics/{contractId}:
    get:
      tags:
        - Subscription Management
        - Subscription Contracts
      summary: Get subscription contract analytics and revenue metrics
      description: >-
        Retrieves comprehensive analytics for a specific subscription contract,
        including total revenue generated, number of successful orders, and
        formatted revenue display. This endpoint provides key performance
        metrics for understanding the financial impact of individual
        subscriptions.


        **What This Endpoint Returns:**

        Financial and operational analytics for a single subscription contract,
        calculated from all successful billing attempts throughout the
        subscription's lifetime. Unlike realtime contract queries, this provides
        historical aggregated data.


        **Metrics Included:**


        **Revenue Metrics:**

        - **totalOrderAmount**: Total revenue in decimal format (e.g., 299.95)

        - **totalOrderRevenue**: Formatted currency string (e.g., "$299.95")

        - Calculated from all SUCCESS status billing attempts

        - Includes taxes, shipping, and discounts

        - Does NOT include failed or pending payments


        **Order Count:**

        - **totalOrders**: Count of successful billing attempts

        - Represents number of orders generated by subscription

        - Does NOT include failed billing attempts

        - Starts at 0 for brand new subscriptions


        **Currency Formatting:**

        - Uses shop's configured money_format

        - Respects shop's currency code (USD, EUR, GBP, etc.)

        - Handles currency symbols and decimal places correctly

        - Falls back to USD if currency unknown


        **Calculation Logic:**


        **Data Source:**

        ```sql

        SELECT 
          COUNT(*) as totalOrders,
          SUM(order_amount) as totalOrderAmount
        FROM subscription_billing_attempt

        WHERE shop = ? 
          AND contract_id = ?
          AND status = 'SUCCESS'
        ```


        **What Gets Counted:**

        - ✅ Initial subscription order

        - ✅ All successful recurring orders

        - ✅ Manual billing attempts that succeeded

        - ✅ Retry attempts that eventually succeeded

        - ❌ Failed payment attempts

        - ❌ Skipped billing cycles

        - ❌ Cancelled/voided orders

        - ❌ Pending/in-progress billing


        **Use Cases:**


        **1. Customer Lifetime Value:**

        - Calculate total revenue from specific customer

        - Measure subscription ROI

        - Identify high-value subscriptions

        - Track revenue growth over time


        **2. Subscription Performance:**

        - Analyze revenue per subscription

        - Compare subscriptions by total value

        - Identify most profitable subscription types

        - Calculate average order value


        **3. Customer Portal:**

        - Display "You've saved $XXX" messaging

        - Show "X orders delivered" stats

        - Celebrate subscription milestones

        - Build customer loyalty through transparency


        **4. Reporting & Analytics:**

        - Build subscription revenue dashboards

        - Generate customer value reports

        - Track subscription health metrics

        - Forecast future revenue


        **5. Business Intelligence:**

        - Segment customers by subscription value

        - Identify churn risk (low order count)

        - Calculate retention rates

        - Measure subscription program success


        **Response Format:**

        ```json

        {
          "totalOrders": 12,
          "totalOrderAmount": 599.88,
          "totalOrderRevenue": "$599.88"
        }

        ```


        **Response Fields:**

        - `totalOrders` (integer): Count of successful billing attempts

        - `totalOrderAmount` (decimal): Numeric revenue total

        - `totalOrderRevenue` (string): Formatted currency display


        **Example Scenarios:**


        **Brand New Subscription:**

        ```json

        {
          "totalOrders": 0,
          "totalOrderAmount": 0.00,
          "totalOrderRevenue": "$0.00"
        }

        ```


        **After First Successful Order:**

        ```json

        {
          "totalOrders": 1,
          "totalOrderAmount": 49.99,
          "totalOrderRevenue": "$49.99"
        }

        ```


        **Established Subscription (EUR):**

        ```json

        {
          "totalOrders": 24,
          "totalOrderAmount": 1199.76,
          "totalOrderRevenue": "€1.199,76"
        }

        ```


        **Integration Examples:**


        **Customer Portal - Loyalty Display:**

        ```javascript

        const analytics = await fetch(
          `/api/external/v2/subscription-contract-details/analytics/${contractId}`,
          { headers: { 'X-API-Key': 'your-key' } }
        ).then(r => r.json());


        const loyaltyMessage = `
          <div class="loyalty-badge">
            <h3>Thank you for your loyalty!</h3>
            <p>You've received ${analytics.totalOrders} orders</p>
            <p>Total value: ${analytics.totalOrderRevenue}</p>
          </div>
        `;

        ```


        **Revenue Dashboard:**

        ```javascript

        // Fetch analytics for multiple subscriptions

        const contractIds = [123, 456, 789];

        const analyticsPromises = contractIds.map(id => 
          getContractAnalytics(id)
        );


        const allAnalytics = await Promise.all(analyticsPromises);

        const totalRevenue = allAnalytics.reduce(
          (sum, a) => sum + a.totalOrderAmount, 0
        );


        console.log(`Total subscription revenue: $${totalRevenue.toFixed(2)}`);

        ```


        **Important Considerations:**


        **Data Accuracy:**

        - Based on Appstle's billing attempt records

        - May differ slightly from Shopify order totals

        - Includes only what Appstle successfully billed

        - Updated after each billing attempt completes


        **Currency Handling:**

        - Formatting uses shop's money_format setting

        - Different shops may have different decimal separators

        - Currency symbol placement varies by locale

        - Always use totalOrderAmount for calculations


        **Performance:**

        - Fast database aggregation query

        - Typical response time: 100-300ms

        - Indexed by shop and contract ID

        - Suitable for real-time display


        **Best Practices:**


        1. **Use for Display**: Use totalOrderRevenue for customer-facing
        display

        2. **Calculate with Amount**: Use totalOrderAmount for mathematical
        operations

        3. **Cache Strategically**: Cache for dashboards, fetch real-time for
        critical displays

        4. **Handle Zero**: Gracefully handle new subscriptions with 0 orders

        5. **Validate Contract**: Ensure contract exists before querying
        analytics


        **Limitations:**


        **What's NOT Included:**

        - Future projected revenue

        - Failed payment attempt counts

        - Refunds or chargebacks

        - Pending/processing orders

        - Orders from other subscriptions


        **Related Calculations:**


        **Average Order Value:**

        ```javascript

        const aov = analytics.totalOrderAmount / analytics.totalOrders;

        console.log(`Average order value: $${aov.toFixed(2)}`);

        ```


        **Customer Lifetime Value (projected):**

        ```javascript

        const monthsActive = calculateMonthsActive(contract.createdAt);

        const monthlyRevenue = analytics.totalOrderAmount / monthsActive;

        const projectedLTV = monthlyRevenue * 12; // Annual LTV

        ```


        **Authentication:** Requires valid X-API-Key header
      operationId: getSubscriptionContractAnalyticsByContractIdExternalV2
      parameters:
        - description: Contract ID
          in: path
          name: contractId
          required: true
          schema:
            type: string
        - description: API Key (Deprecated - Use Header X-API-Key instead)
          in: query
          name: api_key
          required: false
          schema:
            type: string
        - in: header
          name: X-API-Key
          required: false
          schema:
            type: string
      responses:
        '200':
          content:
            application/json:
              examples:
                Active subscription with history:
                  description: Active subscription with history
                  value:
                    totalOrderAmount: 599.88
                    totalOrderRevenue: $599.88
                    totalOrders: 12
                New subscription (no orders yet):
                  description: New subscription (no orders yet)
                  value:
                    totalOrderAmount: 0
                    totalOrderRevenue: $0.00
                    totalOrders: 0
              schema:
                $ref: '#/components/schemas/ContractAnalytics'
          description: Successfully retrieved contract analytics
        '400':
          content:
            application/json:
              example:
                detail: Contract ID must be a valid positive integer
                status: 400
                title: Invalid contract ID
                type: https://example.com/errors/bad-request
          description: Bad request - Invalid contract ID
        '401':
          content:
            application/json:
              example:
                detail: Valid X-API-Key header is required
                status: 401
                title: Authentication required
                type: https://example.com/errors/unauthorized
          description: Authentication required
        '403':
          content:
            application/json:
              example:
                detail: Contract does not belong to your shop
                status: 403
                title: Access denied
                type: https://example.com/errors/forbidden
          description: Forbidden - Contract does not belong to authenticated shop
        '404':
          content:
            application/json:
              example:
                detail: No subscription contract found with ID 12345
                status: 404
                title: Contract not found
                type: https://example.com/errors/not-found
          description: Contract not found
components:
  schemas:
    ContractAnalytics:
      properties:
        totalOrderAmount:
          format: double
          type: number
        totalOrderCount:
          format: int64
          type: integer
        totalOrderRevenue:
          type: string
      type: object

````