# Loopwise Developer Documentation

> Developer and AI-agent documentation for Loopwise (formerly Teachify), a platform for creators selling courses, events, memberships, and digital downloads. Covers OAuth 2.0 / OpenID Connect integration, the Admin GraphQL API, webhooks, and how an agent discovers and reads a storefront. Per-tenant endpoints and catalog data live on each storefront's own origin, not here — every storefront publishes its own llms.txt.

Every documentation page below is inlined in full, each under its own heading with its canonical URL. For the index alone, fetch https://docs.loopwise.com/llms.txt.

---

# Loopwise Developer Docs (https://docs.loopwise.com/)



Welcome to the Loopwise developer documentation. Here you'll find everything you need to integrate with our platform.

## Getting started [#getting-started]

If you're new to the Loopwise API, start with the [OAuth Quickstart](/guides/oauth-quickstart) to get up and running in minutes.

Building an **AI agent** against a storefront? Start with [Agent discovery](/concepts/agent-discovery) to find every per-tenant resource (MCP, OpenAPI, Agent Skills, markdown content) from one catalog, then read the [Storefront content API](/guides/storefront-content-api).

## Documentation structure [#documentation-structure]

### [Guides](/guides/oauth-quickstart) [#guides]

Step-by-step instructions for common integration tasks, including OAuth setup, Enterprise SSO, and Zapier.

### [Concepts](/concepts/oauth-overview) [#concepts]

Background information on how things work and why they're designed the way they are.

### [Admin API](/api) [#admin-api]

GraphQL API reference for managing courses, students, payments, subscriptions, and more.

### [Webhooks](/webhooks/overview) [#webhooks]

Real-time event notifications for payments, courses, users, and other resources.

### [Reference](/reference/scopes) [#reference]

Technical specifications, endpoint details, and lookup tables.

### [Changelog](/changelog) [#changelog]

Recent platform changes and updates.


---

# Loopwise Admin API Best Practices (https://docs.loopwise.com/api/best-practices)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

This guide provides best practices for working with the Loopwise Admin API to ensure optimal performance, security, and reliability.

## Authentication [#authentication]

* **Secure your API keys**: Never expose your API keys in client-side code or public repositories.
* **Use separate API keys** for different environments (development, staging, production).
* **Implement proper key rotation** procedures for your organization.
* **Monitor API key usage** to detect unusual patterns that might indicate a security breach.

## Request Optimization [#request-optimization]

### Requesting Only What You Need [#requesting-only-what-you-need]

GraphQL allows you to specify exactly which fields you need. Always limit your queries to only the fields your application requires:

```graphql
# Good: Only requesting needed fields
query {
  courses(first: 10) {
    nodes {
      id
      name
    }
  }
}

# Avoid: Requesting unnecessary fields
query {
  courses(first: 10) {
    nodes {
      id
      name
      description
      startDate
      endDate
      createdAt
      updatedAt
      # ... many more fields
    }
  }
}
```

### Pagination [#pagination]

When working with collections, always use pagination to limit the amount of data returned:

* Use the `first` parameter to limit the number of items (default: 20, max: 100)
* Use the `after` parameter with the `endCursor` from previous responses to fetch subsequent pages
* Check `hasNextPage` to determine if more data is available

```graphql
query {
  students(first: 50, after: "cursor-from-previous-page") {
    nodes {
      id
      name
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

### Filtering [#filtering]

Use filters to narrow down results on the server side rather than fetching large datasets and filtering client-side:

```graphql
# Good: Server-side filtering
query {
  students(filter: { courseId: "course-123" }) {
    nodes {
      id
      name
    }
  }
}

# Avoid: Fetching all students and filtering client-side
```

## Error Handling [#error-handling]

* Always check for errors in the response before processing the data
* Implement proper error handling for different types of errors:
  * Authentication errors (invalid or expired API key)
  * Validation errors (invalid input)
  * Resource not found errors
  * Rate limiting errors

Example error handling in JavaScript:

```javascript
async function makeApiRequest(query, variables) {
  const response = await fetch('https://teachify.io/admin/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Teachify-API-Key': apiKey
    },
    body: JSON.stringify({ query, variables })
  });

  const result = await response.json();

  // Check for GraphQL errors
  if (result.errors) {
    const error = result.errors[0];

    // Handle different error types
    if (error.message.includes('authentication')) {
      throw new Error('Authentication failed. Check your API key.');
    } else if (error.message.includes('rate limit')) {
      throw new Error('Rate limit exceeded. Please try again later.');
    } else {
      throw new Error(`API Error: ${error.message}`);
    }
  }

  // Check for mutation-specific errors
  if (result.data && result.data.someMutation && result.data.someMutation.errors) {
    const mutationErrors = result.data.someMutation.errors;
    throw new Error(`Mutation failed: ${mutationErrors[0].message}`);
  }

  return result.data;
}
```

## Rate Limiting [#rate-limiting]

The API implements rate limiting to ensure fair usage:

* **Mutations**: 200 requests per minute per API key
* **Queries**: 600 requests per minute per API key

When you exceed these limits, you'll receive a 429 status code with a `Retry-After` header. Always respect this header and implement retry logic with exponential backoff.

For detailed information about rate limits, error handling, and best practices, see the [Rate Limiting](./rate-limiting) guide.

## Webhooks vs. Polling [#webhooks-vs-polling]

For real-time updates, consider using webhooks (when available) instead of polling the API:

* Webhooks provide immediate notifications when data changes
* Polling can lead to increased API usage and potential rate limiting
* If polling is necessary, use reasonable intervals (e.g., no more than once per minute for non-critical data)

## Handling Large Operations [#handling-large-operations]

For operations that might affect many records:

* Use pagination to process large datasets in smaller batches
* Implement proper error handling and retry logic
* Consider using background jobs for very large operations
* Monitor the progress of long-running operations


---

# Loopwise Admin API (https://docs.loopwise.com/api)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only. We will announce when the API is ready for integration.

## Overview [#overview]

The Loopwise Admin API provides programmatic access to school data and operations through a GraphQL interface. This API allows third-party applications to perform operations similar to those available in the school admin dashboard, including accessing course information, student data, and performing administrative actions.

## Endpoint [#endpoint]

Loopwise's GraphQL endpoint is:

```
https://teachify.io/admin/graphql
```

The endpoint supports GraphQL introspection, allowing you to explore the full schema.

## Authentication [#authentication]

### Obtaining an API Key [#obtaining-an-api-key]

Access to the Loopwise Admin API requires an API key that is associated with a specific school and authorized application.

1. **Request an API Key**:
   * Contact Loopwise support to request an API key for your application
   * API keys are issued on a per-school basis
   * You will need to provide information about your application and its intended use

2. **API Key Security**:
   * Keep your API key secure
   * Do not share it in client-side code or public repositories
   * Each API key is specific to a school-application pair
   * Loopwise monitors API usage and may revoke keys that are misused

### Using the API Key [#using-the-api-key]

Include the API key in all API requests using the `X-Teachify-API-Key` HTTP header:

```bash
curl \
  -X POST \
  -H "Content-Type: application/json" \
  -H "X-Teachify-API-Key: <Your API Key>" \
  -H "API-Version: 2027-01-01" \
  --data '{ "query": "{ courses { nodes { id name } } }" }' \
  https://teachify.io/admin/graphql
```

Send the `API-Version` header on every request to choose the schema release your integration was built against. The example sends `2027-01-01`, the release these docs describe, so the integration keeps working when that release takes effect. See [Versioning](./versioning).

## Getting Started [#getting-started]

### GraphQL Clients [#graphql-clients]

We recommend using a GraphQL client to explore and interact with the API. Popular options include:

* [GraphiQL](https://github.com/graphql/graphiql)
* [Apollo Studio Explorer](https://studio.apollographql.com/sandbox/explorer)
* [Insomnia](https://insomnia.rest/)
* [Postman](https://www.postman.com/)

These tools allow you to browse the schema, build queries, and test your requests with proper authentication.

### Basic Query Example [#basic-query-example]

To get started, here's a simple query to retrieve basic information about the authenticated school:

```graphql
query SchoolInfo {
  school {
    id
    name
    createdAt
  }
}
```

### Pagination [#pagination]

Most list queries in the Loopwise Admin API use cursor-based pagination to efficiently handle large datasets. Paginated responses typically include:

* `nodes`: Array of items for the current page
* `pageInfo`: Metadata about the current page, including:
  * `hasNextPage`: Boolean indicating if more pages exist
  * `endCursor`: Cursor to use for fetching the next page

Example of paginated query:

```graphql
query Courses($first: Int, $after: String) {
  courses(first: $first, after: $after) {
    nodes {
      id
      name
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

### Error Handling [#error-handling]

The API returns standard GraphQL errors in the following format:

```json
{
  "errors": [
    {
      "message": "Error message description",
      "locations": [{ "line": 2, "column": 3 }],
      "path": ["fieldName"]
    }
  ]
}
```

Common error scenarios include:

* Authentication failures
* Rate limiting
* Invalid input parameters
* Resource not found
* Permission denied

## Next Steps [#next-steps]

Explore the following sections to learn more about using the Loopwise Admin API:

* **Queries**: Available query operations
  * [Overview](./queries): Introduction to queries
  * [Pagination](./queries#pagination): Working with paginated responses
  * [Filtering](./queries#filtering): Filtering query results
  * **Resources**:
    * [Courses](./queries/courses): Course queries
    * [Events](./queries/events): Event queries
    * [Users](./queries/users): User queries
    * [Assignments](./queries/assignments): Assignment queries
* [Best Practices](./best-practices): Guidelines for effective API usage


---

# Rate Limiting (https://docs.loopwise.com/api/rate-limiting)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Loopwise Admin API implements rate limiting to ensure system stability and fair usage across all users. Rate limits are applied per API key and vary based on the type of operation being performed.

## Rate Limit Tiers [#rate-limit-tiers]

Rate limits are differentiated by operation type to balance system resources while providing a good developer experience:

| Operation Type | Limit        | Window     | Typical Use Cases                         |
| -------------- | ------------ | ---------- | ----------------------------------------- |
| **Mutations**  | 200 requests | per minute | Creating, updating, or deleting resources |
| **Queries**    | 600 requests | per minute | Reading data, listing resources           |

These limits are designed to accommodate:

* Batch operations (e.g., enrolling multiple students)
* Data synchronization workflows
* Dashboard and reporting applications
* Real-time data queries

## How Rate Limiting Works [#how-rate-limiting-works]

### Identification [#identification]

Rate limits are tracked **per API key**. Each API key has its own independent rate limit counters for mutations and queries.

### Time Windows [#time-windows]

Rate limits use a **sliding window** of 1 minute:

* The counter tracks requests in the past 60 seconds
* Once a request is older than 60 seconds, it no longer counts toward your limit
* This provides smooth, continuous access rather than hard resets at fixed intervals

### Operation Detection [#operation-detection]

The API automatically detects whether a request is a mutation or query:

* **Mutation**: GraphQL query string starts with `mutation`
* **Query**: All other GraphQL operations (including introspection queries)

Example:

```graphql
# This counts as a MUTATION (200/minute limit)
mutation {
  enrollStudentToCourse(input: { ... }) {
    enrollment { id }
  }
}

# This counts as a QUERY (600/minute limit)
query {
  courses(first: 50) {
    nodes { id name }
  }
}
```

## Rate Limit Headers [#rate-limit-headers]

When you exceed the rate limit, the API returns a 429 status code with headers to help you track your usage:

### Response Headers (429 Only) [#response-headers-429-only]

```http
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 45
X-RateLimit-Limit: 200
X-RateLimit-Reset: 1699012860
```

* **`Retry-After`**: Number of seconds you should wait before making another request
* **`X-RateLimit-Limit`**: The maximum number of requests allowed in the current window
* **`X-RateLimit-Reset`**: Unix timestamp indicating when the rate limit window resets

## Error Response Format [#error-response-format]

When you exceed a rate limit, you'll receive a structured GraphQL error response:

```json
{
  "errors": [{
    "message": "Rate limit exceeded for mutations. Please retry after 45 seconds.",
    "extensions": {
      "code": "RATE_LIMIT_EXCEEDED",
      "operation_type": "mutations",
      "limit": 200,
      "retry_after": 45,
      "reset_at": 1699012860
    }
  }]
}
```

### Error Response Fields [#error-response-fields]

| Field            | Description                          |
| ---------------- | ------------------------------------ |
| `message`        | Human-readable error message         |
| `code`           | Error code: `RATE_LIMIT_EXCEEDED`    |
| `operation_type` | Either `mutations` or `queries`      |
| `limit`          | The rate limit that was exceeded     |
| `retry_after`    | Seconds to wait before retrying      |
| `reset_at`       | Unix timestamp when the limit resets |

## Concurrency and Execution-Time Limits [#concurrency-and-execution-time-limits]

Request counts do not capture how expensive a GraphQL operation is, so a second layer limits **how much work** one credential can have in progress. It applies to every credential type (API keys, OAuth applications, vendor apps, installed apps), not only API keys.

| Budget                   | Limit                           | Notes                                                                                                                                                           |
| ------------------------ | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Operations in flight** | 10 at a time                    | The 11th concurrent operation is rejected until one finishes                                                                                                    |
| **Execution time**       | 60 seconds per 60-second window | A token bucket charged with each operation's server-side execution time; it refills continuously, so one 4-second operation costs the same as forty 100 ms ones |

Enforcement is enabled per credential. Until it is enabled for yours, an operation over either budget still runs and the response is `200`; the `RateLimit` headers below are reported either way, so you can bring your usage under the budgets before enforcement reaches you.

### Headers (every executed operation) [#headers-every-executed-operation]

Unlike the per-minute limits, these budgets are reported on every response whose operation reached execution — admitted or rejected — so you can pace yourself before being rejected. The values describe the budgets **after** that operation was charged:

```http
RateLimit-Policy: "active-operations";q=10;qu="concurrent-requests"
RateLimit: "active-operations";r=9
RateLimit-Limit: 60000
RateLimit-Remaining: 58240
RateLimit-Reset: 2
```

* **`RateLimit-Policy`*&#x2A; / &#x2A;*`RateLimit`**: the concurrency budget, in the structured fields of the IETF RateLimit header draft — `q` is the quota, `qu` its registered unit, `r` the operations you can still start
* **`RateLimit-Limit`*&#x2A; / &#x2A;*`RateLimit-Remaining`*&#x2A; / &#x2A;*`RateLimit-Reset`**: the execution-time budget under the older header names — the budget in milliseconds, what is left of it, and the seconds until it is full again. The draft has no quota unit for execution time, which is why this budget is not in `RateLimit-Policy`

Responses that never reach the limiters — authentication failures, an invalid [`API-Version`](./versioning), GraphQL syntax or validation errors — carry no budget headers. All of these fields are exposed to cross-origin browser clients.

### Rejection [#rejection]

A rejected operation is **not executed**. The response status is `429`, `Retry-After` says how long to wait (`1` second for a concurrency rejection, the refill time for an exhausted execution budget), and the body is a regular GraphQL errors payload so GraphQL clients see the same error:

```json
{
  "errors": [{
    "message": "Rate limited by runtime: limit 60000",
    "extensions": {
      "code": "RATE_LIMITED",
      "limiter": "runtime",
      "retry_after_ms": 1820
    }
  }]
}
```

| Field            | Description                                                                                   |
| ---------------- | --------------------------------------------------------------------------------------------- |
| `code`           | Error code: `RATE_LIMITED`                                                                    |
| `limiter`        | `active_operations` or `runtime` — which budget rejected the operation                        |
| `retry_after_ms` | Milliseconds until the execution budget admits an operation again; present for `runtime` only |

Tell the two layers apart by the error code: `RATE_LIMIT_EXCEEDED` is the per-minute request count, `RATE_LIMITED` is a concurrency or execution-time budget. Both send `Retry-After`, so a client that honours that header handles both.

### Staying under the execution budget [#staying-under-the-execution-budget]

* Keep operations small: paginate with 50–100 items and avoid deeply nested selections
* Do not run more than a handful of requests in parallel per credential
* Watch `RateLimit-Remaining`; when it drops low, slow down instead of waiting for a `429`
* Expensive mutations (for example enrolling a member into a plan with many courses) can take seconds each — batch them sequentially, not concurrently

## Best Practices [#best-practices]

To avoid hitting rate limits:

* **Respect the `Retry-After` header** - Always wait the specified time before retrying a 429 response
* **Implement retry logic** - Use exponential backoff with a maximum retry limit for production applications
* **Cache query responses** - Reduce API calls by caching frequently accessed data
* **Batch operations** - Use GraphQL aliases to combine multiple mutations into a single request
* **Use appropriate pagination** - Fetch 50-100 items per page instead of making many small requests
* **Spread out non-urgent operations** - Add delays between background tasks to stay under limits

## Common Scenarios [#common-scenarios]

**High-Volume Data Synchronization**: Use pagination (50-100 items/page) with 1-2 second delays between requests. Cache data when possible and run during off-peak hours.

**Real-Time Dashboards**: Cache aggressively (30-60 seconds), use webhooks instead of polling when available, and implement smart polling intervals.

**Batch Operations**: Group related operations into single requests using GraphQL aliases. Process in batches of 20-50 items with delays between batches.

## Increasing Rate Limits [#increasing-rate-limits]

The default rate limits are designed to accommodate the vast majority of use cases. However, if you have a legitimate need for higher limits:

1. **Contact our support team** with details about your use case
2. **Provide information** about:
   * Your application's purpose
   * Expected request patterns
   * Peak usage times
   * Number of users/schools affected
3. **Demonstrate** that you've implemented best practices (caching, batching, etc.)

We review rate limit increase requests on a case-by-case basis.

### Configuration [#configuration]

For self-hosted deployments, rate limits can be adjusted in `config/initializers/rack_attack.rb`:

```ruby
module AdminGraphqlRateLimits
  MUTATIONS_LIMIT = 200  # requests per minute (default: 200)
  QUERIES_LIMIT = 600    # requests per minute (default: 600)
  PERIOD = 1.minute      # time window
end
```

After modifying these values, restart your Rails server for the changes to take effect.

## Testing Rate Limits [#testing-rate-limits]

When developing your integration, you can test rate limit handling:

```bash
# Test script to trigger rate limits (for testing only)
for i in {1..250}; do
  curl -X POST https://teachify.io/admin/graphql \
    -H "Content-Type: application/json" \
    -H "X-Teachify-API-Key: your_test_key" \
    -d '{"query":"mutation { enrollStudentToCourse(input: {courseId: \"test\", email: \"test@example.com\"}) { enrollment { id } } }"}' \
    &
done
```

> **Note:** Only test rate limits in a development or staging environment, never in production.

## FAQ [#faq]

### Q: Are rate limits shared across multiple API keys? [#q-are-rate-limits-shared-across-multiple-api-keys]

No. Each API key has its own independent rate limit counters.

### Q: Do failed requests count toward my rate limit? [#q-do-failed-requests-count-toward-my-rate-limit]

Yes. All requests count toward your rate limit, regardless of whether they succeed or fail.

### Q: Can I check my current rate limit usage without making a request? [#q-can-i-check-my-current-rate-limit-usage-without-making-a-request]

No. Rate limit information is only provided in response headers after making a request.

### Q: What happens to requests made exactly when the limit resets? [#q-what-happens-to-requests-made-exactly-when-the-limit-resets]

The sliding window approach means there's no hard reset. As older requests age out (after 60 seconds), your available quota gradually increases.

### Q: Are GraphQL introspection queries counted? [#q-are-graphql-introspection-queries-counted]

Yes, introspection queries count as queries and use your query rate limit (600/min).

### Q: Do retried requests count multiple times? [#q-do-retried-requests-count-multiple-times]

Yes. Each request attempt counts toward your limit, including retries.

## Summary [#summary]

* **Mutations**: 200/minute per API key
* **Queries**: 600/minute per API key
* **In flight**: 10 operations at a time per credential
* **Execution time**: 60 seconds per 60-second window per credential, reported on every executed operation via the `RateLimit-*` headers
* Always respect the `Retry-After` header when receiving a 429 response
* Implement retry logic with exponential backoff
* Cache responses and batch operations to reduce API calls


---

# Versioning (https://docs.loopwise.com/api/versioning)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Admin API is versioned by **release date**. Additive changes (new fields, arguments, types and enum values) ship continuously to every version. Breaking changes are grouped into dated releases that a client opts into.

The field tables in these docs describe the `2027-01-01` release. Timestamps are shown as `Int`, except fields already documented as `BigInt`. Under `2027-04-01`, those `Int` timestamps become `BigInt` strings. See [Migrating to 2027-04-01](#migrating-to-2027-04-01).

## Requesting a version [#requesting-a-version]

Send the date of the release your integration was built against in the `API-Version` header:

```bash
curl \
  -X POST \
  -H "Content-Type: application/json" \
  -H "X-Teachify-API-Key: <Your API Key>" \
  -H "API-Version: 2027-01-01" \
  --data '{ "query": "{ courses { nodes { id name } } }" }' \
  https://teachify.io/admin/graphql
```

The API resolves the header as follows. A credential is the API key, the OAuth application (its creation date, not the access token's), or the App Installation that authenticates the request.

| Situation                                                | Schema you get                                                 |
| -------------------------------------------------------- | -------------------------------------------------------------- |
| Header names a release date                              | That release                                                   |
| Header names a date between two releases                 | The release in effect on that date                             |
| Header names a date later than the newest release        | The newest release                                             |
| Header names a date older than every release             | The baseline (pre-versioning) schema                           |
| No header, credential created on or after a release date | The release in effect when the credential was created (pinned) |
| No header, credential older than every release           | The baseline schema                                            |
| Header present but empty or whitespace-only              | Treated as no header                                           |
| Header is not `YYYY-MM-DD`                               | `400` with `extensions.code` set to `INVALID_API_VERSION`      |

Any valid `YYYY-MM-DD` date is accepted, including a future date. To test an upcoming release before it takes effect, send its date now, for example `API-Version: 2027-04-01`.

The response echoes the version the request was resolved with in an `API-Version` header: the header value you sent, or the pinned release when you sent none. The response also lists `API-Version` in `Vary`. Cross-origin browser clients can read the `API-Version` response header. A request with no header and no pinned release gets no `API-Version` response header.

Pinning keeps an integration on the schema it was built against without sending the header. Sending the header on every request is still recommended, and it is required to move to a newer release.

### Invalid versions [#invalid-versions]

A header value that is not a `YYYY-MM-DD` date is rejected with HTTP `400`:

```json
{
  "errors": [
    {
      "message": "\"latest\" is not a valid API version (expected YYYY-MM-DD)",
      "extensions": {
        "code": "INVALID_API_VERSION"
      }
    }
  ]
}
```

### Deprecation warnings [#deprecation-warnings]

When a request selects a field that a later release removes, the response carries an `API-Deprecated` header. It names each such field and the release that removes it:

```
API-Deprecated: CurriculumPlan.symbol; removed=2027-01-01
```

Each entry is `Type.field; removed=YYYY-MM-DD`. Several entries are separated by commas, and each field appears once. The header is absent when the request selects no field scheduled for removal, and when the request fails validation. Cross-origin browser clients can read the `API-Deprecated` response header.

## Release cadence and support [#release-cadence-and-support]

* Breaking changes are batched into at most one release per quarter. A release is dated the first day of the quarter: `YYYY-01-01`, `YYYY-04-01`, `YYYY-07-01` or `YYYY-10-01`.
* A field or type scheduled for removal is marked `@deprecated`, with the release date in its reason, at least **three months** before that date.
* Every release stays available for at least **twelve months** after the next release ships. After that, its definitions may be folded into the baseline. The schedule is announced in the [changelog](/changelog) before it happens.

## Releases [#releases]

| Release      | Changes                                                                                                                                                                                                                                                         |
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `2027-01-01` | `CurriculumPlan.symbol` is removed. Use `currencySymbol`.                                                                                                                                                                                                       |
| `2027-04-01` | Every Unix-timestamp field, argument and filter typed `Int` / `IntOperator` moves to `BigInt` / `BigIntOperator`, so dates after 2038-01-19 encode. Timestamps already typed `BigInt` keep their type. See [Migrating to 2027-04-01](#migrating-to-2027-04-01). |

## Migrating to 2027-04-01 [#migrating-to-2027-04-01]

* `BigInt` is serialized as a JSON string, for example `"1893456000"`. Parse it before you compare or sort it. As strings, `"999" > "1000"`.
* Timestamp arguments and filters accept an integer as a JSON number or a numeric string. Any other number is rejected with `must be an integer`, including `1700000000.0`. Values must fall between 0001-01-01 and 9999-12-31 UTC.
* Update variable declarations. A `$since: Int` or `$filter: IntOperator` variable fails validation against a `BigInt` / `BigIntOperator` argument. Inline literals such as `since: 1700000000` keep working. If you use code generation, add a `BigInt` scalar mapping. Generated types change from number to string.
* Earlier releases keep `Int`. On an earlier release, a timestamp outside the `Int` range is **clamped** to `2147483647` (2038-01-19) or `-2147483648` (1901-12-13) instead of failing the query. Do not write a timestamp read on an earlier release back unchanged: it moves a later date to 2038. A clamped value also does not match an `eq` filter, and earlier releases cannot send a timestamp after 2038.
* On every release, timestamps that were already `BigInt` now get the same integer and 0001–9999 checks. This covers the `BigIntOperator` filters (`updatedAt` on payments, courses and membership plans; `createdAt` on reviews) and the coupon, event, assignment and curriculum plan inputs. A fraction or an out-of-range value is now a validation error instead of a failed request or a silently stored value.


---

# Changelog (https://docs.loopwise.com/changelog)



All notable changes to the Loopwise Admin API are documented on this page.

***

## October 27, 2026 [#october-27-2026]

### Added [#added]

* **API versioning is documented** - The Admin API is versioned by release date. Send the date of the release your integration was built against in the `API-Version` request header. Breaking changes ship only in dated releases, and additive changes reach every version. See [Versioning](/api/versioning) for how a version is resolved, the release cadence and the support window.
* **`API-Deprecated` response header** - A response to a request that selects a field scheduled for removal names each such field and its removal release, for example `API-Deprecated: CurriculumPlan.symbol; removed=2027-01-01`. See [Deprecation warnings](/api/versioning#deprecation-warnings).

### Upcoming releases [#upcoming-releases]

* **`2027-01-01`** - `CurriculumPlan.symbol` is removed. Use `currencySymbol`.
* **`2027-04-01`** - Every Unix-timestamp field, argument and filter typed `Int` / `IntOperator` moves to `BigInt` / `BigIntOperator`. Timestamps already typed `BigInt` keep their type. `BigInt` values are serialized as JSON strings, so parse them before comparing or sorting. See [Migrating to 2027-04-01](/api/versioning#migrating-to-2027-04-01).

No release is in effect yet. A request without an `API-Version` header receives the baseline schema, and an API key, OAuth application or App Installation created on or after `2027-01-01` is pinned to that release automatically.

To test an upcoming release early, send its date in the header, for example `API-Version: 2027-04-01`. The API accepts any valid `YYYY-MM-DD` date, including a future date.


---

# Agent discovery (https://docs.loopwise.com/concepts/agent-discovery)



Every Loopwise storefront advertises its agent-facing capabilities at
**predictable, per-origin URLs**, so an AI agent can discover what a school
offers in a single fetch instead of guessing. All URLs below are served per
storefront origin — substitute the storefront's host (a custom domain like
`https://funi.best` or a default subdomain).

## Start here: the AI Catalog [#start-here-the-ai-catalog]

The single entry point is the [Agentic Resource Discovery](https://ai-catalog.io/)
catalog:

```
GET https://school.example/.well-known/ai-catalog.json
```

It returns one manifest listing every agentic resource on the origin — the
MCP server, each Agent Skill, the OpenAPI spec, the ACP merchant endpoint,
and the API catalog — each with a domain-anchored `urn:air` identifier, a
media type, and a URL. An agent reads this first, then follows the entries it
needs.

## What the catalog lists [#what-the-catalog-lists]

`ai-catalog.json` contains one entry per agentic resource on the origin:

| Catalog entry | URL                                                       | What it is                                                                                                          |
| ------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| MCP server    | `/.well-known/mcp/server-card.json` (transport at `/mcp`) | Anonymous, read-only Model Context Protocol tools over the catalog.                                                 |
| OpenAPI spec  | `/openapi.json`                                           | OpenAPI 3.0 for the content and OAuth/OIDC endpoints. See [Storefront content API](/guides/storefront-content-api). |
| Agent Skills  | `/.well-known/agent-skills/index.json`                    | Published skills for navigating and evaluating the catalog.                                                         |
| API Catalog   | `/.well-known/api-catalog`                                | RFC 9727 linkset of the public APIs on this origin.                                                                 |
| ACP merchant  | `/.well-known/acp.json`                                   | Agentic Commerce Protocol merchant discovery.                                                                       |

The catalog also carries a `host.documentationUrl` pointing at the
storefront's [`llms.txt`](#related-per-origin-resources).

## Related per-origin resources [#related-per-origin-resources]

These aren't catalog entries, but they live at predictable URLs on the same
origin and are worth following:

| Resource     | URL                                 | What it is                                                                       |
| ------------ | ----------------------------------- | -------------------------------------------------------------------------------- |
| llms.txt     | `/llms.txt`, `/llms-full.txt`       | Human/agent-readable index of the storefront's content and developer resources.  |
| OAuth / OIDC | `/.well-known/openid-configuration` | Per-tenant identity provider — see [OAuth quickstart](/guides/oauth-quickstart). |

## Why per-origin [#why-per-origin]

Each storefront is a distinct tenant. Identifiers and URLs in every document
above resolve to the **requested host**, so a custom domain and a default
subdomain each return a self-consistent view. The *shape* of these resources
is identical across all schools (it comes from one platform); only the host
and the underlying data differ.

## Reachability [#reachability]

The machine endpoints are always served from the storefront origin, so an
agent can operate even if this documentation site is unavailable. This page
explains how the surfaces work; the per-origin documents are the source of
truth for a specific school.


---

# Authorization Code Flow (https://docs.loopwise.com/concepts/authorization-code-flow)



The Authorization Code flow with PKCE is the only supported OAuth flow in Loopwise. This page explains each step in detail.

## Flow diagram [#flow-diagram]

<Mermaid
  chart="sequenceDiagram
    participant Client
    participant Loopwise
    participant User

    Note over Client: 1. Generate code_verifier<br/>+ code_challenge (S256)

    Client->>Loopwise: 2. Redirect to /oauth/authorize<br/>(client_id, scope, code_challenge)
    Loopwise->>User: 3. Show login page
    User->>Loopwise: 4. Authenticate (credentials)
    Loopwise->>User: 5. Show consent screen
    User->>Loopwise: 6. Grant consent

    Loopwise-->>Client: 7. Redirect to redirect_uri<br/>(code, state)

    Client->>Loopwise: 8. POST /api/oauth/token<br/>(code, code_verifier)
    Loopwise-->>Client: 9. Return access_token<br/>(+ refresh_token, school_id)

    Client->>Loopwise: 10. Call API with Bearer token
    Loopwise-->>Client: API response"
/>

## Step-by-step [#step-by-step]

### 1. Generate PKCE values [#1-generate-pkce-values]

Before starting the flow, generate a random `code_verifier` (43-128 characters, URL-safe) and compute its SHA-256 hash as the `code_challenge`:

```javascript
const codeVerifier = generateRandomString(64);
const codeChallenge = base64url(sha256(codeVerifier));
```

### 2. Authorization request [#2-authorization-request]

Redirect the user to the authorization endpoint:

```
GET /oauth/authorize
```

| Parameter               | Required    | Description                                         |
| ----------------------- | ----------- | --------------------------------------------------- |
| `response_type`         | Yes         | Must be `code`                                      |
| `client_id`             | Yes         | Your application's client ID                        |
| `redirect_uri`          | Yes         | Must match a registered redirect URI                |
| `scope`                 | Yes         | Space-separated list of [scopes](/reference/scopes) |
| `state`                 | Recommended | Random string to prevent CSRF attacks               |
| `code_challenge`        | Yes         | PKCE code challenge                                 |
| `code_challenge_method` | Yes         | Must be `S256`                                      |

### 3-6. User authentication and consent [#3-6-user-authentication-and-consent]

Loopwise handles user authentication. If the user is not logged in, they are shown a login page. After authentication:

* If the client is a **trusted first-party app**, authorization is granted automatically (no consent screen)
* Otherwise, the user sees a consent screen showing the requested scopes
* The token is automatically scoped to the school where the OAuth application was registered

### 7. Authorization response [#7-authorization-response]

After the user grants consent, Loopwise redirects to your `redirect_uri`:

```
https://myapp.com/callback?code=AUTH_CODE&state=YOUR_STATE
```

Verify that `state` matches what you sent in step 2.

### 8-9. Token exchange [#8-9-token-exchange]

Exchange the authorization code for tokens. See [Token Endpoints](/reference/token-endpoints) for the full specification.

```http
POST /api/oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&code=AUTH_CODE
&redirect_uri=https://myapp.com/callback
&client_id=YOUR_CLIENT_ID
&code_verifier=YOUR_CODE_VERIFIER
```

### 10. Use the access token [#10-use-the-access-token]

Include the token in the `Authorization` header for all API requests:

```http
GET /api/v1/courses
Authorization: Bearer ACCESS_TOKEN
```

## Error responses [#error-responses]

If the authorization request fails, Loopwise redirects to your `redirect_uri` with error parameters:

```
https://myapp.com/callback?error=access_denied&error_description=The+user+denied+the+request
```

Common error codes:

| Error                 | Description                                          |
| --------------------- | ---------------------------------------------------- |
| `invalid_request`     | Missing or invalid parameters                        |
| `unauthorized_client` | Client is not authorized for this grant type         |
| `access_denied`       | User denied the authorization request                |
| `invalid_scope`       | Requested scope is invalid or exceeds allowed scopes |
| `server_error`        | Internal server error                                |


---

# OAuth Overview (https://docs.loopwise.com/concepts/oauth-overview)



Loopwise uses [OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc6749) to allow third-party applications to access school data on behalf of users. This page explains the key concepts.

## Why OAuth? [#why-oauth]

OAuth lets users grant limited access to their Loopwise data without sharing their password. An integration (the "client") receives an access token with specific [scopes](/reference/scopes) that define exactly what it can do.

Benefits:

* **Security** — users never share their credentials with third-party apps
* **Granular access** — scopes limit what data an integration can access
* **Revocable** — users or admins can revoke access at any time without changing passwords
* **Auditable** — each integration has its own identity, making it easy to track who accessed what

## Architecture [#architecture]

Each school operates as an independent OAuth provider. When you create an OAuth application in a school's admin panel, it is scoped exclusively to that school.

<Mermaid
  chart="flowchart TB
    subgraph Your Integration
        A[Your App]
    end

    subgraph &#x22;School A (demo.teachify.tw)&#x22;
        D1[OAuth Server]
        E1[API]
        F1[(School A Data)]
    end

    A -->|1. Authorize| D1
    D1 -->|2. Access Token| A
    A -->|3. API calls with Bearer token| E1
    E1 --> F1"
/>

The token issued by School A can only access School A's data. There is no cross-school access.

## Key concepts [#key-concepts]

### Authorization server [#authorization-server]

Each school acts as its own OAuth authorization server. It authenticates users, presents the consent screen, issues authorization codes, and exchanges them for access tokens.

A school's OAuth endpoints are accessible at `https://{school-domain}` (e.g., `https://demo.teachify.tw`). Each school's frontend application proxies OAuth requests to the centralized OAuth backend at `connect.loopwise.com`.

### Client application [#client-application]

The third-party integration that wants to access a school's data. Clients are identified by a `client_id` and optionally a `client_secret` (for confidential clients). Each client is registered within a specific school and can only access that school's resources.

### Resource owner [#resource-owner]

The user (typically a school admin) who authorizes the client to access data. The authorization grants access to the school where the OAuth application was registered.

### Access token [#access-token]

A short-lived credential (2 hours) that the client uses to make API requests. Tokens are scoped to the school where the OAuth application was created, along with a set of permissions.

### Refresh token [#refresh-token]

A long-lived credential used to obtain new access tokens without requiring the user to re-authorize.

## Supported flows [#supported-flows]

Loopwise supports the **Authorization Code** flow with **PKCE** (Proof Key for Code Exchange, [RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636)). This is the recommended flow for all clients, including public clients (SPAs, native apps, CLI tools).

For a detailed walkthrough of the flow, see [Authorization Code Flow](/concepts/authorization-code-flow).

## School scoping [#school-scoping]

Each OAuth application belongs to exactly one school. When an admin creates an OAuth application in their school's settings, the application is permanently bound to that school:

* The issued `client_id` only works with that school's authorization endpoint
* All tokens carry the school's `school_id` and are validated against it
* The token response includes `school_id` and `school_subdomain` for the client's reference

This design ensures strict tenant isolation — an OAuth application created for School A can never be used to access School B's data.

### Proxy architecture [#proxy-architecture]

Each school runs its own frontend application on a custom domain (e.g., `demo.teachify.tw`). The frontend exposes standard OAuth endpoints (`/oauth/authorize`, `/api/oauth/token`, etc.) that proxy requests to the centralized OAuth backend at `connect.loopwise.com`. From the client's perspective, all OAuth interactions happen through the school's domain — the backend proxy is transparent.

<Mermaid
  chart="flowchart LR
    A[Your App] -->|OAuth requests| B[&#x22;School Frontend\n(demo.teachify.tw)&#x22;]
    B -->|Proxy| C[&#x22;OAuth Backend\n(connect.loopwise.com)&#x22;]
    C -->|Response| B
    B -->|Response| A"
/>

## MCP clients [#mcp-clients]

Loopwise also supports [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) clients such as Claude Code and Cursor. These are platform-level integrations that use the same OAuth 2.0 protocol but work differently from school-scoped applications:

* MCP clients are registered as **system-default** applications across the platform
* During authorization, the user selects which school to grant access to
* Each authorization produces a token scoped to the selected school

If you are building a standard integration for a specific school, you do not need to worry about MCP — simply register your application in the school's admin panel.

## Audience model [#audience-model]

Every OAuth application declares an **audience** — who is allowed to authenticate through it. Audience is enforced at authorization time.

| Audience    | Who can authenticate                                                     | Typical apps                                                                                           |
| ----------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
| `org_admin` | Tenant operators (owner or manager role) of the contextual school        | Claude Code, Cursor, Windsurf, `loopwise-cli`; school-registered admin dashboards                      |
| `member`    | Any role of the bound or contextual school (student, TA, owner, manager) | School-registered member-facing apps (quiz, exam, bootcamp companion tools); future member MCP clients |

Audience is orthogonal to two other dimensions you will notice in the admin UI:

* **Registration scope** — whether the app is bound to a single school (visible only in that school's admin) or pre-registered by Loopwise for use across all schools (e.g., Claude Code).
* **Audience selection on the school admin UI is a planned follow-up**; today, newly created school-registered apps default to `member` (any role can complete OAuth), preserving the long-standing behaviour of school-installed integrations. When the UI lands, admins will be able to narrow an app to `org_admin` explicitly.

### How scopes are determined [#how-scopes-are-determined]

Scope limits depend on how the app was registered:

* **Loopwise pre-registered apps** (Claude Code, Cursor, etc.) — the platform applies an audience-based scope ceiling automatically. `org_admin` apps get resource scopes (`courses:*`, `students:*`, `pages:*`, etc.) but never `admin:*`. `member` apps get the identity scopes (`openid profile email`) plus `account:read` / `account:write`, which reach the Member API.
* **School-registered apps** — the admin chooses the app's scopes when creating the application. Audience still controls who can complete OAuth into the app, but the scope set comes from the admin's configuration (subject to platform validation).

### Defense in depth [#defense-in-depth]

The audience gate runs before consent and before token issuance. It's complemented by:

* **Per-audience scope ceiling** for Loopwise pre-registered apps — those apps cannot obtain a scope outside their audience's allowed set, even if their configured scope list ever drifts.
* **Resolver-level scope gates** on the GraphQL API — regardless of how an app's scopes were configured, the API rejects data access that lacks the required scope.
* **Contextual school check** — `org_admin` authorization requires the user to administer **the school selected during the authorize flow**, not just "any" school they happen to administer.

> Loopwise also runs a small number of platform-internal OAuth applications for its own operational tools. Some of those apps use a `staff` audience, but that audience is internal-only: it is not exposed via the school admin UI, cannot be self-registered, and is not part of the public integration surface described above.

## IP allowlisting [#ip-allowlisting]

For enhanced security, we recommend allowlisting the following IP address in your firewall or reverse proxy:

```
52.194.91.27
```

This is the IP address from which Loopwise makes outbound requests (webhooks, callbacks).


---

# AI Agent Integration (https://docs.loopwise.com/guides/agent-integration)



This guide is written for AI agents (or the engineers directing them) building a new integration against a Loopwise school. It covers the **shortest path** from "I have a `client_id` and `client_secret`" to a working OAuth login that knows the user's school and role.

If you are looking for the protocol-level details, read [OAuth Quickstart](/guides/oauth-quickstart) first. This page focuses on the consumer pattern that's productive for agentic workflows: declarative `mapProfileToUser`, no extra GraphQL roundtrips, and a stable "primary role" contract.

## What you get out of `/api/oauth/userinfo` [#what-you-get-out-of-apioauthuserinfo]

A standard OIDC `/api/oauth/userinfo` call against Loopwise returns:

```json
{
  "sub":            "550e8400-e29b-41d4-a716-446655440000",
  "name":           "Jane Doe",
  "email":          "jane@example.com",
  "email_verified": true,
  "org_id":         "7a1e9d5f-3c2b-4a8e-9d3f-0c2b6e8d4f1a",
  "roles":          ["owner", "teacher"]
}
```

Two of these are Loopwise-specific extension claims advertised in [`/.well-known/oauth-authorization-server`](/reference/authorization-endpoints#discovery-endpoint):

* **`org_id`** — the school identifier the access token is bound to. Use it as the tenant key when you store the OAuth user in your own database.
* **`roles`** — the user's roles on that school, ordered by privilege (and may be an empty array if the user has no roles on the bound school). When the array is non-empty, `roles[0]` is contractually the highest-privilege role and is the recommended source for onboarding-time role mapping.

The full claim schema and ordering rules live in the [UserInfo endpoint reference](/reference/token-endpoints#userinfo-endpoint).

## Pattern A: Next.js + better-auth via `@loopwise/admin-sdk` [#pattern-a-nextjs--better-auth-via-loopwiseadmin-sdk]

This is the recommended path if your integration is a Next.js app. The SDK ships a branded better-auth provider that pre-fills Loopwise discovery and PKCE.

```ts
import { betterAuth } from 'better-auth';
import { loopwise } from '@loopwise/admin-sdk/better-auth';

// Map "Loopwise role" → "your app's role" once, at sign-up.
const ROLE_MAP: Record<string, string> = {
  owner:              'admin',
  manager:            'admin',
  admin:              'admin',
  teacher:            'instructor',
  teaching_assistant: 'instructor',
  student:            'member',
};

export const auth = betterAuth({
  // ...your base config
  plugins: [
    loopwise({
      clientId:     process.env.LOOPWISE_CLIENT_ID!,
      clientSecret: process.env.LOOPWISE_CLIENT_SECRET!,
      baseURL:      process.env.LOOPWISE_BASE_URL!,

      mapProfileToUser: (profile) => {
        // `roles[0]` is the highest-privilege role the user holds —
        // when the array is non-empty. Both `org_id` and `roles` may be
        // absent for platform-managed tokens with no school context; we
        // keep `schoolId` optional and fall back to "member" for `role`.
        const primary = (profile.roles as string[] | undefined)?.[0];
        return {
          teachifyUserId: profile.sub as string,
          schoolId:       profile.org_id as string | undefined,
          role: primary ? (ROLE_MAP[primary] ?? 'member') : 'member',
        };
      },
    }),
  ],
});
```

With this in place, your application's user table is populated from a single declarative callback — no follow-up GraphQL call, no scope negotiation, no custom flow.

You'll need to declare each field you persist (`teachifyUserId`, `schoolId`, `role`) as an `additionalField` in your better-auth config and add the matching columns to your schema (e.g. in Prisma):

```ts
betterAuth({
  user: {
    additionalFields: {
      teachifyUserId: { type: 'string', required: false },
      schoolId:       { type: 'string', required: false },
      role:           { type: 'string', required: false },
    },
  },
  // ...
});
```

For the complete end-to-end example, see the [`nextjs-admin-sdk`](https://github.com/Loopwise/templates/tree/main/examples/nextjs-admin-sdk) template.

## Pattern B: Raw OAuth (no SDK) [#pattern-b-raw-oauth-no-sdk]

If you're not on better-auth — say you're writing a Python service, a CLI, or a custom backend — the contract is identical, just plain OAuth + a single HTTP call.

```python
import requests

# Step 1: exchange the authorization code for tokens (already done).
access_token = "..."

# Step 2: fetch user identity.
resp = requests.get(
    "https://your-school-domain.com/api/oauth/userinfo",
    headers={"Authorization": f"Bearer {access_token}"},
)
profile = resp.json()

teachify_user_id = profile["sub"]
school_id        = profile.get("org_id")
primary_role     = (profile.get("roles") or ["member"])[0]
```

Store these three values against your application's user record. That's the onboarding write you need.

## Mapping Loopwise roles to your app's role model [#mapping-loopwise-roles-to-your-apps-role-model]

Loopwise's built-in roles, ordered by privilege:

| Loopwise role        | Typical app-side mapping | Notes                                       |
| -------------------- | ------------------------ | ------------------------------------------- |
| `owner`              | Admin / Owner            | School founder. One per school.             |
| `manager`            | Admin                    | Business admin. Same admin-gate as `owner`. |
| `admin`              | Admin                    | Elevated permissions overlay.               |
| `teacher`            | Instructor / Editor      | Content creator.                            |
| `teaching_assistant` | Instructor (limited)     | Supports teachers, limited write surface.   |
| `student`            | Member / Learner         | The default end-user.                       |

Tenant-defined custom roles (created from the school's admin UI) appear by name after the built-in roles, sorted alphabetically. Map them in your `ROLE_MAP` table the same way:

```ts
const ROLE_MAP: Record<string, string> = {
  owner: 'admin',
  // ...
  '行銷': 'marketing',
  'finance':  'finance',
};
```

If `ROLE_MAP[profile.roles[0]]` is undefined, fall back to a safe default (`'member'` is usually right).

## Edge cases [#edge-cases]

### A user with no `org_id` / `roles` [#a-user-with-no-org_id--roles]

Both claims appear only when the access token carries a school binding — true for every standard OAuth login (the authorize-time school picker writes `school_id` onto the token). If you see a token without these claims, it usually means a platform-managed personal-access flow that hasn't yet bound to a school. Handle this as "no school context yet" rather than as a failure.

### A user who is staff on multiple schools [#a-user-who-is-staff-on-multiple-schools]

A Loopwise user can be staff on more than one school (e.g. a contractor with `teacher` on School A and `manager` on School B). The OAuth token binds to **one** school — the one selected at authorize-time — and `org_id` / `roles` reflect that single school.

If your integration needs the user's full school list, request the `account:read` scope and call the Member API at `{school}/member/graphql`:

```graphql
query {
  viewer {
    id
    schools {
      schoolId
      subdomain
      name
      roles
    }
  }
}
```

This is rarely needed for the agent-onboarding case, but it's there.

### Role changes after sign-in [#role-changes-after-sign-in]

`/api/oauth/userinfo` is a live database lookup — if a user is demoted from `owner` to `manager` after they've signed in, the next userinfo call reflects the new state. Your cached `role` column does not update automatically; refresh it on relevant events (re-login, role-change webhook if you've subscribed, or a scheduled sync).

## Common mistakes [#common-mistakes]

* **Treating `roles` as a permissions list.** It's an identity claim (which roles this user holds), not an authorization claim (what this token can do). The token's actual capabilities are governed by the OAuth scopes — see [Scopes](/reference/scopes).
* **Assuming `roles[0]` is always defined.** A school-bound token whose user has no roles on that school returns `roles: []`. (Separately: tokens with no school context at all omit both `org_id` and `roles` entirely.) Handle both — missing key *and* empty array — and default to your safest fallback (e.g. `'member'`).
* **Requesting `account:read` unnecessarily.** If you only need "the user's primary role on the school they just logged into," `openid` is enough. Adding scopes you don't need triggers unnecessary consent surface and slows down adoption.
* **Hardcoding `roles[0] === 'owner'` checks.** Use a `ROLE_MAP` lookup so tenant-defined custom roles still resolve to a sensible default rather than silently falling through.

## Related references [#related-references]

* [UserInfo endpoint](/reference/token-endpoints#userinfo-endpoint) — full claim schema and the role ordering contract.
* [Scopes](/reference/scopes) — which scopes unlock which data.
* [Authorization Code Flow](/concepts/authorization-code-flow) — the underlying protocol.
* [`@loopwise/admin-sdk` on npm](https://www.npmjs.com/package/@loopwise/admin-sdk) — for calling the admin GraphQL API once the user is authenticated.
* [`nextjs-admin-sdk` template](https://github.com/Loopwise/templates/tree/main/examples/nextjs-admin-sdk) — end-to-end working example.


---

# Custom CSS & JavaScript (https://docs.loopwise.com/guides/custom-code)



Loopwise storefronts can be customized with your own CSS and JavaScript. This
page is the contract for that customization: the DOM selectors you can rely on,
how your CSS and JavaScript are processed before they reach the browser, and how
long changes take to go live.

Set custom code in the school admin under **學院設定 → 網站外觀 → 進階選項**
(**Settings → Site appearance → Advanced**), in the **自訂 CSS** and
**自訂 JavaScript** fields.

## Stable DOM selectors [#stable-dom-selectors]

The selectors below are a published contract. They are covered by a test that
fails if any of them disappears from the storefront, so header/footer injection
and other customizations that target them keep working across releases.

| Selector                                                                                                            | What it is                                                                                                                                                                                                                                     |
| ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `.navbar-wrapper`                                                                                                   | The sticky wrapper around the storefront navbar. To insert a header, use the slots inside it (below) rather than the wrapper's own children.                                                                                                   |
| `.footer-wrapper`                                                                                                   | The wrapper around the footer. Present on every content page and on lecturer profile pages (`/@slug`), even when there is no platform footer to show (the element stays, its contents are empty). To insert a footer, use the slots inside it. |
| `main#content`                                                                                                      | The main content landmark (`<main id="content">`) that wraps every page body between the navbar and footer.                                                                                                                                    |
| `.setting-banner`                                                                                                   | The 200px page banner on settings-style content pages.                                                                                                                                                                                         |
| `.purchased-card`                                                                                                   | The identity class on each card in the learner's "My Courses" list.                                                                                                                                                                            |
| `.mc-page`, `.mc-toolbar`, `.mc-sidebar`, `.mc-course-grid`, `.mc-course-card`, `.mc-empty-state`, `.mc-pagination` | Region hooks for the "My Courses" redesign — page root, toolbar, filter sidebar, course grid, an individual card, the empty state, and pagination.                                                                                             |
| `.mc-card-cover`, `.mc-card-title`                                                                                  | Two internals of an individual `.mc-course-card`: the cover-image wrapper and the course title. Other card internals (rating, footer, progress, CTA) are **not** a contract — target only these two.                                           |

<Callout type="info">
  Any class or id **not** listed here is not a contract. Tailwind utility
  classes, hashed CSS-module names, and internal wrappers can change at any time
  — never target them.
</Callout>

### Insertion slots [#insertion-slots]

Each shell exposes empty elements the platform never renders into. Append your
own markup to a slot instead of inserting next to (or inside) the platform's
element — the slot's position is a promise, the platform element's internals
are not. Beside each pair of slots, a `data-loopwise` marks the platform's own
piece so your CSS can hide it when your version replaces it. (Both are
platform-owned attributes: `data-slot` and `data-part` also appear on component
internals and are not a contract.)

**Storefront** — content pages, and `/@slug` lecturer profiles, which share
the hook names but are their own shell (see the callout below):

| Hook                                   | Where it is                                                                                                                                                                                                                                                                                                                                                               |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `[data-loopwise-slot="header-before"]` | Inside `.navbar-wrapper`, above the platform navbar. Part of the sticky region: a header inserted here sticks together with ours, and — when the school's navbar style is the default (not "fixed") — the desktop bar slides up by its full rendered height on scroll-down, taking your insertion with it. A "fixed" navbar never hides, and neither will your insertion. |
| `[data-loopwise="header"]`             | The platform navbar. Hide it with CSS when your header replaces it.                                                                                                                                                                                                                                                                                                       |
| `[data-loopwise-slot="header-after"]`  | Inside `.navbar-wrapper`, below the platform navbar.                                                                                                                                                                                                                                                                                                                      |
| `[data-loopwise-slot="footer-before"]` | Inside `.footer-wrapper`, above the platform footer.                                                                                                                                                                                                                                                                                                                      |
| `[data-loopwise="footer"]`             | The platform footer (empty when the school disabled it, or on `/@slug`).                                                                                                                                                                                                                                                                                                  |
| `[data-loopwise-slot="footer-after"]`  | Inside `.footer-wrapper`, below the platform footer.                                                                                                                                                                                                                                                                                                                      |

**Learning centre** — the dashboard shell with the learning header and
sidebar: `/learning` (dashboard), `/learning/my-courses`,
`/learning/announcements`, `/learning/assignments` and
`/learning/reservations`, including the assignment and reservation detail
pages under them. A different shell from the storefront — no sticky navbar,
no footer — with the same mechanism under its own names. Lesson players
(`/learning/<course>/…`), assignment submissions (`/learning/submissions/…`)
and the live reservation room (`/learning/reservations/<id>/session`) render
their own full-screen shells and expose **no** slots:

| Hook                                                                                              | Where it is                                                                                      |
| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| `[data-loopwise-slot="learning-header-before"]`, `[data-loopwise-slot="learning-header-after"]`   | Above / below the learning header.                                                               |
| `[data-loopwise="learning-header"]`                                                               | The platform learning header.                                                                    |
| `[data-loopwise-slot="learning-sidebar-before"]`, `[data-loopwise-slot="learning-sidebar-after"]` | Above / below the sidebar, inside the sidebar column — they are hidden with it on small screens. |
| `[data-loopwise="learning-sidebar"]`                                                              | The platform sidebar.                                                                            |

`onReady` below is the helper from [Lifecycle events](#lifecycle-events); the
example does not work without it.

```js
function applyChrome() {
  const slot = document.querySelector(
    '[data-loopwise-slot="header-before"][data-loopwise-live]'
  );
  if (!slot || slot.querySelector('.my-header')) return;
  slot.append(buildHeader()); // your element, with class "my-header"
}
onReady(applyChrome);
document.addEventListener('loopwise:navigate', applyChrome);
```

`data-loopwise-live` is present on every slot, `data-loopwise` part and
`main#content` of the shell currently on screen, and absent on a parked copy
(below). It is set after hydration, so it is there by the time `loopwise:ready`
and `loopwise:navigate` fire; it is not in the server-rendered HTML.

```css
/* Your header replaces ours */
[data-loopwise='header'] {
  display: none;
}
```

<Callout type="warn">
  **Left-behind shells are parked, not removed.** The storefront content
  pages, the `/@slug` profiles and the learning centre are three shells. Moving
  between content pages keeps the same shell, so what you appended stays.
  Crossing into another shell (`/@slug` → `/courses`, or into the learning
  centre) does **not** tear the old one down: the router keeps it in the DOM,
  hidden (`display: none`, out of the accessibility tree), with your nodes still
  inside, and shows it again — nodes included — when the user navigates back.
  Up to two left-behind copies are kept per route level and evicted by count,
  never by time, so right after `/@slug` → `/courses` there are two
  `.navbar-wrapper`s and two of every slot, and `loopwise:navigate` fires while
  the parked one is still there. A bare
  `document.querySelector('[data-loopwise-slot="header-before"]')` may return
  the hidden one, and "my node exists somewhere in the document" is not proof
  that the live slot has it. Select the slot with `[data-loopwise-live]` and
  look for your node **inside that slot**, as in the example above.

  The height rule still applies to layout: anything you insert inside
  `.navbar-wrapper` becomes part of the sticky bar, while with a "fixed"
  navbar the page's top padding is sized for the platform navbar alone (64px
  on desktop). The scroll-down hide distance is not: it follows the wrapper's
  rendered height.
</Callout>

### Course page content hooks [#course-page-content-hooks]

The course page marks its content blocks with `data-loopwise` attributes so
your CSS can target a block without depending on its HTML tags. Heading levels,
list markup and wrapper elements inside these blocks are **not** a contract:
they change as the page's structure and accessibility improve, so a rule such
as `.course-section h2` or `#section-content li` can stop matching, or start
matching something else, after a release. Target the hooks instead. They are in
the server-rendered HTML and, unlike the shell hooks above, carry no
`data-loopwise-live` marker. They are on the standard course page layout; a
crowdfunding course page carries the curriculum hooks but not the sidebar,
lecturer or FAQ ones.

| Hook                                         | What it is                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `[data-loopwise="course-curriculum"]`        | The curriculum block (the element that is also `#section-content`).                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `[data-loopwise="course-curriculum-header"]` | The curriculum's title row: the 課程內容 heading and the unit and hour totals beside it.                                                                                                                                                                                                                                                                                                                                                                                                         |
| `[data-loopwise="course-chapter"]`           | One chapter of the curriculum, with its title row and its lectures.                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `[data-loopwise="course-chapter-title"]`     | A chapter's title row: the heading that holds the expand button, the chapter name, its unit count and duration.                                                                                                                                                                                                                                                                                                                                                                              |
| `[data-loopwise="course-lecture-list"]`      | The list of a chapter's lectures (absent for a chapter with none).                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `[data-loopwise="course-lecture"]`           | One lecture row inside a chapter.                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `[data-loopwise="course-sidebar"]`           | The sidebar column, holding the `course-info` card, what to buy or open the course with, and course recommendations. It is on the page once: on phones it sits between the section tabs and the description, and on wider screens it is the right-hand column. Its plan block is also `#section-plans`, which the plan buttons and links scroll to.                                                                                                                                          |
| `[data-loopwise="course-info"]`              | The sidebar card with the cover and the course contents list. On a free or public course it also holds the go-to-course button once the viewer can open the course. What follows the card sits outside it: the redeem button of a free course not yet redeemed, and on a paid course the plan cards. A viewer who already owns the course sees its one-time plans replaced, in the same place, by a card with go to course and review; plans that can be bought again stay, after that card. |
| `[data-loopwise="course-info-title"]`        | The heading of the card's course contents list (本課程包含以下內容).                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `[data-loopwise="course-lecturers"]`         | The lecturers block (the element that is also `#section-lecturer`).                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `[data-loopwise="course-lecturer"]`          | One lecturer: avatar, name, headline and bio.                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `[data-loopwise="course-lecturer-name"]`     | A lecturer's name heading.                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `[data-loopwise="course-faq"]`               | The FAQ block (the element that is also `#section-faq`).                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `[data-loopwise="course-faq-section"]`       | One FAQ group: its name and its questions.                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `[data-loopwise="course-faq-section-title"]` | A FAQ group's name.                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `[data-loopwise="course-faq-item"]`          | One question with its answer panel.                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `[data-loopwise="course-faq-question"]`      | A question's heading, which holds the button that opens its answer.                                                                                                                                                                                                                                                                                                                                                                                                                          |

```css
/* Drop the divider above each lecture row */
[data-loopwise='course-lecture'] {
  border-top: 0;
}
```

### Hiding the navbar and footer [#hiding-the-navbar-and-footer]

The storefront sets `data-chrome="none"` on `<body>` while a page takes over the
full viewport (for example a live meeting room). This hides both
`.navbar-wrapper` and `.footer-wrapper` via CSS. If your custom CSS injects a
header or footer, scope it so it is also hidden in that state:

```css
body[data-chrome='none'] .my-injected-header {
  display: none;
}
```

## Custom CSS is SCSS [#custom-css-is-scss]

Your custom CSS is compiled as **SCSS** (Sass, SCSS syntax) and served minified.
Plain CSS is valid SCSS, so most stylesheets work unchanged, but you also get
SCSS features: nesting, variables, `&` parent references, and mixins. The
compiler's compressed output normalises your source — attribute-selector quotes
are dropped, so `[data-loopwise="header"]` is served as
`[data-loopwise=header]` — so compare behaviour, not bytes, when checking what
was applied.

<Callout type="warn">
  **Invalid SCSS is rejected on save.** When you save, your SCSS is compiled
  first. If it does not compile, the save fails and the admin shows the exact
  compiler error — nothing is applied. Saving *is* the test; there is no need to
  compile your SCSS elsewhere first. This runs on both the Rails settings form
  and the Admin GraphQL `updateSettings` mutation (the `update_settings` MCP
  tool calls the same mutation), so the same check applies when you edit custom
  CSS through the API or MCP.

  Two conveniences apply on save: a single wrapping `<style>…</style>` is
  unwrapped for you (the same unwrapping also happens when the stylesheet is
  served), and if a school's *already-stored* CSS is broken — saved before this
  validation existed — the appearance-advanced page shows a warning banner and
  the storefront falls back to the **last successfully compiled** CSS rather than
  dropping your styles. That fallback is best-effort: the last-good copy is
  cached and can expire, so a school whose CSS has never compiled successfully
  still serves no custom CSS. You can still save unrelated settings without first
  fixing that legacy CSS.
</Callout>

### The `@import` trap [#the-import-trap]

`@import` means two different things, and only one of them works:

* **CSS `@import`** — pulling in a remote stylesheet or web font — is fine. Both
  the `url()` form and a bare quoted URL survive compilation:

  ```scss
  @import url('https://fonts.googleapis.com/css2?family=Inter&display=swap');
  @import 'https://fonts.googleapis.com/css2?family=Inter&display=swap';
  ```

* **Sass `@import 'partial'`** (importing another Sass file) is **not**
  supported. There is no file system for your partials to live on, so the
  compile fails — and, per the rule above, the save is rejected with that error.
  Put everything in the single field instead.

### No size limit [#no-size-limit]

No layer enforces a size limit on custom CSS. Keep it lean anyway: it is fetched
and parsed on every storefront page load.

### Never inline base64 images [#never-inline-base64-images]

Do **not** embed images as base64 data URIs — neither `background:
url(data:image/…)` in custom CSS nor `<img src="data:image/…">` in markup. A
data URI cannot be cached, compressed, or served independently of the resource
that carries it: it bloats that stylesheet or page, so the image bytes are
re-transferred and re-parsed every time the parent resource is fetched (a cache
miss or revalidation) instead of being cached and reused on their own. Inlining
many images this way is the most common cause of slow custom storefronts. Base64
also adds \~33% overhead versus the original binary.

Host each image as its own file — upload it in the page builder (**新增圖片 /
上傳圖片**) or point at any CDN URL — and reference it by URL:

```css
.hero {
  background-image: url('https://cdn.example.com/hero.webp');
}
```

Referencing by URL lets the browser cache each image on its own and download it
in parallel. It also makes markup images eligible for lazy-loading — add
`loading="lazy"` to an `<img>` to defer offscreen images (CSS background images
are not lazy-loaded automatically).

## Custom JavaScript [#custom-javascript]

Custom JavaScript is **processed in the browser**, not on the server. The
storefront fetches your script and decides how to run it based on its shape:

* **Plain JavaScript** (no `<script>` tag) is loaded and run as a single program,
  **verbatim** — comments and all. It is syntax-checked first; if it does not
  parse, it is not run.
* **HTML markup** with `<script>` tags is parsed: each `<script src="...">`
  becomes an external script, each inline `<script>` block is run, and any loose
  text between blocks is treated as plain JavaScript. Loose code is injected
  **verbatim** — comments are not stripped, so `//` inside string literals and
  URLs stays intact. Each loose fragment is syntax-checked on its own; a fragment
  that does not parse is skipped and logs `console.warn('Custom script fragment
  skipped: invalid JavaScript syntax', …)` with the parser message, while the
  other fragments still run.
* **Mixed or partially-invalid** content falls back to block-by-block parsing so
  individual valid blocks still run.

Syntax checking (via `new Function`) and the `try/catch` wrapper apply to **inline
`<script>` blocks and loose code** recovered from the parsed path. They do **not**
apply to:

* **External `<script src="...">`** — appended as-is; its contents are neither
  fetched nor validated by the loader, and a load failure is logged, not caught.
* **A whole plain program** — loaded verbatim without a `try/catch`, so a runtime
  error in it can surface to the page.

<Callout type="warn">
  Only real JavaScript executes. A `<script type="application/ld+json">` block is
  treated as data and injected verbatim (not validated or wrapped). Any other
  non-JavaScript `type` is left alone.
</Callout>

### When it runs [#when-it-runs]

The loader runs after hydration (never during initial render). Injection timing
then depends on classification:

* A **whole plain program** is appended immediately once fetched and validated.
* **Parsed blocks** (external, inline, and loose code) are scheduled on the window
  `load` event, or via `requestIdleCallback` if the page is already interactive.

Injected scripts are de-duplicated per version, so the same snippet is not added
twice across re-renders — and they are **not re-run on client-side navigation**.
A script runs once per full page load; to react to route changes, listen for
the lifecycle events below.

### Lifecycle events [#lifecycle-events]

The storefront dispatches two `CustomEvent`s on `document`. They are a published
contract, covered by the same test as the selectors above.

| Event               | When                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | `event.detail` |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- |
| `loopwise:ready`    | Once per full page load, after the storefront layout **and its shell** have hydrated: every `data-loopwise-slot` / `data-loopwise` hook the page rendered carries `data-loopwise-live` (a shell that never hydrates releases the event after 5 s). The shell hydrates a little later than the layout around it, and hydration discards nodes appended before it ran, so this is the earliest moment an insertion is safe. On pages that render the platform header and footer, `.navbar-wrapper` and `.footer-wrapper` are in the DOM; bare flows (password reset, redirects) have neither and fire immediately. | `{ pathname }` |
| `loopwise:navigate` | After every client-side navigation that changes the pathname, deferred until the new page has committed — the new route's layout and any content that rendered with it are in the DOM. The exact delay is not a contract (it is one animation frame in a visible tab, a zero-delay timer in a hidden one). Content or `document.title` still streaming behind a loading state can land later. Not fired for query-string-only changes (pagination, filter tabs). If a second navigation lands before the first has fired, only the final destination is announced.                                               | `{ pathname }` |

Custom scripts attach asynchronously — they are fetched after the layout has
hydrated, so by the time your code runs `loopwise:ready` has **already fired**.
Check the `window.loopwise.ready` flag first and only fall back to the event
when it is not yet set:

```js
function onReady(fn) {
  if (window.loopwise?.ready) fn();
  else document.addEventListener('loopwise:ready', fn, { once: true });
}

function applyChrome() {
  const slot = document.querySelector(
    '[data-loopwise-slot="header-before"][data-loopwise-live]'
  );
  if (!slot || slot.querySelector('.my-injected-header')) return;
  slot.append(buildHeader()); // your element, with class "my-injected-header"
}

onReady(applyChrome);
document.addEventListener('loopwise:navigate', applyChrome);
```

<Callout type="warn">
  Handlers must be **idempotent**, and "already inserted" must mean **inside
  the live slot**. The storefront shell (and its slots) survives navigation
  between content pages, so an element you inserted is usually still there when
  the next `loopwise:navigate` fires — inserting again creates duplicates. But
  a shell the user just left is parked, hidden, with your nodes still in it, so
  `document.querySelector('#my-header')` can find a node that is not on
  screen and wrongly skip the live slot. Query inside the live slot
  (`liveSlot.querySelector(...)`, as above), or remove your node and reinsert.

  Page content is parked the same way: after `/courses` → `/posts`, the
  `/courses` page — `.mc-page`, `.mc-course-card` and all — is still in
  `main#content`, hidden, next to the live page, and a third page adds a second
  parked copy. Pages carry no live marker (there is one `main#content` per
  shell, not per page). Filter what you read or change with
  `element.checkVisibility()`; `offsetParent !== null` is not equivalent — it is
  also `null` for the live navbar when the school's navbar style is "fixed".
</Callout>

<Callout type="info">
  `loopwise:ready` guarantees the storefront layout has hydrated — including
  the platform header, footer, slots and `main#content` on pages that render
  them (`main#content[data-loopwise-live]` is the live shell's). Do not insert
  into a slot before it: React's hydration reconciles the server-rendered
  shell and removes nodes it did not render.
  Page content that streams in behind a loading state can still land
  after it — if you depend on a specific page element, check for it in your
  handler or observe it with a `MutationObserver`. Do not read React internals
  (root fiber, `isDehydrated`) to detect hydration; they are not a contract and
  change between React versions.
</Callout>

## Caching and propagation [#caching-and-propagation]

Custom CSS and JavaScript are cached at two layers:

* **Origin** — 5 minutes (`stale-while-revalidate`, `stale-if-error`).
* **Edge** — 300 seconds (`max-age=300, s-maxage=300`).

The storefront requests them with a `?v=<school updated_at>` cache-buster, so a
save that bumps the school's timestamp starts serving the new version as caches
turn over — typically within a few minutes. No manual step is required; the
admin's "revalidate" action does not force an immediate purge, it just relies on
these short TTLs.

<Callout type="info">
  If a change doesn't appear, wait out the \~5 minute window and hard-refresh.
  There is no way to force a global purge faster than the TTL.
</Callout>


---

# Enterprise SSO Integration (https://docs.loopwise.com/guides/enterprise-sso)



> **Note:** This guide covers Enterprise SSO integration where Loopwise acts as an OAuth client connecting to your organization's identity provider. For building third-party applications that access Loopwise data, see the [OAuth Quickstart](/guides/oauth-quickstart).

## Introduction [#introduction]

This guide aims to help enterprise developers understand how to integrate the Loopwise platform with your OAuth provider system. This integration not only enhances security and data privacy but also provides a seamless user experience allowing users to access Loopwise's services using existing enterprise credentials.

## Benefits [#benefits]

1. **Enhanced Security**: Leverages existing authentication mechanisms to reduce potential security risks.
2. **Increased Efficiency**: Users can log in using their company credentials without needing to create new accounts, simplifying the login process.
3. **Unified User Experience**: The integrated system offers a consistent user interface, improving user satisfaction.

## Implementation Steps [#implementation-steps]

Below is a detailed sequence diagram showing the OAuth integration flow:

<Mermaid
  chart="sequenceDiagram
    participant User
    participant Loopwise
    participant AuthEndpoint
    participant TokenEndpoint
    participant UserInfoEndpoint

    User->>+Loopwise: Click &#x22;Login&#x22; on Loopwise
    Loopwise->>+AuthEndpoint: Redirect to Authorization Endpoint
    AuthEndpoint->>+User: Present login and consent page
    User->>+AuthEndpoint: Authenticate and grant consent
    AuthEndpoint->>+Loopwise: Redirect with authorization code
    Loopwise->>+TokenEndpoint: Exchange code for access token
    TokenEndpoint->>+Loopwise: Return access token
    Loopwise->>+UserInfoEndpoint: Request User Info with access token
    UserInfoEndpoint->>+Loopwise: Return User Profile Data
    Loopwise->>+User: Complete login process"
/>

To ensure a successful integration of Loopwise with your OAuth system, it is imperative that the following API endpoints and steps are fully implemented:

1. **Authorization Endpoint**: This endpoint is crucial for the authorization and authentication of users. It initiates the OAuth flow by redirecting users for login and consent, thereby granting Loopwise the necessary permissions to access user data under defined scopes.

2. **Token Endpoint**: After the authorization is complete, your system should redirect the user back to the specified `redirect_uri` with an authorization code. Loopwise will then use this code to request an access token from your token endpoint.

3. **User Information Endpoint**: This endpoint is essential for retrieving basic information about the user once they have been authenticated. Loopwise utilizes this data to personalize and enhance the user experience on our platform.

## IP Allowlisting [#ip-allowlisting]

To enhance security, we recommend setting up IP allowlisting for your OAuth integration. This ensures that only requests from trusted IP addresses are accepted.

### Loopwise IP Address [#loopwise-ip-address]

Please add the following IP address to your allowlist:

```
52.194.91.27
```

Please carefully assess your system's capability to support these endpoints and steps. If there are any uncertainties regarding the specifications or implementation details, do not hesitate to reach out to Loopwise for further clarification or assistance. We are here to support you through every step of the integration process to ensure a seamless and efficient setup.

***

## Authorization Endpoint [#authorization-endpoint]

The Authorization Endpoint is primarily responsible for handling login requests from Loopwise users. When users click the "Login" button within the Loopwise system, they are redirected to your enterprise's login page. This step is the initial phase of the OAuth authentication process, aimed at obtaining user consent and performing authentication.

### Process [#process]

1. User Interaction: The user selects the login option on the Loopwise interface.
2. Redirection: Loopwise redirects the user's browser to your enterprise's Authorization Endpoint URL. This URL typically includes necessary query parameters such as response\_type, client\_id, redirect\_uri, and scope.
3. User Login: Users enter their credentials (e.g., username and password) on your enterprise login page.
4. Login Confirmation and Authorization Code Issuance: Once the credentials are verified as valid, your enterprise's OAuth service automatically redirects the user back to the redirect\_uri provided by Loopwise, along with an authorization code (token).

```
https://yourdomain.com/oauth/authorize?response_type=code&client_id=your_client_id&redirect_uri=https://loopwise.com/callback&scope=profile
```

### Key Parameters [#key-parameters]

* `response_type`: Specifies the type of authorization requested. Here, `code` indicates that the authorization code flow is being used.
* `client_id`: The application identifier assigned to Loopwise by your enterprise OAuth system during the registration process.
* `redirect_uri`: The URI to which the user is redirected after successful authorization, typically carrying the authorization code.
* `scope`: Specifies the extent of access that Loopwise is requesting to the user's information. The scope can include details like `profile` and `email`, which define the specific data Loopwise can access from the user's account.
* `state`: A unique randomly generated value used to mitigate CSRF attacks.

***

## Token Exchange [#token-exchange]

The Token Exchange process is a critical step in the OAuth 2.0 flow, occurring after the user has granted permission to your application. This process involves exchanging the authorization code received from the Authorization Endpoint for an access token, which is then used to make authenticated requests to the Loopwise API on behalf of the user.

### Functionality [#functionality]

After receiving the authorization code, your application must make a secure server-to-server request to exchange this code for an access token.

### Purpose [#purpose]

The Token Exchange process serves to:

1. Verify the authorization code's validity
2. Ensure the request is coming from the same client that initiated the authorization flow
3. Provide a secure method to obtain access tokens

### API Example [#api-example]

```http
POST https://yourdomain.com/oauth/token HTTP/1.1

&code={authorization_code}
&redirect_uri={REDIRECT_URI}
```

### Key Parameters [#key-parameters-1]

* `code`: The authorization code received from the Authorization Endpoint.
* `redirect_uri`: Must match the redirect URI used in the initial authorization request.

### Sample Response [#sample-response]

```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "read write"
}
```

### Fields Explained [#fields-explained]

* `access_token`: The token used to authenticate requests to the Loopwise API.
* `token_type`: Indicates how the access token should be used, typically "Bearer".
* `expires_in`: The lifetime of the access token in seconds.
* `scope`: The scopes granted to this access token.

***

## User Information Endpoint [#user-information-endpoint]

The User Information Endpoint is utilized post-authentication to retrieve essential user information, which can then be used by Loopwise to personalize the user experience or manage user-specific data. This endpoint is crucial for accessing profile details that the user has consented to share under the authorized scopes during the OAuth process.

### Functionality [#functionality-1]

After a successful authentication and authorization process, where the user grants Loopwise permission to access their profile data, Loopwise can request user information from this endpoint using the access token obtained. This ensures that only necessary data is accessed, respecting user privacy and adhering to minimal data access principles.

### Purpose [#purpose-1]

The User Information Endpoint is utilized post-authentication to retrieve essential user information, which can then be used by Loopwise to personalize the user experience or manage user-specific data. This endpoint is crucial for accessing profile details that the user has consented to share under the authorized scopes during the OAuth process.

### API Example [#api-example-1]

```http
GET https://yourdomain.com/oauth/userinfo
Authorization: Bearer access_token
```

### Key Parameters [#key-parameters-2]

`Authorization`: This is a mandatory header where the Bearer `access_token` must be included. The access token is used to authenticate the request, ensuring that the request for user information is authorized.

### Sample Response [#sample-response-1]

The response from the User Information Endpoint typically includes JSON data containing the user's details as specified by the scopes authorized. Below is an example of what this might look like:

```json title="User info example"
{
  "uid": "1234567890",
  "name": "Jane Doe",
  "email": "jane.doe@example.com",
  "picture": "http://example.com/jane.jpg"
}
```

### Fields Explained [#fields-explained-1]

* `uid`: A unique identifier for the user, which is often used by the client to manage user sessions and database records.
* `name`: The full name of the user.
* `email`: The user's email address, which can be used for communication or identification purposes.
* `picture`: A URL to an image file representing the user's profile picture.

This setup allows Loopwise to effectively use the provided user data to enhance user interaction and provide a more tailored educational experience. By securing the endpoint and ensuring data is only available after proper authentication and authorization, both Loopwise and your enterprise can maintain high standards of data privacy and security.


---

# Loopwise Pages (https://docs.loopwise.com/guides/loopwise-pages)



Loopwise Pages lets you deploy a directory of static files (HTML/CSS/JS, plus a
Vite build for SPAs) to a path on an organization's storefront — a landing page,
a microsite, or a full single-page app. This page is the contract for how a
deployment behaves: how it goes live, where you can preview it, why asset
requests redirect off-origin, what wins when a page's path collides with a
built-in route, how long changes take to propagate, and the size limits that are
actually enforced.

You deploy either with the Loopwise CLI (`loopwise pages push`) or with the
`deploy_static_page` / `prepare_deployment` MCP tools. The lifecycle below is the
same for both, but note the size limits differ between the single-shot and
multiphase paths (see [Size limits](#size-limits)).

## Deployment lifecycle [#deployment-lifecycle]

A deployment is an immutable snapshot. **Uploading** a new bundle never changes
what visitors see on its own — but how it goes live depends on `is_preview`. A
non-preview deployment (the CLI and MCP default) goes **live on completion**, with
no separate `promote_deployment` step. A preview deployment stays hidden behind the
current live one until you promote it.

<Mermaid
  chart="flowchart LR
  A[Prepare / push bundle] --> B[Upload assets]
  B --> C[Complete deployment]
  C --> D{is_preview?}
  D -->|true| E[Preview only<br/>previous deploy stays live]
  D -->|false| F[Live at path_prefix]
  E -->|promote_deployment| F"
/>

* **Prepare / push** — the CLI's `pages push` walks the directory and uploads it;
  the multi-phase MCP flow is `prepare_deployment` → `upload_asset` × N →
  `complete_deployment`. `deploy_static_page` collapses all of that into one call
  for small bundles.
* **Preview vs live** — deploying with `--preview` (CLI) or `is_preview: true`
  (MCP) marks the deployment as a preview. The page keeps serving its previous
  live deployment at its `path_prefix`, so a preview alone never changes what
  visitors see.
* **Promote** — `promote_deployment` cuts live traffic over to a preview
  deployment. Rollback is the same operation pointed at an earlier deployment —
  each one is a complete snapshot. The switch itself is a single pointer update,
  but it is not visible everywhere at once: allow for the propagation window
  below.

<Callout type="info">
  Loopwise Pages is available to every organization — there is no plan gating on
  deploying or serving a page.
</Callout>

## Preview surfaces [#preview-surfaces]

A deployment can be reached from two different hosts, and they behave
differently. Pick the one that matches what you're testing.

| Surface             | URL shape                                     | Auth / cart / member content                                                          | Cache                   |
| ------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------- | ----------------------- |
| **Tenant origin**   | `<tenant-origin>/_preview/<scriptName>/?pt=…` | Full — same-origin to the storefront BFF, so login, cart, and member-gated reads work | Not cached (`no-store`) |
| **Loopwise origin** | `https://<scriptName>.loopwise.page`          | Anonymous reads only — cross-origin to the tenant                                     | Edge-cacheable          |

The tenant-origin preview carries a signed `pt` token and is the URL you share
for QA. The MCP deploy tools return it as `preview_url`, with the
`loopwise.page` cross-origin fallback as `preview_url_loopwise_origin`. Use the
tenant-origin surface whenever you need to test anything that depends on the
member session (login, cart, gated content); use the `loopwise.page` surface for
a shareable, anonymous preview before the organization has its own domain.

Both preview surfaces render the bundle **without** the storefront header/footer
— that is true for embedded pages too. (The tenant-origin preview also injects a
`<base href="/_preview/<scriptName>/">` into HTML that has no author-provided
`<base>`, so relative asset paths resolve — it is not a byte-for-byte copy.) A
preview without header/footer is not evidence that embedded rendering is broken;
an embedded page only renders inside the organization's chrome once a non-preview
deployment is live.

## Why assets redirect to \*.loopwise.page [#why-assets-redirect-to-loopwisepage]

<Callout type="info">
  Every tenant host — `*.kaik.io`, `*.myteachify.com`, and a school's own custom
  domain — is served today through the Next.js storefront path. The asset `302`
  redirect and the root-page `/`-only match described here apply on all of them.
</Callout>

On a **live** deployment served over the **Next.js storefront path** (the shared
`*.myteachify.com` / `*.kaik.io` origin, and any custom domain), the **document** is
served same-origin, and requests for **static asset files** — those with a
recognized asset extension (`.css`, `.js`, images, fonts, etc.) — **302-redirect**
to `https://<scriptName>.loopwise.page/…`. The redirect only changes where the
asset **bytes** come from (the Cloudflare CDN); it is a `302` (not `301`) because
the `scriptName` changes on every deployment, and it carries
`Cache-Control: no-store` so no intermediary pins a redirect to a now-stale
`scriptName`. Only **extensionless** paths — including the routes that serve your
HTML documents (for example `/` or `/about`) — and paths whose extension is **not**
on the static-asset list (for example `.csv`) are served same-origin. A path with
a recognized extension is redirected regardless of what it holds: `.html`, `.htm`,
`.json`, `.xml`, and `.txt` are on the static-asset list too, so navigating
directly to `/about.html` lands on `loopwise.page` and makes the **document**
itself cross-origin. Link between pages with extensionless routes to keep the
document same-origin.

The redirect does **not** change a script's execution origin. A `<script>` on a
live tenant-origin document executes in that document's origin regardless of
where its bytes were fetched from, so a root-relative `fetch('/…')` resolves
against the tenant host and carries the member session — authenticated calls work
on live pages with no special handling.

The cross-origin caveat applies only to the `loopwise.page` **document** surface:
if you open the page itself at `https://<scriptName>.loopwise.page`, the document
origin is `loopwise.page`, so calls back to the tenant are cross-origin and
anonymous. The tenant-origin preview (`/_preview/<scriptName>/…`) keeps the
document same-origin (and proxies its relative assets with `no-store`), which is
why it is the surface for testing authenticated flows.

<Callout type="warn">
  Use the `loopwise.page` host only for anonymous, shareable previews. For
  anything that depends on the member session (login, cart, gated content), keep
  the **document** on the tenant origin — the live URL or the tenant-origin
  preview (`/_preview/<scriptName>/`) — and use the
  [Loopwise SDK](https://docs.loopwise.com/guides/agent-integration) for API
  calls. Do not open the document on `loopwise.page` and expect an authenticated
  session.
</Callout>

## Route priority: what wins over built-in routes [#route-priority-what-wins-over-built-in-routes]

A page mounted at a `path_prefix` **shadows** the storefront's built-in route at
that path. Three rules decide who serves a request:

1. **Tenant URL redirects run first — except on origin-bound paths.** For
   requests the storefront middleware handles, a configured redirect normally
   takes precedence over both a deployed page and a built-in route. The
   exception is a set of machine-readable, origin-bound paths that redirects
   never rewrite: `/mcp` and `/mcp/…`, `/oauth/…`,
   `/.well-known/…`, `/skills/…`, `/account/graphql`, and the discovery files
   `/llms.txt`, `/llms-full.txt`, `/openapi.json`, `/auth.md`, `/pricing.md`.
   `/api/…` is exempt for a different reason: the middleware matcher excludes it
   (`api(?:/|$)`), so those requests never enter `findAndApplyRedirect` at all —
   a redirect can never win for an `/api/…` path.

2. **A deployed page shadows built-in routes — but can only mount outside the
   reserved prefixes.*&#x2A; You cannot create a page under a reserved system prefix:
   the backend rejects the mount at write time with &#x2A;"is reserved by the platform
   and cannot be used"* (`Page#path_prefix_not_reserved`), so there is no way to
   end up with a silently unreachable mount. The reserved prefixes are:

   `/api`, `/admin`, `/oauth`, `/auth`, `/cable`, `/graphql`, `/assets`,
   `/locales`, `/mcp`, `/member`, `/developer-portal`, `/developers`, `/_next`,
   `/_preview`, `/lw-preview`, `/_lw`, `/lw-pages`, `/.well-known`, and the member
   area: `/hub`, `/my`, `/my-courses`, `/my-events`, `/my-digital-downloads`

3. **The root path matches only `/`.** A page mounted at `path_prefix: "/"`
   replaces the homepage. It matches **only** `/`, so built-in routes such as
   `/courses` and `/checkout` keep working and are never captured by a root page.

So a page mounted at `/faq` serves `/faq` in place of any built-in `/faq`, but a
request to a reserved prefix such as `/api/...` or `/oauth/...` always reaches the
platform. A path that is *not* reserved (for example `/login`) can be mounted by a
page and will then shadow the built-in route — only the root page is restricted to
an exact `/` match.

<Callout type="info">
  The reserved list lives in two places that are kept in step but do **not**
  mirror exactly: the backend (`Page::RESERVED_PATH_PREFIXES`) is authoritative
  for what you can mount, while the frontend
  (`lib/loopwise-pages/excluded-prefixes.ts`) omits `/_lw` on purpose — that
  namespace is handled by the frontend's mount-independent asset branch instead
  of being skipped.
</Callout>

### Shadowing also moves the agent-facing surfaces [#shadowing-also-moves-the-agent-facing-surfaces]

Shadowing a built-in route swaps out more than the HTML page. When a page mounts
at, say, `/faq`, the platform stops treating that path as its own:

* **The markdown twin no longer serves built-in content.** A request for
  `/faq.md` `307`s to your deployed `/faq`; a request to `/faq` with
  `Accept: text/markdown` is served straight from your deployment by the
  Loopwise route match (no redirect). Either way an agent lands on the same page
  humans see, not the built-in FAQ markdown.
* **`llms.txt` drops the built-in twin.** The per-tenant `llms.txt` /
  `llms-full.txt` stop advertising the shadowed path's built-in `.md` twin,
  because it would only redirect back onto your page.
* **Built-in structured data is gone.** The built-in FAQ page emits `FAQPage`
  JSON-LD; a deployed page renders none unless you include it. **If you rely on
  rich results or want agents to read structured data, embed your own JSON-LD in
  the page's HTML** — a standalone (full-page) deployment's `<script
  type="application/ld+json">` is served through untouched.

The twins reconciled in `llms.txt` are the concrete built-ins (`/`, `/faq`,
`/courses`, `/lecturers`, `/search`) plus any per-slug family whose fixed
ancestor you mount — mounting `/courses` also drops `/courses/:slug`, because the
built-in course-detail markdown is no longer served under that prefix. What a
`.md` request does depends on where it sits relative to the mount:

* **The mount's own twin** (`/faq.md` for a `/faq` mount, or `/courses/foo.md`
  when `/courses/foo` is itself the mounted leaf) `307`s to the HTML path.
* **Anything inside a mounted subtree** (`/courses/foo.md` under a `/courses`
  mount, `/faq/index.md` under a `/faq` mount) is served straight from your
  deployment like every other path you own there, including `.md` files you
  deploy yourself — no built-in twin is involved, so there is nothing to redirect.

What `llms.txt` can't decide for a single-slug mount is whether to drop the whole
`/courses/:slug` pattern, so it keeps the pattern unless the fixed ancestor
itself is mounted.

## Propagation timing [#propagation-timing]

Promoting a deployment (or deploying a non-preview) is not instantaneous
end-to-end. The route table and the CDN each hold the previous state briefly. The
edge dispatch worker starts routing within **\~30 seconds*&#x2A; (Cloudflare KV), but a
custom production domain is served through a CloudFront-cached lookup. Promote and
rollback actively invalidate that lookup entry, so it normally refreshes within
**\~1–2 minutes*&#x2A;; if the invalidation is delayed or retried (transient CloudFront
throttling backs off progressively, up to \~10 minutes), the previous route can
stay visible for up to the CloudFront TTL (**\~10 minutes**). Allow that longer
window before judging the result, and verify from a fresh or
incognito session so you're not seeing a locally cached response. When verifying
a live deploy, request `<tenant-origin><path_prefix>` directly (for example with
`curl`).

## Size limits [#size-limits]

The limit that applies depends on how you deploy. Both paths cap a deployment at
**10,000 files**, cap any single file at **25 MiB** (Cloudflare Workers Assets
rejects larger files on every path), and require an `index.html` at the bundle
root.

| Deploy path                                                                    | Limit                                                                                                                                                                        |
| ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Single-shot — CLI `pages push`, MCP `deploy_static_page`                       | **100 MB request body**, &#x2A;*25 MiB per file.** The whole bundle is sent as one JSON request; binary files are base64-encoded and count \~33% larger than their raw size. |
| Multiphase — MCP `prepare_deployment` → `upload_asset` → `complete_deployment` | **100 MB raw total**, **25 MiB per file** (raw staged bytes, no base64 inflation).                                                                                           |

For a large binary-heavy bundle, prefer the multiphase flow — the single-shot
100 MB is measured on the base64-expanded request, so its effective raw capacity
is roughly 75 MB.

<Callout type="info">
  Images: the MCP tools expose an image pipeline (`upload_image` →
  `confirm_upload`) that returns a CDN URL — reference that URL in your HTML
  instead of bundling the bytes, which keeps the request small and applies
  metadata stripping. The CLI has no image command, so `pages push` bundles image
  files directly; keep them within the single-shot request-body limit above.
</Callout>


---

# Managing OAuth Applications (https://docs.loopwise.com/guides/managing-applications)



OAuth applications are managed through the school admin UI. Pre-registered vendor platforms retrieve their credentials — rather than manage applications — via the client registration endpoint.

## Admin UI [#admin-ui]

School administrators can manage OAuth applications at **Settings > OAuth Applications**.

### Creating an application [#creating-an-application]

1. Navigate to **Settings > OAuth Applications**
2. Click **New Application**
3. Fill in the application details:
   * **Name** — a descriptive name shown on the consent screen
   * **Redirect URIs** — one or more callback URLs (one per line)
   * **Scopes** — the permissions this application can request
   * **Confidential** — check this if your application can securely store a client secret
4. Click **Create**

After creation, you'll see the `client_id` and `client_secret` (if confidential). Store the secret securely — it cannot be retrieved later.

### Editing an application [#editing-an-application]

From the application list, click the application name to view its details. You can update the name, redirect URIs, and scopes. The `client_id` cannot be changed.

### Revoking an application [#revoking-an-application]

Deleting an application immediately revokes all access tokens and refresh tokens issued to it. Users who authorized the application will need to re-authorize if a new application is created.

## Client registration for vendor platforms [#client-registration-for-vendor-platforms]

For automated integrations (such as MCP clients like Claude Code or Cursor), the registration endpoint issues credentials for **pre-registered vendor platforms** only: it matches your `client_name` against a known integration and returns that platform's credentials. It is not open dynamic client registration ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)) — an unrecognized `client_name` is refused with `invalid_client_metadata`.

```bash
POST /api/oauth/register
Content-Type: application/json

{
  "client_name": "Claude Code",
  "redirect_uris": ["http://127.0.0.1:41234/callback"],
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"],
  "token_endpoint_auth_method": "none"
}
```

### Known platforms [#known-platforms]

Loopwise recognizes the following client names and maps them to pre-registered platform applications. Loopwise's own internal clients are pre-registered too, but they answer to a fixed client ID rather than a name, so they never appear through this path and are not listed:

| Client name pattern | Platform    |
| ------------------- | ----------- |
| `Claude`            | Claude Code |
| `Cursor`            | Cursor      |
| `Windsurf`          | Windsurf    |
| `Replit`            | Replit      |
| `Lovable`           | Lovable     |
| `Bolt`              | Bolt        |
| `Codex`             | Codex       |
| `Antigravity`       | Antigravity |

When a known platform registers, Loopwise returns the pre-registered application credentials for that platform. This ensures a consistent experience — users see the correct platform name on the consent screen.

An unrecognized `client_name` is refused with `invalid_client_metadata`; the endpoint does not register arbitrary clients. A client that is not a pre-registered vendor identifies via a [Client ID Metadata Document](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/) instead — publish the document over HTTPS and use its URL as your `client_id`, where the server permits the document's host.

The registration response lists only the `redirect_uris` the platform application will accept at the authorization endpoint. A redirect URI you declared that is missing from the response will be refused there; use one that is listed.

## Client ID Metadata Documents [#client-id-metadata-documents]

The discovery metadata advertises `client_id_metadata_document_supported: true`, so an MCP client that supports [Client ID Metadata Documents](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/) uses the HTTPS URL of its document as its `client_id` and skips the registration endpoint. Loopwise fetches the document, and the `redirect_uris` it lists are the ones the authorization endpoint accepts. A loopback redirect (`http://127.0.0.1/...` or `http://localhost/...`) matches on any port.

Documents served from these hosts are trusted with the same permissions as a pre-registered vendor platform:

| Host          | Clients                                       |
| ------------- | --------------------------------------------- |
| `claude.ai`   | Claude (web, desktop and mobile), Claude Code |
| `chatgpt.com` | ChatGPT, Codex                                |
| `vscode.dev`  | Visual Studio Code                            |

The consent screen names the host serving the document and the host the browser returns to, so users can see who they are authorizing. Connections made earlier through the registration endpoint keep working; only new connections switch to the document.

## Discovery endpoint [#discovery-endpoint]

Applications can discover OAuth configuration automatically via the well-known metadata endpoint:

```bash
GET /.well-known/oauth-authorization-server
```

This returns all endpoint URLs, supported scopes, and the default MCP client ID. See [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) for the full specification.


---

# OAuth Quickstart (https://docs.loopwise.com/guides/oauth-quickstart)



This guide walks you through the complete OAuth 2.0 integration flow with Loopwise — from registering a client to making your first authenticated API request.

## Prerequisites [#prerequisites]

* A Loopwise school with admin access
* An application that can make HTTPS requests — either a server-side app or a browser-only public client
* A publicly accessible redirect URI

## Overview [#overview]

Loopwise uses the **Authorization Code flow with PKCE** (RFC 7636):

<Mermaid
  chart="flowchart LR
    A[Register app] --> B[Redirect user\nto authorize]
    B --> C[User logs in\n& grants consent]
    C --> D[Exchange code\nfor tokens]
    D --> E[Call API]"
/>

For a detailed explanation of each step, see [Authorization Code Flow](/concepts/authorization-code-flow).

## Step 1: Register your application [#step-1-register-your-application]

You can register an OAuth application in two ways:

### Option A: Admin UI [#option-a-admin-ui]

Navigate to your school's admin panel at **Settings > OAuth Applications** and create a new application. You'll receive a `client_id` and `client_secret`.

### Option B: Vendor platform registration [#option-b-vendor-platform-registration]

The registration endpoint issues credentials for pre-registered vendor platforms only (Claude Code, Cursor, and the like): it matches your `client_name` against a known integration and returns that platform's `client_id`. It is not open dynamic client registration — an unrecognized `client_name` is refused with `invalid_client_metadata`.

```bash
curl -X POST https://your-school-domain.com/api/oauth/register \
  -H "Content-Type: application/json" \
  -d '{
    "client_name": "Claude Code",
    "redirect_uris": ["http://127.0.0.1:41234/callback"],
    "grant_types": ["authorization_code", "refresh_token"],
    "response_types": ["code"],
    "token_endpoint_auth_method": "none"
  }'
```

The response includes your `client_id`:

```json
{
  "client_id": "abc123...",
  "client_name": "Claude Code",
  "redirect_uris": ["http://127.0.0.1:41234/callback"],
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"],
  "token_endpoint_auth_method": "none",
  "scope": "openid profile email courses:read courses:write students:read students:write analytics:read curriculum:read curriculum:write orders:read school:read"
}
```

A client that is not a pre-registered vendor identifies via a [Client ID Metadata Document](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/) instead — publish the document over HTTPS and use its URL as your `client_id`, where the server permits the document's host.

## Step 2: Redirect the user to authorize [#step-2-redirect-the-user-to-authorize]

Build the authorization URL and redirect the user's browser:

```
https://your-school-domain.com/oauth/authorize?
  response_type=code
  &client_id=YOUR_CLIENT_ID
  &redirect_uri=https://myapp.com/callback
  &scope=openid+profile+email+courses:read+students:read
  &state=RANDOM_STATE_VALUE
  &code_challenge=PKCE_CHALLENGE
  &code_challenge_method=S256
```

The user will see a consent screen showing the requested scopes. The token will be scoped to the school where your OAuth application is registered.

## Step 3: Exchange the code for tokens [#step-3-exchange-the-code-for-tokens]

After the user authorizes, Loopwise redirects to your `redirect_uri` with a `code` parameter. Exchange it for tokens:

```bash
curl -X POST https://your-school-domain.com/api/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "code=AUTHORIZATION_CODE" \
  -d "redirect_uri=https://myapp.com/callback" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "code_verifier=PKCE_VERIFIER"
```

Response:

```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "Bearer",
  "expires_in": 7200,
  "refresh_token": "def456...",
  "scope": "openid profile email courses:read students:read",
  "school_id": "550e8400-e29b-41d4-a716-446655440000",
  "school_subdomain": "demo"
}
```

### Calling from a browser [#calling-from-a-browser]

The token, userinfo and revoke endpoints, and the discovery documents they are found through, answer cross-origin requests: `Access-Control-Allow-Origin: *`. A browser-only public client needs no backend.

Step 2 stays a navigation, not a `fetch` — `/oauth/authorize` renders the login and consent screens, and the user returns to your redirect URI with the code. Everything either side of that is a cross-origin `fetch`: discovery, the token exchange, userinfo, revoke.

One constraint follows from that wildcard. `Access-Control-Allow-Credentials` is never set, so a browser refuses to expose the response to a request made with `credentials: 'include'` — a session cookie gets you nothing here. Send the access token in an `Authorization: Bearer` header instead:

```js
const res = await fetch(`${SCHOOL_URL}/api/oauth/userinfo`, {
  headers: { Authorization: `Bearer ${accessToken}` },
});
```

Because the client cannot keep a secret, register it as a public client and use PKCE — which is the flow this guide already describes.

## Step 4: Make API requests [#step-4-make-api-requests]

Use the access token in the `Authorization` header:

```bash
curl https://your-school-domain.com/api/v1/courses \
  -H "Authorization: Bearer ACCESS_TOKEN"
```

## Refreshing tokens [#refreshing-tokens]

Access tokens expire after 2 hours (30 days for Loopwise CLI). Use the refresh token to get a new access token:

```bash
curl -X POST https://your-school-domain.com/api/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=refresh_token" \
  -d "refresh_token=REFRESH_TOKEN" \
  -d "client_id=YOUR_CLIENT_ID"
```

Response:

```json
{
  "access_token": "new-access-token...",
  "token_type": "Bearer",
  "expires_in": 7200,
  "refresh_token": "new-refresh-token...",
  "scope": "openid courses:read students:read"
}
```

### Token rotation policy [#token-rotation-policy]

<Callout type="warn">
  **You must persist the new `refresh_token` from every refresh response.** Loopwise uses refresh token rotation — the old refresh token is revoked immediately after use. If you discard the new one, your integration silently loses access with no error until the next refresh attempt fails.
</Callout>

Every successful call to `/api/oauth/token` with `grant_type=refresh_token` returns a **new refresh token** alongside the new access token. The previous refresh token is **revoked immediately** and cannot be reused.

This is a security measure ([RFC 6749 §10.4](https://datatracker.ietf.org/doc/html/rfc6749#section-10.4)) — if a refresh token is leaked, it can only be used once before it's invalidated.

**Correct implementation:**

```javascript
async function refreshAccessToken(storedRefreshToken) {
  const res = await fetch(`${SCHOOL_URL}/api/oauth/token`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'refresh_token',
      refresh_token: storedRefreshToken,
      client_id: CLIENT_ID,
    }),
  });

  if (!res.ok) {
    // Token may have been rotated already — re-authenticate
    throw new Error(`Refresh failed: ${res.status}`);
  }

  const data = await res.json();

  // IMPORTANT: persist the NEW refresh token for next time
  await db.set('oauth_tokens', {
    access_token: data.access_token,
    refresh_token: data.refresh_token,  // ← always save the new one
    expires_at: Date.now() + data.expires_in * 1000,
  });

  return data.access_token;
}
```

**Common mistake** — only saving the access token:

```javascript
// ❌ WRONG: discards the new refresh_token
const data = await res.json();
await db.set('access_token', data.access_token);
// Next refresh attempt will fail with invalid_grant because
// the old refresh_token was already revoked
```

### What happens when refresh fails [#what-happens-when-refresh-fails]

If you submit a revoked or expired refresh token, the server returns:

```json
{
  "error": "invalid_grant",
  "error_description": "The authorization grant provided is invalid, expired, or revoked. For refresh tokens: token rotation is enabled — each /api/oauth/token response returns a new refresh_token that must be saved and used (the old one becomes invalid immediately). For authorization codes: codes are single-use and expire after 10 minutes — please exchange the code for an access_token as soon as possible after receiving it.",
  "error_uri": "https://docs.loopwise.com/reference/errors#invalid_grant"
}
```

If you submit a refresh token that was **already used** (rotation reuse), the server returns a more specific message:

```json
{
  "error": "invalid_grant",
  "error_description": "This refresh token has already been used. Refresh token rotation is enabled — each call to /api/oauth/token returns a new refresh_token that must replace the old one. The previous token is revoked the moment the new one is issued; if you see this error, your process likely lost the rotated value (e.g. crash mid-rotation) and the user must restart the OAuth authorize flow.",
  "error_uri": "https://docs.loopwise.com/reference/errors#invalid_grant"
}
```

**Recovery:** Re-authenticate the user by starting the [authorization code flow](#step-2-redirect-the-user-to-authorize) again.

### Token lifecycle summary [#token-lifecycle-summary]

| Token              | Lifetime                    | Rotation                                     |
| ------------------ | --------------------------- | -------------------------------------------- |
| Access token       | 2 hours (30 days for CLI)   | No rotation — just expires                   |
| Refresh token      | Valid until used or revoked | Rotated on every use — new token in response |
| Authorization code | 10 minutes                  | Single-use                                   |

## Next steps [#next-steps]

* [Available scopes](/reference/scopes) — see what data you can access
* [Authorization Code Flow](/concepts/authorization-code-flow) — understand the flow in detail
* [Token Endpoints](/reference/token-endpoints) — full token endpoint reference


---

# Storefront content API (https://docs.loopwise.com/guides/storefront-content-api)



Every Loopwise storefront exposes its public catalog as **agent-friendly
markdown**, so an AI agent can read a course or lecturer page without parsing
HTML. All paths are served per storefront origin — substitute the
storefront's host below.

## Markdown content endpoints [#markdown-content-endpoints]

```
GET https://school.example/api/md/{resource}
```

| Path                               | Content            |
| ---------------------------------- | ------------------ |
| `/api/md/home`                     | Homepage           |
| `/api/md/faq`                      | FAQ                |
| `/api/md/courses`                  | Course index       |
| `/api/md/courses/{slug}`           | A course           |
| `/api/md/posts/{slug}`             | A post             |
| `/api/md/events/{slug}`            | An event           |
| `/api/md/digital-downloads/{slug}` | A digital download |
| `/api/md/plans/{slug}`             | A membership plan  |
| `/api/md/categories/{slug}`        | A category         |
| `/api/md/lecturers`                | Lecturer index     |
| `/api/md/lecturers/{slug}`         | A lecturer profile |

Each returns `text/markdown` with YAML frontmatter.

## Content negotiation [#content-negotiation]

The same markdown is available on the equivalent HTML page by sending an
`Accept: text/markdown` header — no separate URL needed:

```bash
curl -H "Accept: text/markdown" https://school.example/courses/my-course
```

<Callout type="warn">
  On enterprise-training storefronts the HTML content pages are
  authentication-gated *before* the markdown rewrite runs, so this
  content-negotiation form can return a login redirect for an anonymous
  agent. The `/api/md/*` endpoints above bypass that gate and stay readable
  without a session — prefer them when you may be anonymous.
</Callout>

## Bulk index [#bulk-index]

* `GET /llms.txt` — a compact, linked index of the storefront's content and
  its developer/agent resources.
* `GET /llms-full.txt` — a single-document bundle of the content.

## Machine-readable spec [#machine-readable-spec]

The authoritative, per-origin description of these endpoints (plus the
OAuth 2.0 / OpenID Connect endpoints) is published as OpenAPI 3.0:

```
GET https://school.example/openapi.json
```

Its `servers[].url` is the requested origin, so the spec is directly usable
against the storefront it was fetched from. To discover this and every other
agentic resource from one place, start at the
[AI Catalog](/concepts/agent-discovery).


---

# Zapier Quickstart (https://docs.loopwise.com/guides/zapier)



All endpoints require authentication with an API key. You can obtain the API key from your school's integration settings in the Zapier dashboard.

## Me [#me]

Get the name of the school associated with the API key.

```bash title="cURL"
curl -X GET \
    -H "Authorization: Bearer {api_key}" \
    https://yourdomain.com/api/v1/zapiers/me
```

```ruby title="Ruby"
require 'uri'
require 'net/http'

url = URI("https://yourdomain.com/api/v1/zapiers/me")

https = Net::HTTP.new(url.host, url.port);
https.use_ssl = true

request = Net::HTTP::Get.new(url)
request["Authorization"] = "Bearer {api_key}"

response = https.request(request)
puts response.read_body
```

## Enroll Course [#enroll-course]

Get a list of StudentCourseShip records for courses belonging to the school that were created in the past 30 minutes.

```bash title="cURL"
curl -G https://kaik.io/v1/api/v1/zapiers/enroll_course \
  -H "Authorization: Bearer {token}"
```

```ruby title="Ruby"
require 'net/http'
require 'uri'

url = URI('https://kaik.io/v1/api/v1/zapiers/enroll_course')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
request['Authorization'] = 'Bearer {token}'

response = http.request(request)
puts response.read_body
```

```json
// Response
// Status: 200 OK
// Body:
[
  {
    "id": "b20784f1-e0d1-46c8-ba6b-9e2d3266da23",
    "course": {
      "id": "b051c891-9201-4056-a7b9-2e28c23cbfbf",
      "name": "Math",
      "slug": "math",
      "subtitle": "Introduction to Math",
      "description": "This course provides an introduction to mathematics for beginners."
    },
    "user": {
      "name": "John Doe",
      "email": "johndoe@example.com",
      "phone_number": "1234567890"
    }
  },
  {
    "id": "cecf1c7b-5a8e-41d2-ae5c-846fb7bfc404",
    "course": {
      "id": "534456eb-1b70-4d4d-90f6-7f0575c21ac9",
      "name": "English",
      "slug": "english",
      "subtitle": "Introduction to English",
      "description": "This course provides an introduction to English for beginners."
    },
    "user": {
      "name": "Jane Doe",
      "email": "janedoe@example.com",
      "phone_number": "1234567890"
    }
  }
]
```

## New User [#new-user]

Get a list of User records for students belonging to the school that were created in the past 30 minutes.

```bash title="cURL"
curl -G https://kaik.io/v1/api/v1/zapiers/new_user \
  -H "Authorization: Bearer {token}"
```

```ruby title="Ruby"
require 'net/http'
require 'uri'
require 'json'

uri = URI('https://kaik.io/v1/api/v1/zapiers/new_user')

request = Net::HTTP::Get.new(uri)
request['Authorization'] = 'Bearer {token}'

response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  http.request(request)
end

puts response.body
```

```json
// Response
// Status: 200 OK
// Body:
[
  {
    "id": "b20784f1-e0d1-46c8-ba6b-9e2d3266da23",
    "name": "John Doe",
    "email": "johndoe@example.com",
    "phone_number": "1234567890"
  },
  {
    "id": "cecf1c7b-5a8e-41d2-ae5c-846fb7bfc404",
    "name": "Jane Doe",
    "email": "janedoe@example.com",
    "phone_number": "1234567890"
  }
]
```

## New Transaction [#new-transaction]

Get a list of `Payment` records for payments belonging to the school that were paid in the past 30 minutes.

```bash title="cURL"
curl -G https://kaik.io/api/v1/zapiers/new_transaction \
  -H "Authorization: Bearer {token}"
```

```ruby title="Ruby"
require 'uri'
require 'net/http'

url = URI("https://kaik.io/api/v1/zapiers/new_transaction")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Get.new(url)
request["Authorization"] = "Bearer {token}"

response = http.request(request)
puts response.read_body
```

```json
// Response
// Status: 200 OK
// Body:
[
  {
    "id": "b20784f1-e0d1-46c8-ba6b-9e2d3266da23",
    "trade_no": "TRADE20220420123456",
    "currency": "TWD",
    "amount": 5000.0,
    "user": {
      "name": "John Doe",
      "email": "johndoe@example.com",
      "phone_number": "1234567890"
    }
  },
  {
    "id": "cecf1c7b-5a8e-41d2-ae5c-846fb7bfc404",
    "trade_no": "TRADE20220420123457",
    "currency": "USD",
    "amount": 100.0,
    "user": {
      "name": "Jane Doe",
      "email": "janedoe@example.com",
      "phone_number": "1234567890"
    }
  }
]
```

## New Comment [#new-comment]

Get a list of Comment records for comments belonging to the school that were created in the past 30 minutes.

```bash title="cURL"
curl -G https://kaik.io/api/v1/zapiers/new_comment \
  -H "Authorization: Bearer {token}"
```

```ruby title="Ruby"
require 'net/http'

uri = URI('https://kaik.io/api/v1/zapiers/new_comment')

req = Net::HTTP::Get.new(uri)
req['Authorization'] = 'Bearer {token}'

res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  http.request(req)
end

puts res.code
puts res.body
```

```json
// Response
// Status: 200 OK
// Body:
[
  {
    "id": "b20784f1-e0d1-46c8-ba6b-9e2d3266da23",
    "content": "This is a comment.",
    "created_at": "2023-04-20T09:30:00.000Z",
    "user": {
      "name": "John Doe",
      "email": "johndoe@example.com",
      "phone_number": "1234567890"
    }
  },
  {
    "id": "cecf1c7b-5a8e-41d2-ae5c-846fb7bfc404",
    "content": "This is another comment.",
    "created_at": "2023-04-20T09:35:00.000Z",
    "user": {
      "name": "Jane Doe",
      "email": "janedoe@example.com",
      "phone_number": "1234567890"
    }
  }
]
```


---

# Authorization Endpoints (https://docs.loopwise.com/reference/authorization-endpoints)



## Authorization endpoint [#authorization-endpoint]

```
GET /oauth/authorize
```

Initiates the OAuth 2.0 Authorization Code flow. Redirects the user to the Loopwise login and consent screen.

### Parameters [#parameters]

| Parameter               | Type   | Required    | Description                                                      |
| ----------------------- | ------ | ----------- | ---------------------------------------------------------------- |
| `response_type`         | string | Yes         | Must be `code`                                                   |
| `client_id`             | string | Yes         | The application's client ID                                      |
| `redirect_uri`          | string | Yes         | Must exactly match a registered redirect URI                     |
| `scope`                 | string | Yes         | Space-separated list of requested [scopes](/reference/scopes)    |
| `state`                 | string | Recommended | Opaque value to prevent CSRF. Returned unchanged in the callback |
| `code_challenge`        | string | Yes         | Base64url-encoded SHA-256 hash of the `code_verifier`            |
| `code_challenge_method` | string | Yes         | Must be `S256`                                                   |
| `school_id`             | string | No          | Pre-select a school by UUID (skips the school picker if valid)   |

### Success response [#success-response]

Redirects to `redirect_uri` with:

| Parameter | Description                                      |
| --------- | ------------------------------------------------ |
| `code`    | The authorization code (single-use, short-lived) |
| `state`   | The `state` value from the request               |

### Error response [#error-response]

Redirects to `redirect_uri` with:

| Parameter           | Description                                           |
| ------------------- | ----------------------------------------------------- |
| `error`             | Error code (e.g., `access_denied`, `invalid_request`) |
| `error_description` | Human-readable error description                      |
| `state`             | The `state` value from the request                    |

***

## Discovery endpoint [#discovery-endpoint]

```
GET /.well-known/oauth-authorization-server
```

Returns OAuth 2.0 Authorization Server Metadata per [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414).

### Response [#response]

```json
{
  "issuer": "https://your-school-domain.com",
  "authorization_endpoint": "https://your-school-domain.com/oauth/authorize",
  "token_endpoint": "https://your-school-domain.com/api/oauth/token",
  "token_endpoint_auth_methods_supported": ["none", "client_secret_post"],
  "revocation_endpoint": "https://your-school-domain.com/api/oauth/revoke",
  "registration_endpoint": "https://your-school-domain.com/api/oauth/register",
  "response_types_supported": ["code"],
  "grant_types_supported": ["authorization_code", "refresh_token"],
  "code_challenge_methods_supported": ["S256"],
  "scopes_supported": ["openid", "profile", "email", "courses:read", "..."],
  "userinfo_endpoint": "https://your-school-domain.com/api/oauth/userinfo",
  "subject_types_supported": ["public"],
  "claims_supported": ["sub", "name", "picture", "email", "email_verified", "org_id", "roles"],
  "service_documentation": "https://docs.loopwise.com",
  "mcp_client_id": "..."
}
```

***

## Client registration endpoint [#client-registration-endpoint]

```
POST /api/oauth/register
```

Issues credentials for pre-registered vendor platforms only: it matches `client_name` against a known integration (Claude Code, Cursor, etc.) and returns that platform's credentials. It is not open dynamic client registration ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)) — an unrecognized `client_name` is refused with `invalid_client_metadata`. A client that is not a pre-registered vendor uses a Client ID Metadata Document instead, where the server permits the document's host (an allowlisted host, or any host when open registration is enabled — see `client_id_metadata_document_supported` in the discovery metadata).

### Request body [#request-body]

| Field                        | Type      | Required | Description                                           |
| ---------------------------- | --------- | -------- | ----------------------------------------------------- |
| `client_name`                | string    | Yes      | Name matched against a known vendor platform          |
| `redirect_uris`              | string\[] | No       | List of allowed redirect URIs                         |
| `grant_types`                | string\[] | No       | Defaults to `["authorization_code", "refresh_token"]` |
| `response_types`             | string\[] | No       | Defaults to `["code"]`                                |
| `token_endpoint_auth_method` | string    | No       | Defaults to `"none"` (public client)                  |

### Response [#response-1]

```json
{
  "client_id": "abc123...",
  "client_name": "Claude Code",
  "redirect_uris": ["http://127.0.0.1:41234/callback"],
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"],
  "token_endpoint_auth_method": "none",
  "scope": "openid profile email courses:read ..."
}
```

The response carries no `client_secret`: it declares `token_endpoint_auth_method: "none"`, meaning the client does not authenticate at the token endpoint at all. PKCE is not a substitute for that — it protects the authorization code itself, by requiring the `code_verifier` matching the `code_challenge` sent at authorization.


---

# OAuth Errors (https://docs.loopwise.com/reference/errors)



Loopwise's [RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749)-style OAuth error responses (responses whose payload includes an OAuth `error` code like `invalid_scope`) carry three fields:

```json
{
  "error":             "invalid_scope",
  "error_description": "Human-readable explanation with concrete fix hints.",
  "error_uri":         "https://docs.loopwise.com/reference/errors#invalid_scope"
}
```

The `error_uri` field follows [RFC 6749 §5.2](https://datatracker.ietf.org/doc/html/rfc6749#section-5.2) — optional in the spec, but Loopwise populates it on every RFC 6749 OAuth error so agents reading the JSON have a deterministic URL to fetch for context. The anchor in `error_uri` points at the matching section on this page.

Non-OAuth gateway errors (e.g. an unauthenticated request hitting the Next.js proxy before the token endpoint sees it) follow a different shape and don't carry `error_uri` — only OAuth-protocol responses do.

This page is the canonical source the `error_uri` field points at — anchor on each error code below matches the slug an integrator's `error_uri` will land on.

## access\_denied [#access_denied]

The user or the authorization server denied the request. Three causes are possible:

1. **The user clicked Deny on the consent screen.** They must restart the authorize flow and click Allow.
2. **The user's grant was revoked** — either by the user themselves from `/oauth/authorized_applications`, or by a school admin. The user must re-authorize.
3. **A scope your application requests was removed from the client's allowed-scopes list** between authorize and callback. Check `/oauth/applications` for the current allowed-scope set on this client.

## invalid\_client [#invalid_client]

Client authentication failed. Three branches:

1. **`client_id` not found.** Confirm the value you're sending exactly matches what's shown at `/oauth/applications` — no trailing whitespace, no truncation.
2. **`client_secret` wrong.** The client exists but the secret was rejected. Either your `.env` is out of date, or the secret was regenerated. Open the client at `/oauth/applications` to verify or regenerate.
3. **Audience mismatch.** The client was found, but its audience (`staff` / `org_admin` / `member`) doesn't match the flow you're executing. A `member`-audience client cannot run a staff flow; a `staff`-audience client cannot access account-only flows.

## invalid\_client\_metadata [#invalid_client_metadata]

The client registration endpoint (`POST /api/oauth/register`) refused the request. It is not open Dynamic Client Registration ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)): it issues credentials only for **pre-registered vendor platforms** (Claude Code, Cursor, and the like), matching `client_name` against a known integration. An unrecognized `client_name` lands here. Pick the path that fits your client:

1. **A pre-registered vendor platform** — send the exact `client_name` the integration uses and the endpoint returns that platform's `client_id`. See [Authorization endpoints](/reference/authorization-endpoints).
2. **A self-asserted client** we have not pre-registered (a CLI tool, desktop app, or hosted web client) — publish a [Client ID Metadata Document](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/) over HTTPS and use its URL as your `client_id`, where the server permits the document's host (an allowlisted host, or any host when open registration is enabled).
3. **A school-specific application** — a school administrator creates one at **Settings > OAuth Applications**. See [Managing OAuth Applications](/guides/managing-applications).

## invalid\_code\_challenge\_method [#invalid_code_challenge_method]

The `code_challenge_method` is missing, or is not one this server accepts. Only `S256` is accepted; `plain` is rejected because under it the code verifier travels in the authorize URL through the user's browser.

Send `code_challenge_method=S256` whenever you send a `code_challenge`. Omitting the parameter is rejected too — this server has never applied RFC 7636's "absent means plain" default. `/.well-known/oauth-authorization-server` publishes the accepted set as `code_challenge_methods_supported`.

## invalid\_grant [#invalid_grant]

The provided authorization grant is invalid, expired, or revoked. Two common causes:

* **Refresh token rotation.** Loopwise rotates refresh tokens — every `/api/oauth/token` response returns a new `refresh_token` that must replace the old one. The previous token is revoked immediately. If you've reused a refresh token (e.g. a process crash lost the rotation), the next call returns `invalid_grant` and the user must re-authorize.
* **Authorization code single-use + 10-minute expiry.** Codes can be exchanged for tokens exactly once and only within 10 minutes of issuance. Exchange the code as soon as your callback runs.

## invalid\_redirect\_uri [#invalid_redirect_uri]

The `redirect_uri` you sent is malformed or not whitelisted on the OAuth client. To fix:

1. Open `/oauth/applications`, navigate to this OAuth client, and copy the exact entries in **Redirect URIs**.
2. Compare to what you're sending: scheme (`http` vs `https`), host, port, and full path must all match — none of them are normalized.

**Common mistake — better-auth / genericOAuth callback path.** On better-auth 1.7 and later, the `genericOAuth` callback is better-auth's core callback route, with no `/oauth2/` segment:

```
https://yourapp.com/api/auth/callback/loopwise
```

A redirect URI registered with the `/oauth2/` segment no longer matches what better-auth sends. Use `getLoopwiseRedirectURI({ baseURL })` from `@loopwise/admin-sdk/better-auth` (0.1.0-beta.5 or later) to get the right URL to register.

## invalid\_request [#invalid_request]

The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed. The `error_description` will name the specific parameter when the cause is missing/malformed input.

## invalid\_scope [#invalid_scope]

The requested scope is invalid, unknown, or not enabled for this OAuth application. What refuses the request is the application's own allowed scopes, not what the server supports:

1. A platform-registered client is capped at its audience ceiling — a pre-registered vendor client holds the operator set, a member client holds the identity scopes plus `account:read` / `account:write`.
2. A school-registered application holds only the scopes an operator enabled for it, under **Developers → OAuth Applications** in the school admin.

`scopes_supported` in `/.well-known/oauth-authorization-server` is the server's universe, and it differs by origin — the platform hosts publish the operator ceiling, a school origin publishes the full catalogue — so it cannot tell you why a particular request was refused.

**Common mistake.** Use `students:read` or `members:read` — not `members:list`. The Loopwise scope grammar is `resource:action`; verbs are `read` / `write`, not `list`.

**Special case — userinfo endpoint.** `/api/oauth/userinfo` returns `invalid_scope` when the token is missing the `openid` identity scope (not because a data scope is malformed). If your `error_description` references `openid` and the userinfo endpoint, add `openid` to the `scope` parameter of your authorize request — it's free, always included in the default scope set, and required for any OIDC identity endpoint.

## invalid\_target [#invalid_target]

The `resource` parameter you sent on the token request is malformed. Per [RFC 8707 §2](https://datatracker.ietf.org/doc/html/rfc8707#section-2), `resource` must be an absolute http(s) URI without query, fragment, or `userinfo` components, and ≤ 2048 characters.

## invalid\_token [#invalid_token]

The access token presented to a protected endpoint is invalid. Three sub-cases (the `error_description` discriminates):

* **Token expired.** Use your stored `refresh_token` to call `POST /api/oauth/token` and obtain a new `access_token`. No user-facing re-authorization needed.
* **Token revoked.** The user (or an admin) revoked this token. The user must restart the OAuth authorize flow.
* **Token unknown / malformed.** The bearer string is invalid, missing, or from a different issuer. Confirm your `Authorization: Bearer <access_token>` header has the right value.

## server\_error [#server_error]

An unexpected condition prevented the authorization server from fulfilling the request. This is a Loopwise-side fault. Retry with backoff; if it persists, contact support with the response timestamp.

## temporarily\_unavailable [#temporarily_unavailable]

The authorization server is temporarily overloaded or under maintenance. Retry with backoff.

`/mcp` also returns this, as a `503`, when it cannot reach a verdict on your token — its own introspection call failed. Your token is not necessarily invalid, and the response carries no `WWW-Authenticate` challenge because re-authorizing would not help. Retry with backoff rather than restarting the authorization flow.

## unauthorized\_client [#unauthorized_client]

The client is not authorized to perform this request using this method. Confirm:

* The application audience (`staff` / `org_admin` / `member`) at `/oauth/applications` matches the flow you're running.
* The grant type your call uses is enabled on the client.

## unsupported\_grant\_type [#unsupported_grant_type]

The authorization server does not support the grant type you sent. Loopwise's third-party integration surface supports `authorization_code` and `refresh_token`. `client_credentials` is configured at the protocol level (Doorkeeper allows it in `grant_flows`) but is reserved for internal service-to-service callers — third-party OAuth clients should not rely on it. Other grant types (`password`, `device_code`) are not enabled at all.

## unsupported\_response\_type [#unsupported_response_type]

The authorization server does not support the response type you requested. Loopwise supports `code` only — `token` (implicit flow) and other response types are not enabled.

## Related references [#related-references]

* [Authorization endpoints](/reference/authorization-endpoints) — flow that emits `access_denied`, `invalid_code_challenge_method`, `invalid_redirect_uri`, `unsupported_response_type`.
* [Token endpoints](/reference/token-endpoints) — flow that emits `invalid_grant`, `invalid_client`, `invalid_scope`, `invalid_target`, `invalid_token`.
* [Scopes](/reference/scopes) — when diagnosing `invalid_scope`.


---

# Scopes (https://docs.loopwise.com/reference/scopes)



Scopes define what data an OAuth application can access. Request only the scopes your integration needs.

## Identity scopes (OIDC) [#identity-scopes-oidc]

These scopes follow the [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html) specification and provide access to user identity information via the [UserInfo endpoint](/reference/token-endpoints#userinfo-endpoint).

| Scope     | Description                                                                                                                                                                                                                                                                                             |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `openid`  | Required for identity access. Returns the user's unique identifier (`sub` claim), and — when the token has a school context — the `org_id` (school identifier) and `roles` (user's roles on that school, ordered by privilege; may be empty if the user has no roles there). This is the default scope. |
| `profile` | Access the user's name and profile picture                                                                                                                                                                                                                                                              |
| `email`   | Access the user's email address and verification status                                                                                                                                                                                                                                                 |

The `org_id` and `roles` claims are OIDC extension claims (see [UserInfo endpoint](/reference/token-endpoints#userinfo-endpoint) for the full claim schema and ordering contract). They let agents and OAuth integrations read "which school + which role" directly from the standard userinfo response — no extra request to admin GraphQL required for the common onboarding case.

## Account scopes [#account-scopes]

These scopes unlock the Member API at `{school}/member/graphql` — one signed-in member's own data, rather than a whole school's admin surface. Useful when a user belongs to multiple schools and the integration needs to enumerate them. See the [AI Agent Integration guide](/guides/agent-integration#a-user-who-is-staff-on-multiple-schools) for the canonical multi-school query example.

`enrolledCourses`, `digitalProducts` and `eventRegistrations` answer *what* a member has access to. They are not order records — no order number, coupon code, refund status or invoice — so do not build a billing history from them. Build it from `viewer.payments`, which is on the same endpoint under the same scope and carries all four. One node there is one payment, and `tradeNo` identifies that payment rather than the purchase behind it: a retried checkout is a separate node with a different `tradeNo`, and nothing joins the attempts of one purchase together.

`consultingServices` is not a purchase list at all: it returns the services offered against the courses delivered to the viewer, and its `meetings` are the viewer's own reserved meetings under the service.

| Scope           | Description                                                                                                                                                                                                                                                                               |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `account:read`  | Read the authenticated user's account context: school memberships (including roles per school), enrolled courses, digital products, consulting services, event registrations, the member's own payments, and the member's own notification inbox, unread count and per-type subscriptions |
| `account:write` | Update the authenticated user's own notification state: mark one notification or all of them as read, and change the in-app and email opt-in for a notification type. Nothing else on the Member API is writable.                                                                         |

## Data scopes [#data-scopes]

These scopes control access to school data through the API.

| Scope                    | Description                                              |
| ------------------------ | -------------------------------------------------------- |
| `courses:read`           | Read course details, curriculum, and enrollment data     |
| `courses:write`          | Create, update, and delete courses                       |
| `students:read`          | Read student profiles and progress data                  |
| `students:write`         | Create and update student records, manage enrollments    |
| `analytics:read`         | Read analytics and reporting data                        |
| `curriculum:read`        | Read curriculum structure (lessons, chapters, materials) |
| `curriculum:write`       | Create and update curriculum content                     |
| `orders:read`            | Read order and payment data                              |
| `school:read`            | Read school configuration and settings                   |
| `school:write`           | Update school configuration and settings                 |
| `appearance:read`        | Read school appearance and theme settings                |
| `appearance:write`       | Update school appearance and theme settings              |
| `events:read`            | Read event details and attendees                         |
| `events:write`           | Create, update, and delete events                        |
| `membership_plans:read`  | Read membership plan details                             |
| `membership_plans:write` | Create and update membership plans                       |
| `coupons:read`           | Read coupon details                                      |
| `coupons:write`          | Create and update coupons                                |
| `posts:read`             | Read post content                                        |
| `posts:write`            | Create, update, and delete posts                         |
| `digital_products:read`  | Read digital download details                            |
| `digital_products:write` | Create and update digital downloads                      |
| `comments:read`          | Read comments                                            |
| `lecturers:read`         | Read lecturer profiles                                   |
| `lecturers:write`        | Create and update lecturer profiles                      |
| `storage:write`          | Upload files and images                                  |
| `subscriptions:read`     | Read subscription data                                   |
| `subscriptions:write`    | Manage subscriptions                                     |

## MCP tool to scope mapping [#mcp-tool-to-scope-mapping]

When using the [MCP server](/guides/mcp-quickstart), each tool requires a specific OAuth scope. Note that MCP tool names may differ from scope names (e.g. `list_members` requires `students:read`).

| MCP Tool                                           | Required Scope                       |
| -------------------------------------------------- | ------------------------------------ |
| `list_courses`, `get_course`, `list_reviews`       | `courses:read`                       |
| `update_course`                                    | `courses:write`                      |
| `list_members`, `get_member`                       | `students:read`                      |
| `get_site_info`                                    | `school:read`                        |
| `get_settings`                                     | `school:read` or `appearance:read`   |
| `update_settings`                                  | `school:write` or `appearance:write` |
| `list_orders`                                      | `orders:read`                        |
| `list_lessons`                                     | `curriculum:read`                    |
| `list_membership_plans`, `get_membership_plan`     | `membership_plans:read`              |
| `list_events`, `get_event`, `list_event_attendees` | `events:read`                        |
| `list_coupons`, `get_coupon`                       | `coupons:read`                       |
| `list_posts`, `get_post`                           | `posts:read`                         |
| `create_post`, `update_post`, `delete_post`        | `posts:write`                        |
| `list_digital_downloads`, `get_digital_download`   | `digital_products:read`              |
| `list_comments`, `get_comment`                     | `comments:read`                      |
| `upload_image`, `confirm_upload`                   | `storage:write`                      |
| `list_lecturers`, `get_lecturer`                   | `lecturers:read`                     |
| `create_lecturer`, `update_lecturer`               | `lecturers:write`                    |

<Callout>
  Some tools are accessible via multiple scopes. For example, `get_settings` is available with either `school:read` or `appearance:read`.
</Callout>

## Requesting scopes [#requesting-scopes]

Include the desired scopes as a space-separated list in the `scope` parameter of the authorization request:

```
/oauth/authorize?scope=openid+profile+email+courses:read+students:read&...
```

If no scopes are specified, only `openid` is granted by default.

## Scope hierarchy [#scope-hierarchy]

Use the most restrictive scopes possible for your use case. This follows the principle of least privilege and makes the consent screen clearer for users.

For example, if your integration only needs to read course data and the user's email, request `openid email courses:read` rather than requesting all available scopes.

## Admin scopes [#admin-scopes]

The `admin:read` and `admin:write` scopes are reserved for platform administrators and are not available to third-party applications. They are excluded from the discovery endpoint and dynamic client registration responses.


---

# Token Endpoints (https://docs.loopwise.com/reference/token-endpoints)



## Token lifecycle [#token-lifecycle]

<Mermaid
  chart="stateDiagram-v2
    [*] --> AuthCode: User authorizes
    AuthCode --> AccessToken: POST /api/oauth/token<br/>(grant_type=authorization_code)
    AccessToken --> Expired: After 2 hours
    Expired --> AccessToken: POST /api/oauth/token<br/>(grant_type=refresh_token)
    AccessToken --> Revoked: POST /api/oauth/revoke
    Expired --> Revoked: POST /api/oauth/revoke
    Revoked --> [*]"
/>

## Token endpoint [#token-endpoint]

```
POST /api/oauth/token
```

Exchanges an authorization code for an access token, or refreshes an existing token.

### Authorization Code grant [#authorization-code-grant]

| Parameter       | Type   | Required    | Description                                          |
| --------------- | ------ | ----------- | ---------------------------------------------------- |
| `grant_type`    | string | Yes         | Must be `authorization_code`                         |
| `code`          | string | Yes         | The authorization code from the callback             |
| `redirect_uri`  | string | Yes         | Must match the URI used in the authorization request |
| `client_id`     | string | Yes         | Your application's client ID                         |
| `code_verifier` | string | Yes         | The PKCE code verifier (plain-text, 43-128 chars)    |
| `client_secret` | string | Conditional | Required for confidential clients                    |

#### Response [#response]

```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "Bearer",
  "expires_in": 7200,
  "refresh_token": "def456...",
  "scope": "openid courses:read students:read",
  "created_at": 1710000000,
  "school_id": "550e8400-e29b-41d4-a716-446655440000",
  "school_subdomain": "demo"
}
```

| Field              | Description                                            |
| ------------------ | ------------------------------------------------------ |
| `access_token`     | Bearer token for API requests                          |
| `token_type`       | Always `Bearer`                                        |
| `expires_in`       | Token lifetime in seconds (default: 7200 / 2 hours)    |
| `refresh_token`    | Token to obtain a new access token                     |
| `scope`            | Granted scopes (may be a subset of what was requested) |
| `school_id`        | The UUID of the authorized school                      |
| `school_subdomain` | The subdomain of the authorized school                 |

***

### Refresh Token grant [#refresh-token-grant]

| Parameter       | Type   | Required    | Description                       |
| --------------- | ------ | ----------- | --------------------------------- |
| `grant_type`    | string | Yes         | Must be `refresh_token`           |
| `refresh_token` | string | Yes         | A valid refresh token             |
| `client_id`     | string | Yes         | Your application's client ID      |
| `client_secret` | string | Conditional | Required for confidential clients |

#### Response [#response-1]

Same format as the authorization code grant response.

<Callout type="warn" title="Refresh token rotation">
  Every successful refresh returns a &#x2A;*new `refresh_token`** in the response. The previous refresh token is immediately revoked.

  Your client **must** persist the new refresh token and use it for the next refresh. Replaying an old token returns `invalid_grant`.
</Callout>

```js title="Example: handling token rotation"
async function refreshAccessToken(storedRefreshToken) {
  const res = await fetch(TOKEN_URL, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "refresh_token",
      refresh_token: storedRefreshToken,
      client_id: CLIENT_ID,
      // Include client_secret for confidential clients:
      // client_secret: CLIENT_SECRET,
    }),
  });

  if (!res.ok) throw new Error(`Refresh failed: ${res.status}`);

  const { access_token, refresh_token, expires_in } = await res.json();

  // Always persist the latest refresh_token
  await store.set("oauth_tokens", {
    access_token,
    refresh_token: refresh_token ?? storedRefreshToken,
    expires_at: Date.now() + expires_in * 1000,
  });

  return access_token;
}
```

***

## Revocation endpoint [#revocation-endpoint]

```
POST /api/oauth/revoke
```

Revokes an access token or refresh token per [RFC 7009](https://datatracker.ietf.org/doc/html/rfc7009).

| Parameter         | Type   | Required | Description                       |
| ----------------- | ------ | -------- | --------------------------------- |
| `token`           | string | Yes      | The token to revoke               |
| `token_type_hint` | string | No       | `access_token` or `refresh_token` |
| `client_id`       | string | Yes      | Your application's client ID      |

The endpoint always returns `200 OK`, even if the token was already revoked or invalid. This prevents token-guessing attacks.

***

## Introspection endpoint [#introspection-endpoint]

```
POST /api/oauth/introspect
```

Returns metadata about a token per [RFC 7662](https://datatracker.ietf.org/doc/html/rfc7662).

| Parameter   | Type   | Required | Description                  |
| ----------- | ------ | -------- | ---------------------------- |
| `token`     | string | Yes      | The token to introspect      |
| `client_id` | string | Yes      | Your application's client ID |

#### Response (active token) [#response-active-token]

```json
{
  "active": true,
  "scope": "openid courses:read",
  "client_id": "abc123",
  "token_type": "Bearer",
  "exp": 1710007200
}
```

#### Response (inactive/invalid token) [#response-inactiveinvalid-token]

```json
{
  "active": false
}
```

***

## UserInfo endpoint [#userinfo-endpoint]

```
GET /api/oauth/userinfo
POST /api/oauth/userinfo
```

Returns identity claims about the authenticated user per [OpenID Connect Core 1.0 §5.3](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo). The `openid` scope is required.

### Request [#request]

Include the access token as a Bearer token in the `Authorization` header:

```
Authorization: Bearer <access_token>
```

### Response [#response-2]

The claims returned depend on the scopes granted to the token:

```json
{
  "sub": "550e8400-e29b-41d4-a716-446655440000",
  "name": "Jane Doe",
  "email": "jane@example.com",
  "email_verified": true,
  "org_id": "7a1e9d5f-3c2b-4a8e-9d3f-0c2b6e8d4f1a",
  "roles": ["owner", "teacher"]
}
```

`openid` is always required to call this endpoint — the "Extra scope"
column below says *which additional scope to request* if you want a
particular claim to appear (— means no extra scope needed beyond
`openid`).

| Claim            | Extra scope | Present when                                                          | Description                                                                                                                                                                                                                                                       |
| ---------------- | ----------- | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sub`            | —           | Always                                                                | Unique user identifier (UUID)                                                                                                                                                                                                                                     |
| `name`           | `profile`   | `profile` scope was granted                                           | User's display name                                                                                                                                                                                                                                               |
| `picture`        | `profile`   | `profile` scope was granted **and** the member has an uploaded avatar | URL of the member's profile picture (OIDC Core §5.1). Omitted when the member has no avatar.                                                                                                                                                                      |
| `email`          | `email`     | `email` scope was granted                                             | User's email address                                                                                                                                                                                                                                              |
| `email_verified` | `email`     | `email` scope was granted                                             | Whether the email has been verified                                                                                                                                                                                                                               |
| `org_id`         | —           | the token has a school context                                        | School identifier the token is bound to. Use this to scope tenant data by Loopwise school.                                                                                                                                                                        |
| `roles`          | —           | the token has a school context                                        | User's roles on the bound school (may be an empty array if the user has no roles there). **Ordered by privilege**, so `roles[0]` — when the array is non-empty — is the highest-privilege role and is suitable as a stable "primary role" for onboarding mapping. |

`org_id` and `roles` are OIDC extension claims (OIDC Core §5.1.2), present whenever the access token carries a school binding — true for every standard OAuth login flow. They are advertised in `/.well-known/oauth-authorization-server` under `claims_supported`.

#### Role ordering [#role-ordering]

`roles` is sorted by an explicit privilege priority:

```
owner > manager > admin > teacher > teaching_assistant > student
```

Tenant-defined custom roles (created from your school's admin UI) sort after the built-in roles, alphabetically among themselves. The ordering is a stable contract: when `roles` is non-empty, `roles[0]` is the highest-privilege role the user holds. Callers must still handle the empty-array case (a school-bound token for a user with no roles on that school).

### Error responses [#error-responses]

| HTTP Status | Error           | When                                      |
| ----------- | --------------- | ----------------------------------------- |
| 401         | `invalid_token` | Missing, expired, or revoked token        |
| 403         | `invalid_scope` | Token does not include the `openid` scope |

***

## Error responses [#error-responses-1]

All token endpoints return errors in the standard OAuth 2.0 format:

```json
{
  "error": "invalid_grant",
  "error_description": "The authorization code has expired or has already been used."
}
```

| Error                    | HTTP Status | Description                                                 |
| ------------------------ | ----------- | ----------------------------------------------------------- |
| `invalid_request`        | 400         | Missing or malformed parameter                              |
| `invalid_client`         | 401         | Client authentication failed                                |
| `invalid_grant`          | 400         | Code expired, already used, or verifier mismatch            |
| `unauthorized_client`    | 400         | Client not authorized for this grant type                   |
| `unsupported_grant_type` | 400         | Only `authorization_code` and `refresh_token` are supported |


---

# Assignment Webhooks (https://docs.loopwise.com/webhooks/assignment)



## assignment.created [#assignmentcreated]

The `assignment.created` event is triggered when a teacher creates a new assignment in a course.

### Event Properties [#event-properties]

| Property    | Type    | Description                                                  |
| ----------- | ------- | ------------------------------------------------------------ |
| id          | string  | Unique identifier for the assignment (UUID)                  |
| name        | string  | Name of the assignment                                       |
| description | string  | Description of the assignment                                |
| published   | boolean | Indicates whether the assignment is published                |
| due\_at     | string  | Due date of the assignment (may be absent)                   |
| created\_at | string  | Timestamp when the assignment was created                    |
| updated\_at | string  | Timestamp when the assignment was last updated               |
| course      | object  | The course this assignment belongs to (`id`, `name`, `slug`) |

### Example Payload [#example-payload]

All timestamps are in ISO 8601 format and include a timezone offset (e.g. `+08:00`). Properties with empty values are omitted from the payload.

```json
{
  "type": "assignment.created",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Week 1 Homework",
    "description": "Complete the exercises from chapter 1.",
    "published": true,
    "due_at": "2024-03-28T13:45:30+08:00",
    "created_at": "2024-03-21T13:45:30+08:00",
    "updated_at": "2024-03-21T13:45:30+08:00",
    "course": {
      "id": "660e8400-e29b-41d4-a716-446655440111",
      "name": "Introduction to Programming",
      "slug": "intro-to-programming"
    }
  }
}
```

***

## assignment.updated [#assignmentupdated]

The `assignment.updated` event is triggered when an existing assignment is modified. The payload shape is identical to `assignment.created`.

```json
{
  "type": "assignment.updated",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Week 1 Homework (extended deadline)",
    "description": "Complete the exercises from chapter 1.",
    "published": true,
    "due_at": "2024-04-04T13:45:30+08:00",
    "created_at": "2024-03-21T13:45:30+08:00",
    "updated_at": "2024-03-25T09:00:00+08:00",
    "course": {
      "id": "660e8400-e29b-41d4-a716-446655440111",
      "name": "Introduction to Programming",
      "slug": "intro-to-programming"
    }
  }
}
```

***

## submission.submitted [#submissionsubmitted]

The `submission.submitted` event is triggered when a student submits their work for an assignment.

<Callout type="warn">
  A submission that was returned by the teacher can be re-submitted, so you may receive multiple `submission.submitted` events for the same submission `id`. Use `submitted_at` to distinguish attempts.
</Callout>

<Callout type="warn">
  A teacher can also undo a `returned` or `completed` grading action, which moves the submission back to the `submitted` state **without emitting a webhook event**. If your integration mirrors submission states, treat the event stream as eventually consistent and reconcile periodically via the Admin API.
</Callout>

<Callout type="warn">
  Submission events are delivered asynchronously with independent retries, so they may arrive out of order, and the `data` payload reflects the submission at delivery time — `data.state` can differ from the event `type` if the submission changed in between. Treat `data.state` and the timestamps (`submitted_at`, `checked_at`, `updated_at`) as authoritative rather than the arrival order.
</Callout>

### Event Properties [#event-properties-1]

| Property      | Type   | Description                                                   |
| ------------- | ------ | ------------------------------------------------------------- |
| id            | string | Unique identifier for the submission (UUID)                   |
| state         | string | Current state of the submission (`submitted`)                 |
| title         | string | Title of the submission                                       |
| content       | string | Text content of the submission                                |
| submitted\_at | string | Timestamp when the student submitted                          |
| checked\_at   | string | Timestamp when grading was completed (absent until completed) |
| created\_at   | string | Timestamp when the submission was created                     |
| updated\_at   | string | Timestamp when the submission was last updated                |
| assignment    | object | The assignment being submitted to (`id`, `name`, `course_id`) |
| student       | object | The submitting student (`id`, `name`, `email`)                |

### Example Payload [#example-payload-1]

```json
{
  "type": "submission.submitted",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "state": "submitted",
    "title": "My Week 1 Homework",
    "content": "Here is my answer to the exercises...",
    "submitted_at": "2024-03-22T10:30:00+08:00",
    "created_at": "2024-03-22T10:29:00+08:00",
    "updated_at": "2024-03-22T10:30:00+08:00",
    "assignment": {
      "id": "660e8400-e29b-41d4-a716-446655440111",
      "name": "Week 1 Homework",
      "course_id": "770e8400-e29b-41d4-a716-446655440222"
    },
    "student": {
      "id": "880e8400-e29b-41d4-a716-446655440333",
      "name": "Test Student",
      "email": "student@example.com"
    }
  }
}
```

***

## submission.returned [#submissionreturned]

The `submission.returned` event is triggered when a teacher returns a submission to the student for revision. In addition to all `submission.submitted` properties, the payload may include the current rating.

### Additional Properties [#additional-properties]

| Property | Type   | Description                                                               |
| -------- | ------ | ------------------------------------------------------------------------- |
| rate     | object | The rating given by the teacher (`score`, `comment`); absent if not rated |

### Example Payload [#example-payload-2]

```json
{
  "type": "submission.returned",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "state": "returned",
    "title": "My Week 1 Homework",
    "content": "Here is my answer to the exercises...",
    "submitted_at": "2024-03-22T10:30:00+08:00",
    "created_at": "2024-03-22T10:29:00+08:00",
    "updated_at": "2024-03-23T08:00:00+08:00",
    "assignment": {
      "id": "660e8400-e29b-41d4-a716-446655440111",
      "name": "Week 1 Homework",
      "course_id": "770e8400-e29b-41d4-a716-446655440222"
    },
    "student": {
      "id": "880e8400-e29b-41d4-a716-446655440333",
      "name": "Test Student",
      "email": "student@example.com"
    },
    "rate": {
      "score": 2.5,
      "comment": "Please revise question 3 and resubmit."
    }
  }
}
```

***

## submission.completed [#submissioncompleted]

The `submission.completed` event is triggered when a teacher finishes grading a submission. In addition to all `submission.submitted` properties, the payload may include the rating and the grader.

<Callout type="warn">
  A teacher can grade a submission that was returned to the student, so `submission.completed` may follow `submission.returned` with no `submission.submitted` in between, and with `submitted_at` still describing the earlier attempt. Do not assume a completion always closes the most recent submission event.
</Callout>

### Additional Properties [#additional-properties-1]

| Property | Type   | Description                                                                |
| -------- | ------ | -------------------------------------------------------------------------- |
| rate     | object | The rating given by the teacher (`score`, `comment`); absent if not rated  |
| grader   | object | The teacher who graded the submission (`id`, `name`); absent if not graded |

### Example Payload [#example-payload-3]

```json
{
  "type": "submission.completed",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "state": "checked",
    "title": "My Week 1 Homework",
    "content": "Here is my answer to the exercises...",
    "submitted_at": "2024-03-22T10:30:00+08:00",
    "checked_at": "2024-03-24T15:00:00+08:00",
    "created_at": "2024-03-22T10:29:00+08:00",
    "updated_at": "2024-03-24T15:00:00+08:00",
    "assignment": {
      "id": "660e8400-e29b-41d4-a716-446655440111",
      "name": "Week 1 Homework",
      "course_id": "770e8400-e29b-41d4-a716-446655440222"
    },
    "student": {
      "id": "880e8400-e29b-41d4-a716-446655440333",
      "name": "Test Student",
      "email": "student@example.com"
    },
    "rate": {
      "score": 4.5,
      "comment": "Great work!"
    },
    "grader": {
      "id": "990e8400-e29b-41d4-a716-446655440444",
      "name": "Test Teacher"
    }
  }
}
```


---

# Coupon Webhooks (https://docs.loopwise.com/webhooks/coupon)



## coupon.created [#couponcreated]

> **Note:** The `coupon.created` webhook event is planned for future release and is not yet available.

The `coupon.created` event will be triggered when a new coupon is created in the system.

### Event Properties [#event-properties]

| Property          | Type    | Description                                                                                                                  |
| ----------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- |
| id                | string  | The unique identifier of the coupon                                                                                          |
| code              | string  | The unique code used to redeem the coupon                                                                                    |
| name              | string  | The name of the coupon (maximum 255 characters)                                                                              |
| description       | string  | The description of the coupon (maximum 500 characters)                                                                       |
| state             | string  | The current state of the coupon                                                                                              |
| coupon\_type      | string  | The type of coupon ("fixed\_amount" or "percentage")                                                                         |
| amount            | decimal | The discount amount or percentage                                                                                            |
| started\_at       | string  | The timestamp when the coupon becomes valid (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z")    |
| expired\_at       | string  | The timestamp when the coupon expires (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z")          |
| redemption\_limit | integer | The maximum number of times the coupon can be redeemed                                                                       |
| applied\_count    | integer | The number of times the coupon has been applied                                                                              |
| active            | boolean | Whether the coupon is active                                                                                                 |
| once\_per\_user   | boolean | Whether the coupon can only be used once per user                                                                            |
| single\_product   | boolean | Whether the coupon can only be applied to a single product                                                                   |
| items             | array   | Specific items the coupon applies to                                                                                         |
| created\_at       | string  | The timestamp when the coupon was created (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z")      |
| updated\_at       | string  | The timestamp when the coupon was last updated (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z") |

### Example Payload [#example-payload]

```json
{
	"type": "coupon.created",
	"data": {
		"id": "550e8400-e29b-41d4-a716-446655440001",
		"code": "SUMMER2023",
		"name": "Summer Discount",
		"description": "Special discount for summer courses",
		"state": "active",
		"coupon_type": "percentage",
		"amount": 20.0,
		"started_at": "2023-06-01T00:00:00Z",
		"expired_at": "2023-08-31T23:59:59Z",
		"redemption_limit": 100,
		"applied_count": 0,
		"active": true,
		"once_per_user": true,
		"single_product": false,
		"items": ["course-123", "course-456"],
		"created_at": "2023-05-15T14:30:00Z",
		"updated_at": "2023-05-15T14:30:00Z"
	}
}
```

***

## coupon.updated [#couponupdated]

> **Note:** The `coupon.updated` webhook event is planned for future release and is not yet available.

The `coupon.updated` event will be triggered when an existing coupon is updated in the system.

### Event Properties [#event-properties-1]

| Property          | Type    | Description                                                                                                                       |
| ----------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------- |
| id                | string  | The unique identifier of the coupon                                                                                               |
| code              | string  | The updated code used to redeem the coupon                                                                                        |
| name              | string  | The updated name of the coupon (maximum 255 characters)                                                                           |
| description       | string  | The updated description of the coupon (maximum 500 characters)                                                                    |
| state             | string  | The current state of the coupon                                                                                                   |
| coupon\_type      | string  | The type of coupon ("fixed\_amount" or "percentage")                                                                              |
| amount            | decimal | The updated discount amount or percentage                                                                                         |
| started\_at       | string  | The updated timestamp when the coupon becomes valid (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z") |
| expired\_at       | string  | The updated timestamp when the coupon expires (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z")       |
| redemption\_limit | integer | The updated maximum number of times the coupon can be redeemed                                                                    |
| applied\_count    | integer | The current number of times the coupon has been applied                                                                           |
| active            | boolean | Whether the coupon is currently active                                                                                            |
| once\_per\_user   | boolean | Whether the coupon can only be used once per user                                                                                 |
| single\_product   | boolean | Whether the coupon can only be applied to a single product                                                                        |
| items             | array   | Updated specific items the coupon applies to                                                                                      |
| created\_at       | string  | The timestamp when the coupon was created (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z")           |
| updated\_at       | string  | The timestamp when the coupon was last updated (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z")      |

### Example Payload [#example-payload-1]

```json
{
	"type": "coupon.updated",
	"data": {
		"id": "550e8400-e29b-41d4-a716-446655440001",
		"code": "SUMMER2023EXTENDED",
		"name": "Extended Summer Discount",
		"description": "Extended special discount for summer courses",
		"state": "active",
		"coupon_type": "percentage",
		"amount": 25.0,
		"started_at": "2023-06-01T00:00:00Z",
		"expired_at": "2023-09-30T23:59:59Z",
		"redemption_limit": 200,
		"applied_count": 45,
		"active": true,
		"once_per_user": true,
		"single_product": false,
		"items": ["course-123", "course-456", "course-789"],
		"created_at": "2023-05-15T14:30:00Z",
		"updated_at": "2023-07-01T09:15:00Z"
	}
}
```


---

# Course Webhooks (https://docs.loopwise.com/webhooks/course)



## course.created [#coursecreated]

The `course.created` event is triggered when a new course is created in the system.

### Event Properties [#event-properties]

| Property    | Type   | Description                                    |
| ----------- | ------ | ---------------------------------------------- |
| id          | string | The unique identifier of the course            |
| name        | string | The name of the course                         |
| description | string | The description of the course                  |
| state       | string | The current state of the course                |
| type        | string | The type of the course (always "Course")       |
| created\_at | string | The timestamp when the course was created      |
| updated\_at | string | The timestamp when the course was last updated |
| slug        | string | The URL-friendly slug of the course            |
| plans       | array  | An array of plans associated with the course   |

### Plan Properties [#plan-properties]

Each plan in the `plans` array has the following properties:

| Property    | Type    | Description                                                                                                           |
| ----------- | ------- | --------------------------------------------------------------------------------------------------------------------- |
| id          | string  | The unique identifier of the plan                                                                                     |
| name        | string  | The name of the plan                                                                                                  |
| description | string  | A description of the plan                                                                                             |
| currency    | string  | The currency code for the plan's price                                                                                |
| amount      | integer | The price amount in the smallest currency unit                                                                        |
| created\_at | string  | The timestamp when the plan was created (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z") |
| updated\_at | string  | The timestamp when the plan was last updated (ISO 8601 format)                                                        |

### Example Payload [#example-payload]

```json
{
  "type": "course.created",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Introduction to Programming",
    "description": "Learn the basics of coding with this comprehensive course.",
    "state": "draft",
    "type": "Course",
    "created_at": "2023-05-15T14:30:00Z",
    "updated_at": "2023-05-15T14:30:00Z",
    "slug": "intro-to-programming",
    "plans": [
      {
        "id": "plan_123",
        "name": "Basic Plan",
        "description": "Access to all course materials for 3 months",
        "currency": "TWD",
        "amount": 5000,
        "created_at": "2023-05-15T14:35:00Z",
        "updated_at": "2023-05-15T14:35:00Z"
      },
      {
        "id": "plan_456",
        "name": "Premium Plan",
        "description": "Lifetime access to course materials and weekly Q&A sessions",
        "currency": "TWD",
        "amount": 1900,
        "created_at": "2023-05-15T14:36:00Z",
        "updated_at": "2023-05-15T14:36:00Z"
      }
    ]
  }
}
```

***

## course.updated [#courseupdated]

The `course.updated` event is triggered when an existing course is updated in the system.

### Event Properties [#event-properties-1]

| Property    | Type   | Description                                          |
| ----------- | ------ | ---------------------------------------------------- |
| id          | string | The unique identifier of the course                  |
| name        | string | The updated name of the course                       |
| description | string | The updated description of the course                |
| state       | string | The current state of the course                      |
| type        | string | The type of the course (always "Course")             |
| created\_at | string | The timestamp when the course was created            |
| updated\_at | string | The timestamp when the course was last updated       |
| slug        | string | The updated URL-friendly slug of the course          |
| plans       | array  | An array of updated plans associated with the course |

### Plan Properties [#plan-properties-1]

Each plan in the `plans` array has the following properties:

| Property    | Type    | Description                                                                                                           |
| ----------- | ------- | --------------------------------------------------------------------------------------------------------------------- |
| id          | string  | The unique identifier of the plan                                                                                     |
| name        | string  | The updated name of the plan                                                                                          |
| description | string  | The updated description of the plan                                                                                   |
| currency    | string  | The currency code for the plan's price                                                                                |
| amount      | integer | The updated price amount in the smallest currency unit                                                                |
| created\_at | string  | The timestamp when the plan was created (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z") |
| updated\_at | string  | The timestamp when the plan was last updated (ISO 8601 format)                                                        |

### Example Payload [#example-payload-1]

```json
{
  "type": "course.updated",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Advanced Programming Techniques",
    "description": "Take your coding skills to the next level with advanced programming concepts.",
    "state": "published",
    "type": "Course",
    "created_at": "2023-05-15T14:30:00Z",
    "updated_at": "2023-06-01T10:15:00Z",
    "slug": "advanced-programming-techniques",
    "plans": [
      {
        "id": "plan_123",
        "name": "Standard Plan",
        "description": "6 months access to all course materials",
        "currency": "TWD",
        "amount": 7500,
        "created_at": "2023-05-15T14:35:00Z",
        "updated_at": "2023-06-01T10:15:00Z"
      },
      {
        "id": "plan_456",
        "name": "Premium Plan",
        "description": "Lifetime access to course materials, weekly Q&A sessions, and personal mentoring",
        "currency": "TWD",
        "amount": 15000,
        "created_at": "2023-05-15T14:36:00Z",
        "updated_at": "2023-06-01T10:15:00Z"
      }
    ]
  }
}
```

***

## course.student\_enroll [#coursestudent_enroll]

The `course.student_enroll` event is triggered when a student is enrolled in a course.

### Event Properties [#event-properties-2]

| Property    | Type   | Description                                        |
| ----------- | ------ | -------------------------------------------------- |
| id          | string | The unique identifier of the enrollment            |
| course      | object | Details about the course                           |
| user        | object | Details about the enrolled user                    |
| created\_at | string | The timestamp when the enrollment was created      |
| updated\_at | string | The timestamp when the enrollment was last updated |
| state       | string | The current state of the enrollment delivery       |

### Course Object [#course-object]

| Property | Type   | Description                         |
| -------- | ------ | ----------------------------------- |
| id       | string | The unique identifier of the course |
| name     | string | The name of the course              |
| slug     | string | The URL-friendly slug of the course |
| subtitle | string | The subtitle of the course          |

### User Object [#user-object]

| Property      | Type   | Description                       |
| ------------- | ------ | --------------------------------- |
| id            | string | The unique identifier of the user |
| name          | string | The name of the user              |
| email         | string | The email address of the user     |
| phone\_number | string | The phone number of the user      |

### Example Payload [#example-payload-2]

```json
{
  "type": "course.student_enroll",
  "data": {
    "id": "enroll_123456",
    "course": {
      "id": "course_789012",
      "name": "Introduction to Programming",
      "slug": "intro-to-programming",
      "subtitle": "Learn the basics of coding"
    },
    "user": {
      "id": "user_345678",
      "name": "Sample User",
      "email": "student@example.com",
      "phone_number": "+1234567890"
    },
    "created_at": "2023-05-15T14:30:00Z",
    "updated_at": "2023-05-15T14:30:00Z",
    "state": "pending"
  }
}
```


---

# Digital Download Webhooks (https://docs.loopwise.com/webhooks/digital-download)



## digital\_download.created [#digital_downloadcreated]

The `digital_download.created` event is triggered when a new digital download is created in the system.

### Event Properties [#event-properties]

| Property     | Type    | Description                                                                                                                       |
| ------------ | ------- | --------------------------------------------------------------------------------------------------------------------------------- |
| id           | string  | The unique identifier of the digital download                                                                                     |
| name         | string  | The name of the digital download                                                                                                  |
| description  | string  | The description of the digital download                                                                                           |
| currency     | string  | The currency code for the product's price (default: "TWD")                                                                        |
| amount       | number  | The price amount of the digital download                                                                                          |
| published    | boolean | Indicates if the digital download is published                                                                                    |
| slug         | string  | The URL-friendly identifier for the digital download                                                                              |
| cover\_photo | string  | The URL or path to the cover photo of the digital download                                                                        |
| created\_at  | string  | The timestamp when the digital download was created (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z") |
| updated\_at  | string  | The timestamp when the digital download was last updated (ISO 8601 format)                                                        |

### Example Payload [#example-payload]

```json
{
  "type": "digital_download.created",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Advanced Programming Techniques E-book",
    "description": "A comprehensive guide to advanced programming concepts and best practices.",
    "currency": "TWD",
    "amount": 1500.0,
    "published": false,
    "slug": "advanced-programming-techniques-ebook",
    "cover_photo": "https://example.com/covers/advanced-programming-ebook.jpg",
    "created_at": "2023-05-15T14:30:00Z",
    "updated_at": "2023-05-15T14:30:00Z"
  }
}
```

***

## digital\_download.updated [#digital_downloadupdated]

The `digital_download.updated` event is triggered when an existing digital download is updated in the system.

### Event Properties [#event-properties-1]

| Property     | Type    | Description                                                                                                                       |
| ------------ | ------- | --------------------------------------------------------------------------------------------------------------------------------- |
| id           | string  | The unique identifier of the digital download                                                                                     |
| name         | string  | The name of the digital download                                                                                                  |
| description  | string  | The description of the digital download                                                                                           |
| currency     | string  | The currency code for the product's price (default: "TWD")                                                                        |
| amount       | number  | The price amount of the digital download                                                                                          |
| published    | boolean | Indicates if the digital download is published                                                                                    |
| slug         | string  | The URL-friendly identifier for the digital download                                                                              |
| cover\_photo | string  | The URL or path to the cover photo of the digital download                                                                        |
| created\_at  | string  | The timestamp when the digital download was created (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z") |
| updated\_at  | string  | The timestamp when the digital download was last updated (ISO 8601 format)                                                        |

### Example Payload [#example-payload-1]

```json
{
  "type": "digital_download.updated",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Advanced Programming Techniques E-book (2nd Edition)",
    "description": "An updated and expanded guide to advanced programming concepts and best practices.",
    "currency": "TWD",
    "amount": 1800.0,
    "published": true,
    "slug": "advanced-programming-techniques-ebook-2nd-edition",
    "cover_photo": "https://example.com/covers/advanced-programming-ebook-2nd-edition.jpg",
    "created_at": "2023-05-15T14:30:00Z",
    "updated_at": "2023-06-20T09:45:00Z"
  }
}
```


---

# Event Webhooks (https://docs.loopwise.com/webhooks/event)



## event.created [#eventcreated]

The `event.created` event is triggered when a new event is created in the system.

### Event Properties [#event-properties]

| Property                | Type    | Description                                                                                                    |
| ----------------------- | ------- | -------------------------------------------------------------------------------------------------------------- |
| id                      | string  | Unique identifier for the event (UUID)                                                                         |
| name                    | string  | Name of the event                                                                                              |
| state                   | string  | Current state of the event                                                                                     |
| started\_at             | string  | Start date and time of the event (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z") |
| ended\_at               | string  | End date and time of the event (ISO 8601 format)                                                               |
| created\_at             | string  | Timestamp when the event was created (ISO 8601 format)                                                         |
| updated\_at             | string  | Timestamp when the event was last updated (ISO 8601 format)                                                    |
| max\_attendee\_capacity | integer | Maximum number of attendees allowed                                                                            |
| description             | string  | Detailed description of the event                                                                              |
| slug                    | string  | URL-friendly identifier for the event                                                                          |
| hosting\_type           | string  | Type of hosting for the event ("zoom", "live\_session", or "custom")                                           |
| hosting\_id             | string  | Identifier for the hosting platform or location                                                                |
| join\_url               | string  | URL for attendees to join the event                                                                            |
| published               | boolean | Indicates whether the event is published (true) or draft (false)                                               |
| tickets                 | array   | List of ticket types available for the event                                                                   |

### Hosting Types [#hosting-types]

The `hosting_type` property indicates the platform or method used to host the event. It can have the following values:

* `"zoom"`: The event is hosted using Zoom. In this case, the `hosting_id` will contain the Zoom meeting ID.
* `"live_session"`: The event uses Loopwise's built-in live session feature. The `hosting_id` will be the internal identifier for the live session.
* `"custom"`: A custom hosting solution is used, such as Google Meet or any other platform. For custom hosting, the `join_url` property will contain the link for attendees to join the event.

The `hosting_type` determines how attendees will access the event and what kind of integration or preparation is needed on the organizer's side.

### Ticket Properties [#ticket-properties]

Each ticket in the `tickets` array contains the following properties:

| Property    | Type    | Description                                         |
| ----------- | ------- | --------------------------------------------------- |
| id          | string  | Unique identifier for the ticket (UUID)             |
| level       | integer | Ticket level or tier                                |
| name        | string  | Name of the ticket type                             |
| quantity    | integer | Number of tickets available                         |
| currency    | string  | Currency code for the ticket price (default: "TWD") |
| amount      | number  | Price of the ticket                                 |
| created\_at | string  | Timestamp when the ticket was created               |
| updated\_at | string  | Timestamp when the ticket was last updated          |

### Example Payload [#example-payload]

```json
{
  "type": "event.created",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Annual Tech Conference 2024",
    "state": "scheduled",
    "started_at": "2024-09-15T09:00:00Z",
    "ended_at": "2024-09-15T10:00:00Z",
    "created_at": "2024-03-01T10:30:00Z",
    "updated_at": "2024-03-01T10:30:00Z",
    "max_attendee_capacity": 500,
    "description": "Join us for the biggest tech conference of the year!",
    "slug": "annual-tech-conference-2024",
    "hosting_type": "live_session",
    "hosting_id": "venue-123",
    "join_url": "https://example.com/events/annual-tech-conference-2024",
    "published": true,
    "tickets": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440001",
        "level": 1,
        "name": "Early Bird",
        "quantity": 100,
        "currency": "TWD",
        "amount": 2500,
        "created_at": "2024-03-01T10:35:00Z",
        "updated_at": "2024-03-01T10:35:00Z"
      },
      {
        "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
        "level": 2,
        "name": "Regular",
        "quantity": 300,
        "currency": "TWD",
        "amount": 3500,
        "created_at": "2024-03-01T10:36:00Z",
        "updated_at": "2024-03-01T10:36:00Z"
      }
    ]
  }
}
```

***

## event.updated [#eventupdated]

The `event.updated` event is triggered when an existing event is updated in the system.

### Event Properties [#event-properties-1]

| Property                | Type    | Description                                                      |
| ----------------------- | ------- | ---------------------------------------------------------------- |
| id                      | string  | Unique identifier for the event (UUID)                           |
| name                    | string  | Name of the event                                                |
| state                   | string  | Current state of the event                                       |
| started\_at             | string  | Start date and time of the event                                 |
| ended\_at               | string  | End date and time of the event                                   |
| created\_at             | string  | Timestamp when the event was created                             |
| updated\_at             | string  | Timestamp when the event was last updated                        |
| max\_attendee\_capacity | integer | Maximum number of attendees allowed                              |
| description             | string  | Detailed description of the event                                |
| slug                    | string  | URL-friendly identifier for the event                            |
| hosting\_type           | integer | Type of hosting for the event                                    |
| hosting\_id             | string  | Identifier for the hosting platform or location                  |
| join\_url               | string  | URL for attendees to join the event                              |
| published               | boolean | Indicates whether the event is published (true) or draft (false) |
| tickets                 | array   | List of ticket types available for the event                     |

### Ticket Properties [#ticket-properties-1]

Each ticket in the `tickets` array contains the following properties:

| Property    | Type    | Description                                         |
| ----------- | ------- | --------------------------------------------------- |
| id          | string  | Unique identifier for the ticket (UUID)             |
| level       | integer | Ticket level or tier                                |
| name        | string  | Name of the ticket type                             |
| quantity    | integer | Number of tickets available                         |
| currency    | string  | Currency code for the ticket price (default: "TWD") |
| amount      | number  | Price of the ticket                                 |
| created\_at | string  | Timestamp when the ticket was created               |
| updated\_at | string  | Timestamp when the ticket was last updated          |

### Hosting Types [#hosting-types-1]

The `hosting_type` property indicates the platform or method used to host the event. It can have the following values:

* `"zoom"`: The event is hosted using Zoom. In this case, the `hosting_id` will contain the Zoom meeting ID.
* `"live_session"`: The event uses Loopwise's built-in live session feature. The `hosting_id` will be the internal identifier for the live session.
* `"custom"`: A custom hosting solution is used, such as Google Meet or any other platform. For custom hosting, the `join_url` property will contain the link for attendees to join the event.

The `hosting_type` determines how attendees will access the event and what kind of integration or preparation is needed on the organizer's side.

### Example Payload [#example-payload-1]

```json
{
  "type": "event.updated",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Annual Tech Conference 2024 (Updated)",
    "state": "scheduled",
    "started_at": "2024-09-16T09:00:00Z",
    "ended_at": "2024-09-18T18:00:00Z",
    "created_at": "2024-03-01T10:30:00Z",
    "updated_at": "2024-03-15T14:45:00Z",
    "max_attendee_capacity": 600,
    "description": "Join us for the biggest tech conference of the year! Now with extended dates and increased capacity.",
    "slug": "annual-tech-conference-2024-updated",
    "hosting_type": "live_session",
    "hosting_id": "venue-123",
    "join_url": "https://example.com/events/annual-tech-conference-2024-updated",
    "published": true,
    "tickets": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440001",
        "level": 1,
        "name": "Early Bird",
        "quantity": 100,
        "currency": "TWD",
        "amount": 2500,
        "created_at": "2024-03-01T10:35:00Z",
        "updated_at": "2024-03-15T14:45:00Z"
      },
      {
        "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
        "level": 2,
        "name": "Regular",
        "quantity": 400,
        "currency": "TWD",
        "amount": 3500,
        "created_at": "2024-03-01T10:36:00Z",
        "updated_at": "2024-03-15T14:45:00Z"
      },
      {
        "id": "a1b2c3d4-e5f6-4a5b-9c8d-7e6f5a4b3c2d",
        "level": 3,
        "name": "Last Minute",
        "quantity": 100,
        "currency": "TWD",
        "amount": 4000,
        "created_at": "2024-03-15T14:45:00Z",
        "updated_at": "2024-03-15T14:45:00Z"
      }
    ]
  }
}
```


---

# Invoice Webhooks (https://docs.loopwise.com/webhooks/invoice)



## invoice.created [#invoicecreated]

The `invoice.created` event is triggered when a new invoice is created in the system.

### Event Properties [#event-properties]

| Field       | Type           | Description                                                           |
| ----------- | -------------- | --------------------------------------------------------------------- |
| id          | string         | Unique identifier for the invoice                                     |
| number      | string         | Invoice number (e.g., "AA12345678")                                   |
| state       | string         | Invoice state (issued, pending, voided, allowance\_issued, reissuing) |
| category    | string         | Invoice category (b2b or b2c)                                         |
| currency    | string         | Currency code (ISO 4217 format)                                       |
| amount      | number         | Total invoice amount                                                  |
| buyer\_name | string         | Name of the buyer                                                     |
| buyer\_ubn  | string or null | Buyer's Unified Business Number (for B2B invoices)                    |
| created\_at | string         | Timestamp of invoice creation (ISO 8601 format)                       |
| updated\_at | string         | Timestamp of last update (ISO 8601 format)                            |

### Invoice States [#invoice-states]

The `state` field can have the following values:

* `issued`: Invoice has been issued to the customer
* `pending`: Invoice is awaiting processing
* `voided`: Invoice has been voided/cancelled
* `allowance_issued`: Allowance (折讓) has been issued for this invoice
* `reissuing`: Invoice is in the process of being reissued

### Invoice Categories [#invoice-categories]

The `category` field indicates the invoice type:

* `b2c`: Business-to-Consumer invoice (for individual buyers)
* `b2b`: Business-to-Business invoice (for company buyers)

### Payment Information [#payment-information]

| Field             | Type   | Description                  |
| ----------------- | ------ | ---------------------------- |
| payment.id        | string | Unique payment identifier    |
| payment.trade\_no | string | Trade number for the payment |
| payment.amount    | number | Payment amount               |

### User Information [#user-information]

| Field      | Type   | Description            |
| ---------- | ------ | ---------------------- |
| user.id    | string | Unique user identifier |
| user.email | string | User's email address   |
| user.name  | string | User's name            |

### Example Payload [#example-payload]

```json title='Invoice Created Data Structure'
{
  "type": "invoice.created",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "number": "AA12345678",
    "state": "issued",
    "category": "b2c",
    "currency": "TWD",
    "amount": 1000.0,
    "buyer_name": "Test User",
    "buyer_ubn": null,
    "created_at": "2024-01-15T10:30:00Z",
    "updated_at": "2024-01-15T10:30:00Z",
    "payment": {
      "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
      "trade_no": "TEST20240115001",
      "amount": 1000
    },
    "user": {
      "id": "00f7407f-219e-4ada-9390-28934d7398d5",
      "email": "user@example.com",
      "name": "Test User"
    }
  }
}
```

### B2B Invoice Example [#b2b-invoice-example]

For business-to-business invoices, the `buyer_ubn` field will contain the company's Unified Business Number:

```json title='B2B Invoice Example'
{
  "type": "invoice.created",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440001",
    "number": "BB87654321",
    "state": "issued",
    "category": "b2b",
    "currency": "TWD",
    "amount": 5000.0,
    "buyer_name": "Example Company Ltd.",
    "buyer_ubn": "12345678",
    "created_at": "2024-01-15T10:30:00Z",
    "updated_at": "2024-01-15T10:30:00Z",
    "payment": {
      "id": "f47ac10b-58cc-4372-a567-0e02b2c3d480",
      "trade_no": "TEST20240115002",
      "amount": 5000
    },
    "user": {
      "id": "00f7407f-219e-4ada-9390-28934d7398d6",
      "email": "company@example.com",
      "name": "Company Admin"
    }
  }
}
```

***

## invoice.updated [#invoiceupdated]

The `invoice.updated` event is triggered when an invoice is updated in the system. This includes state changes such as voiding an invoice, issuing an allowance, or reissuing an invoice.

### Event Properties [#event-properties-1]

| Field       | Type           | Description                                                           |
| ----------- | -------------- | --------------------------------------------------------------------- |
| id          | string         | Unique identifier for the invoice                                     |
| number      | string         | Invoice number (e.g., "AA12345678")                                   |
| state       | string         | Invoice state (issued, pending, voided, allowance\_issued, reissuing) |
| category    | string         | Invoice category (b2b or b2c)                                         |
| currency    | string         | Currency code (ISO 4217 format)                                       |
| amount      | number         | Total invoice amount                                                  |
| buyer\_name | string         | Name of the buyer                                                     |
| buyer\_ubn  | string or null | Buyer's Unified Business Number (for B2B invoices)                    |
| created\_at | string         | Timestamp of invoice creation (ISO 8601 format)                       |
| updated\_at | string         | Timestamp of last update (ISO 8601 format)                            |

### Invoice States [#invoice-states-1]

The `state` field can have the following values:

* `issued`: Invoice has been issued to the customer
* `pending`: Invoice is awaiting processing
* `voided`: Invoice has been voided/cancelled
* `allowance_issued`: Allowance (折讓) has been issued for this invoice
* `reissuing`: Invoice is in the process of being reissued

### Invoice Categories [#invoice-categories-1]

The `category` field indicates the invoice type:

* `b2c`: Business-to-Consumer invoice (for individual buyers)
* `b2b`: Business-to-Business invoice (for company buyers)

### Payment Information [#payment-information-1]

| Field             | Type   | Description                  |
| ----------------- | ------ | ---------------------------- |
| payment.id        | string | Unique payment identifier    |
| payment.trade\_no | string | Trade number for the payment |
| payment.amount    | number | Payment amount               |

### User Information [#user-information-1]

| Field      | Type   | Description            |
| ---------- | ------ | ---------------------- |
| user.id    | string | Unique user identifier |
| user.email | string | User's email address   |
| user.name  | string | User's name            |

### Common Update Scenarios [#common-update-scenarios]

#### Invoice Voided [#invoice-voided]

When an invoice is voided, the `state` field will change to `voided`:

```json title='Invoice Voided Example'
{
  "type": "invoice.updated",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "number": "AA12345678",
    "state": "voided",
    "category": "b2c",
    "currency": "TWD",
    "amount": 1000.0,
    "buyer_name": "Test User",
    "buyer_ubn": null,
    "created_at": "2024-01-15T10:30:00Z",
    "updated_at": "2024-01-15T14:20:00Z",
    "payment": {
      "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
      "trade_no": "TEST20240115001",
      "amount": 1000
    },
    "user": {
      "id": "00f7407f-219e-4ada-9390-28934d7398d5",
      "email": "user@example.com",
      "name": "Test User"
    }
  }
}
```

#### Allowance Issued [#allowance-issued]

When an allowance is issued for an invoice, the `state` field will change to `allowance_issued`:

```json title='Allowance Issued Example'
{
  "type": "invoice.updated",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "number": "AA12345678",
    "state": "allowance_issued",
    "category": "b2c",
    "currency": "TWD",
    "amount": 1000.0,
    "buyer_name": "Test User",
    "buyer_ubn": null,
    "created_at": "2024-01-15T10:30:00Z",
    "updated_at": "2024-01-15T15:45:00Z",
    "payment": {
      "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
      "trade_no": "TEST20240115001",
      "amount": 1000
    },
    "user": {
      "id": "00f7407f-219e-4ada-9390-28934d7398d5",
      "email": "user@example.com",
      "name": "Test User"
    }
  }
}
```

### Example Payload [#example-payload-1]

```json title='Invoice Updated Data Structure'
{
  "type": "invoice.updated",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "number": "AA12345678",
    "state": "issued",
    "category": "b2c",
    "currency": "TWD",
    "amount": 1000.0,
    "buyer_name": "Test User",
    "buyer_ubn": null,
    "created_at": "2024-01-15T10:30:00Z",
    "updated_at": "2024-01-15T12:00:00Z",
    "payment": {
      "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
      "trade_no": "TEST20240115001",
      "amount": 1000
    },
    "user": {
      "id": "00f7407f-219e-4ada-9390-28934d7398d5",
      "email": "user@example.com",
      "name": "Test User"
    }
  }
}
```

### Notes [#notes]

* The `updated_at` timestamp will always reflect the time of the most recent update
* Monitor the `state` field to track invoice lifecycle changes
* For B2B invoices, the `buyer_ubn` field will contain the company's Unified Business Number


---

# Membership Plan Webhooks (https://docs.loopwise.com/webhooks/membership-plan)



## membership\_plan.created [#membership_plancreated]

The `membership_plan.created` event is triggered when a new membership plan is created in the system.

### Event Properties [#event-properties]

| Property             | Type    | Description                                                                                                           |
| -------------------- | ------- | --------------------------------------------------------------------------------------------------------------------- |
| id                   | string  | The unique identifier of the membership plan                                                                          |
| name                 | string  | The name of the membership plan                                                                                       |
| description          | string  | The description of the membership plan                                                                                |
| currency             | string  | The currency code for the plan's price (default: "TWD")                                                               |
| amount               | number  | The price amount of the plan                                                                                          |
| interval             | string  | The billing interval (month, year)                                                                                    |
| interval\_count      | integer | The number of intervals between billings                                                                              |
| active               | boolean | Indicates if the plan is active                                                                                       |
| created\_at          | string  | The timestamp when the plan was created (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z") |
| updated\_at          | string  | The timestamp when the plan was last updated (ISO 8601 format)                                                        |
| ended\_at            | string  | The timestamp when the plan ends (ISO 8601 format, if applicable)                                                     |
| plan\_type           | string  | The type of plan (recurring, fixed\_date, specific\_length, or lifetime)                                              |
| quantity             | integer | The quantity of items included in the plan                                                                            |
| sold\_items\_count   | integer | The number of items sold for this plan                                                                                |
| slug                 | string  | The URL-friendly identifier for the plan                                                                              |
| max\_interval\_count | integer | The maximum number of intervals allowed                                                                               |
| visible              | boolean | Indicates if the plan is visible to users                                                                             |

### Example Payload [#example-payload]

#### Recurring Plan Example [#recurring-plan-example]

```json
{
  "type": "membership_plan.created",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Premium Monthly Membership",
    "description": "Access to all premium features with monthly billing",
    "currency": "TWD",
    "amount": 1500.0,
    "interval": "month",
    "interval_count": 1,
    "active": true,
    "created_at": "2023-05-15T14:30:00Z",
    "updated_at": "2023-05-15T14:30:00Z",
    "ended_at": null,
    "plan_type": "recurring",
    "quantity": null,
    "sold_items_count": 0,
    "slug": "premium-monthly-membership",
    "max_interval_count": null,
    "visible": true
  }
}
```

#### Lifetime Plan Example [#lifetime-plan-example]

```json
{
  "type": "membership_plan.created",
  "data": {
    "id": "660e8500-f39c-52e5-b827-557766550111",
    "name": "Lifetime Premium Access",
    "description": "Permanent access to all premium features with a one-time payment",
    "currency": "TWD",
    "amount": 9999.0,
    "interval": "lifetime",
    "interval_count": 1,
    "active": true,
    "created_at": "2023-05-15T14:30:00Z",
    "updated_at": "2023-05-15T14:30:00Z",
    "ended_at": null,
    "plan_type": "lifetime",
    "quantity": null,
    "sold_items_count": 0,
    "slug": "lifetime-premium-access",
    "max_interval_count": null,
    "visible": true
  }
}
```

***

## membership\_plan.updated [#membership_planupdated]

The `membership_plan.updated` event is triggered when an existing membership plan is updated in the system.

### Event Properties [#event-properties-1]

| Property             | Type    | Description                                                                                                           |
| -------------------- | ------- | --------------------------------------------------------------------------------------------------------------------- |
| id                   | string  | The unique identifier of the membership plan                                                                          |
| name                 | string  | The name of the membership plan                                                                                       |
| description          | string  | The description of the membership plan                                                                                |
| currency             | string  | The currency code for the plan's price (default: "TWD")                                                               |
| amount               | number  | The price amount of the plan                                                                                          |
| interval             | string  | The billing interval (month, year)                                                                                    |
| interval\_count      | integer | The number of intervals between billings                                                                              |
| active               | boolean | Indicates if the plan is active                                                                                       |
| created\_at          | string  | The timestamp when the plan was created (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z") |
| updated\_at          | string  | The timestamp when the plan was last updated (ISO 8601 format)                                                        |
| ended\_at            | string  | The timestamp when the plan ends (ISO 8601 format, if applicable)                                                     |
| plan\_type           | string  | The type of plan (recurring, fixed\_date, specific\_length, or lifetime)                                              |
| quantity             | integer | The quantity of items included in the plan                                                                            |
| sold\_items\_count   | integer | The number of items sold for this plan                                                                                |
| slug                 | string  | The URL-friendly identifier for the plan                                                                              |
| max\_interval\_count | integer | The maximum number of intervals allowed                                                                               |
| visible              | boolean | Indicates if the plan is visible to users                                                                             |

### Example Payload [#example-payload-1]

#### Recurring Plan Example [#recurring-plan-example-1]

```json
{
  "type": "membership_plan.updated",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Premium Annual Membership",
    "description": "Access to all premium features with annual billing",
    "currency": "TWD",
    "amount": 15000.0,
    "interval": "year",
    "interval_count": 1,
    "active": true,
    "created_at": "2023-05-15T14:30:00Z",
    "updated_at": "2023-05-16T10:15:00Z",
    "ended_at": null,
    "plan_type": "recurring",
    "quantity": null,
    "sold_items_count": 5,
    "slug": "premium-annual-membership",
    "max_interval_count": null,
    "visible": true
  }
}
```

#### Lifetime Plan Example [#lifetime-plan-example-1]

```json
{
  "type": "membership_plan.updated",
  "data": {
    "id": "660e8500-f39c-52e5-b827-557766550111",
    "name": "Lifetime Premium Access",
    "description": "Permanent access to all premium features with a one-time payment",
    "currency": "TWD",
    "amount": 12999.0,
    "interval": "lifetime",
    "interval_count": 1,
    "active": true,
    "created_at": "2023-05-15T14:30:00Z",
    "updated_at": "2023-05-16T10:15:00Z",
    "ended_at": null,
    "plan_type": "lifetime",
    "quantity": null,
    "sold_items_count": 10,
    "slug": "lifetime-premium-access",
    "max_interval_count": null,
    "visible": true
  }
}
```


---

# Webhooks (https://docs.loopwise.com/webhooks/overview)



In this guide, we will look at how to register and consume webhooks to integrate your app with Loopwise. With webhooks, your app can know when something happens in Loopwise, such as a payment being completed or a user enrolling in a course.

## Integration Guide [#integration-guide]

Webhooks provide an efficient way for your system to receive real-time notifications about events from our platform. This includes scenarios such as when an order is placed, when a refund occurs, or when a new user registers.

## Handling Webhooks [#handling-webhooks]

Once your endpoint receives a webhook request, you should:

1. Validate the Request: Ensure the request is from a trusted source.
2. Parse the Data: Decode the JSON data and process it according to your business logic. For example, updating order status or recording transaction details.
3. Respond to the Request: Respond to the webhook request. Typically, a HTTP status code 200 indicates successful receipt.

## IP Allowlisting [#ip-allowlisting]

To enhance security and ensure that webhook requests are only received from legitimate sources, we recommend setting up IP allowlisting for your webhook endpoints. This ensures that only requests from Loopwise's trusted IP addresses are accepted.

### Loopwise Webhook IP Address [#loopwise-webhook-ip-address]

Please add the following IP address to your allowlist for incoming webhook requests:

```
52.194.91.27
```

## Webhook Signing and Verification [#webhook-signing-and-verification]

To ensure the security and integrity of webhook payloads sent from Loopwise, we implement a signing mechanism. This section explains how to use and verify the signature.

### Signature [#signature]

Each webhook request sent from Loopwise includes a signature in the header. This signature is computed using the payload and a secret signing key.

#### Header [#header]

The signature is included in the `Loopwise-Webhook-Signature` header of the HTTP request.

<Callout type="info">
  For backward compatibility during a deprecation window, the same signature is
  also sent under the legacy `Teachify-Webhook-Signature` header. New
  integrations should read `Loopwise-Webhook-Signature`; the legacy header will
  be removed in a future release.
</Callout>

### Verifying the Signature [#verifying-the-signature]

To verify that a webhook request genuinely came from Loopwise and wasn't tampered with, you should:

1. Extract the signature from the `Loopwise-Webhook-Signature` header.
2. Compute the expected signature using the payload and your signing key.
3. Compare the computed signature with the one in the header.

### Signature Computation [#signature-computation]

The signature is computed using HMAC SHA-256. Here are examples of how to compute and verify the signature:

```ruby title="Ruby"
require 'openssl'

def verify_signature(payload, signature, signing_key)
  computed_signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), signing_key, payload)
  computed_signature == signature
end

# Usage
payload = request.body.read  # Get the raw payload
signature = request.headers['Loopwise-Webhook-Signature']
signing_key = 'your_signing_key_here'

if verify_signature(payload, signature, signing_key)
  puts "Signature verified. Process the webhook."
else
  puts "Invalid signature. Reject the webhook."
end
```

```javascript title="Node.js"
const crypto = require("crypto");

function verifySignature(payload, signature, signingKey) {
	const computedSignature = crypto
		.createHmac("sha256", signingKey)
		.update(payload)
		.digest("hex");
	return computedSignature === signature;
}

// Usage
// Assuming you have middleware to access raw body
const payload = req.rawBody;
const signature = req.headers["loopwise-webhook-signature"];
const signingKey = "your_signing_key_here";

if (verifySignature(payload, signature, signingKey)) {
	console.log("Signature verified. Process the webhook.");
} else {
	console.log("Invalid signature. Reject the webhook.");
}
```

Replace `'your_signing_key_here'` with the actual signing key provided by Loopwise.

### Security Considerations [#security-considerations]

* Keep your signing key secret. Do not expose it in client-side code or public repositories.
* Always verify the signature before processing webhook payloads.
* Use HTTPS for all webhook endpoints to ensure the security of data in transit.
* The signature covers only the raw request body. It does **not** include a timestamp or a per-delivery identifier, so there is no built-in replay protection. The payload is `{ type, data }`, and `data.id` identifies the affected resource, not a unique delivery — the same value recurs across every update to that resource, so it cannot distinguish a replay from a genuine later event. Make handlers idempotent by reconciling against the resource's current state (re-fetch it, or compare with your stored copy) rather than by deduplicating on an id.

By implementing this verification process, you can ensure that the webhooks you receive are genuine and haven't been tampered with, enhancing the security of your integration with Loopwise.

## Delivery, Retries, and Limits [#delivery-retries-and-limits]

Each event is delivered as an HTTP `POST` with a JSON body. Your endpoint should respond with a `2xx` status code as quickly as possible. Each automatically scheduled request has a **30-second** timeout, and a request that exceeds it is treated as a failed delivery. The timeout is per request, so a delivery that follows redirects (up to four hops) can run longer than 30 seconds overall.

### Retry Schedule [#retry-schedule]

If a delivery fails, Loopwise retries with a fixed backoff based on the failure type:

| Failure type                                                                                                                        | Retry delays after the initial attempt | Total attempts (incl. initial) |
| ----------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- | ------------------------------ |
| Server errors (`5xx`), `408`, `429`; connection timeouts, refused/reset, host/network unreachable; transient TLS handshake failures | 1 min, 5 min, 30 min, 2 h              | 5                              |
| Other client errors (`4xx`); DNS resolution failures; TLS certificate-verification failures                                         | 1 min                                  | 2                              |

Some failures are terminal and are **not** retried: requests blocked by our SSRF protection and redirect loops. After the final attempt the delivery is marked failed and recorded in your webhook logs.

<Callout type="info">
  Deliveries can arrive out of order and, on retry, more than once. Since the
  payload carries no unique per-delivery id, make your handler idempotent by
  reconciling against the resource's current state rather than by deduplicating
  on an id.
</Callout>

### Endpoint Limit [#endpoint-limit]

Each school can have at most **5 active webhook endpoints**. Every active endpoint subscribed to an event receives its own delivery.

## Event Timing [#event-timing]

Events are scheduled shortly after the underlying change is committed, with a scheduling delay derived from the commit time (the current time reduced to a fixed window). The delay is not randomized, so changes committed at the same instant can share the same delay:

* `*.created` events are scheduled within roughly **0–59 seconds** of the change.
* `*.updated` events are scheduled within roughly **60–299 seconds** of the change, always after the corresponding `created` event.

These are scheduling delays, not delivery-time guarantees. Each subscribed endpoint is then staggered by a further \~5 seconds per endpoint (up to \~20 seconds for the fifth), and queue and network latency apply on top, so do not assume an event arrives within those windows.

### `user.updated` [#userupdated]

`user.updated` fires only when one of its **trigger fields** changes — `email`, `name`, or `phone_number`. The payload also carries `id`, `created_at`, `updated_at`, and `third_party_id`, but a change to those alone does not trigger delivery — in particular `updated_at` advances on every callback-running write and never, on its own, emits the event. Callback-running writes that touch none of the trigger fields (remember-me tokens, confirmation or reset-token rotation, role or flag flips) no longer emit it, and writes that bypass callbacks — such as sign-in timestamp updates made with `update_columns` — never did. The event still carries the full user object, not a diff, so it remains a signal to re-read the current state rather than a per-field change log: treat delivery as at-least-once and make your handler idempotent (compare against your own stored copy, or re-fetch the user, before acting). `third_party_id` lives on a separate identity record and is not part of this filter — a change to it alone does not emit `user.updated`.


---

# Payment Webhooks (https://docs.loopwise.com/webhooks/payment)



## payment.paid [#paymentpaid]

The `payment.paid` event is triggered when a payment is successfully completed in the system.

### Event Properties [#event-properties]

| Field            | Type            | Description                                                                                                   |
| ---------------- | --------------- | ------------------------------------------------------------------------------------------------------------- |
| id               | string          | Unique identifier for the payment transaction                                                                 |
| trade\_no        | string          | Unique trade number for the transaction                                                                       |
| currency         | string          | Currency code (ISO 4217 format)                                                                               |
| amount           | integer         | Total transaction amount                                                                                      |
| original\_amount | integer         | Original transaction amount before refunds/adjustments                                                        |
| refunded\_amount | integer or null | Refunded amount (null if no refund)                                                                           |
| paid\_at         | string          | Timestamp of payment completion (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z") |
| created\_at      | string          | Timestamp of transaction creation (ISO 8601 format)                                                           |
| refunded\_at     | string or null  | Timestamp of refund if applicable (ISO 8601 format)                                                           |
| payment\_state   | string          | Current payment state (paid, refunding, refunded, failed)                                                     |
| payment\_type    | string          | Payment method (credit, web\_atm, atm, cvs, line\_pay)                                                        |
| affiliate\_code  | string or null  | Associated affiliate code                                                                                     |
| remark           | string or null  | Additional order notes                                                                                        |

### User Information [#user-information]

| Field                 | Type   | Description                        |
| --------------------- | ------ | ---------------------------------- |
| user.id               | string | Unique user identifier             |
| user.email            | string | User's email address               |
| user.name             | string | User's name                        |
| user.phone\_number    | string | User's phone number                |
| user.third\_party\_id | string | Third-party system user identifier |

### Payment Method Details [#payment-method-details]

| Field                               | Type           | Description                                     |
| ----------------------------------- | -------------- | ----------------------------------------------- |
| payment\_method\_details.last\_four | string or null | Last four digits of credit card (if applicable) |
| payment\_method\_details.brand      | string or null | Credit card brand (if applicable)               |

The `brand` field can have the following values:

* `visa`: Visa credit/debit card
* `mastercard`: Mastercard credit/debit card
* `jcb`: JCB credit card
* `unionpay`: UnionPay card
* `amex`: American Express card
* `dinersclub`: Diners Club card
* `discover`: Discover card
* `unknown`: Card brand could not be determined

### Line Items [#line-items]

Each item in the `lineitems` array contains:

| Field                | Type           | Description                                                                                                |
| -------------------- | -------------- | ---------------------------------------------------------------------------------------------------------- |
| name                 | string         | Item name                                                                                                  |
| quantity             | integer        | Quantity purchased                                                                                         |
| amount               | integer        | Current amount for this item (may reflect partial or no refunds)                                           |
| refunded\_amount     | integer        | Refunded amount for this item (0 if no refund applied to this item)                                        |
| item\_type           | string         | Item type (CurriculumPlan, Ticket, MembershipPlan, DigitalProduct, OrderBump)                              |
| item\_id             | string         | Unique item identifier                                                                                     |
| item\_slug           | string         | URL-friendly item identifier                                                                               |
| product\_type        | string         | Product type (Course, Event, MembershipPlan, DigitalProduct)                                               |
| product\_id          | string         | Unique product identifier                                                                                  |
| order\_bump\_details | object or null | Additional details for OrderBump items (only present when item\_type is "OrderBump")                       |
| metadata             | object or null | Custom metadata key-value pairs for this item (only present when the External Metadata feature is enabled) |

When `item_type` is "OrderBump", the `order_bump_details` field will be present with the following structure:

| Field      | Type   | Description                                          |
| ---------- | ------ | ---------------------------------------------------- |
| item\_type | string | Type of the order bump item (e.g., "CurriculumPlan") |
| item\_id   | string | Unique identifier of the order bump item             |
| item\_slug | string | URL-friendly identifier of the order bump item       |

If `item_type` is not "OrderBump", the `order_bump_details` field will not be present in the lineitem.

The `metadata` field is a flat object of string key-value pairs. It is only present when your school has the External Metadata feature enabled and the item has metadata defined. Plan-level metadata takes precedence over product-level metadata when keys conflict.

### Additional Information [#additional-information]

| Field             | Type                     | Description                  |
| ----------------- | ------------------------ | ---------------------------- |
| coupon            | object or null           | Applied coupon details       |
| shipping\_address | object                   | Shipping address information |
| invoice           | object                   | Invoice details              |
| custom\_data      | array of objects         | Custom data fields           |
| refund\_history   | array of objects or null | History of refunds (if any)  |

For detailed descriptions of fields within nested objects (coupon, shipping\_address, invoice, custom\_data, refund\_history), please refer to the full documentation.

#### Invoice Details [#invoice-details]

| Field         | Type    | Description                                                    |
| ------------- | ------- | -------------------------------------------------------------- |
| state         | string  | Invoice state (e.g., "issued")                                 |
| number        | string  | Invoice number                                                 |
| buyer\_ubn    | string  | Buyer's Unified Business Number (null for individual buyers)   |
| buyer\_name   | string  | Name of the buyer                                              |
| category      | string  | Invoice category (b2b or b2c)                                  |
| carrier\_type | string  | Type of carrier for e-invoice (member, certificate, or mobile) |
| carrier\_num  | string  | Carrier number for e-invoice (when applicable)                 |
| donation      | boolean | Indicates if the invoice is for donation (only for b2c)        |
| love\_code    | string  | Donation institution code (only present when donation is true) |

Notes:

* The `category` field can be either "b2b" (business-to-business) or "b2c" (business-to-consumer).
* The `carrier_num` field is only present when `carrier_type` is "certificate" or "mobile".
* The `donation` field is only applicable when `category` is "b2c".
* The `love_code` field is only present when `donation` is true.

### Example Payload [#example-payload]

```json title='Payment Data Structure'
{
	"type": "payment.paid",
	"data": {
		"id": "550e8400-e29b-41d4-a716-446655440000",
		"user": {
			"id": "00f7407f-219e-4ada-9390-28934d7398d5",
			"email": "demo@kaik.io",
			"name": "Kaik",
			"phone_number": "+886911222333",
			"third_party_id": "123123"
		},
		"trade_no": "DEM2022053167602AF30",
		"currency": "TWD",
		"amount": 1800,
		"paid_at": "2022-05-31T11:28:31Z",
		"created_at": "2022-05-31T11:26:42Z",
		"refunded_at": null,
		"refunded_amount": null,
		"original_amount": 1800,
		"payment_state": "paid",
		"payment_type": "credit",
		"payment_method_details": {
			"last_four": "1234",
			"brand": "visa"
		},
		"affiliate_code": "newswebPAGE7",
		"remark": "Order note",
		"lineitems": [
			{
				"name": "Course Name 123",
				"quantity": 1,
				"amount": 500,
				"refunded_amount": 0,
				"item_type": "CurriculumPlan",
				"item_id": "51e07cb8-e450-4ed4-8b54-e0144d4da793",
				"item_slug": "test-slug",
				"product_type": "Course",
				"product_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
				"metadata": {
					"crm_id": "sample-crm_id",
					"source": "sample-source"
				}
			},
			{
				"name": "Course Name",
				"quantity": 1,
				"amount": 1000,
				"refunded_amount": 0,
				"item_type": "CurriculumPlan",
				"item_id": "f8a7b6c5-d4e3-2f1g-9h8i-7j6k5l4m3n2o",
				"item_slug": "test-slug",
				"product_type": "Course",
				"product_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef"
			},
			{
				"name": "Course Bonus Package",
				"quantity": 1,
				"amount": 300,
				"refunded_amount": 0,
				"item_type": "OrderBump",
				"item_id": "c5d6e7f8-g9h0-i1j2-k3l4-m5n6o7p8q9r0",
				"item_slug": "course-bonus-package",
				"product_type": "Course",
				"product_id": "s1t2u3v4-w5x6-y7z8-9a0b-c1d2e3f4g5h6",
				"order_bump_details": {
					"item_type": "CurriculumPlan",
					"item_id": "h8i9j0k1-l2m3-n4o5-p6q7-r8s9t0u1v2w3",
					"item_slug": "course-bonus-package"
				}
			}
		],
		"refund_history": [],
		"coupon": {
			"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
			"name": "30% Off",
			"code": "30p-OFF"
		},
		"shipping_address": {
			"city": "Taipei",
			"district": "Songshan District",
			"postal_code": "105065",
			"address": "xxxxx",
			"full_address": "105065 Taipei City, Songshan District, xxx"
		},
		"invoice": {
			"state": "issued",
			"number": "BL90912974",
			"buyer_ubn": null,
			"buyer_name": "Kaik Demo",
			"category": "b2c",
			"carrier_type": "mobile",
			"carrier_num": "/0000001",
			"donation": false,
			"love_code": null
		},
		"custom_data": [
			{
				"field_id": "xxxxxx",
				"label": "Field One Name",
				"type": "multi_select",
				"values": ["A", "B"],
				"position": 0
			},
			{
				"field_id": "xxxxxx",
				"label": "Field Two Name",
				"type": "radio",
				"values": ["1"],
				"position": 1
			},
			{
				"field_id": "xxxxxx",
				"label": "Field Three Name",
				"type": "text",
				"values": ["xxxxx"],
				"position": 2
			}
		]
	}
}
```

***

## payment.refund [#paymentrefund]

The `payment.refund` event is triggered when a refund is processed for a payment in the system.

### Event Properties [#event-properties-1]

| Field            | Type           | Description                                                                                                            |
| ---------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------- |
| id               | string         | Unique identifier for the payment transaction                                                                          |
| trade\_no        | string         | Unique trade number for the transaction                                                                                |
| currency         | string         | Currency code (ISO 4217 format)                                                                                        |
| amount           | integer        | Current transaction amount after refund                                                                                |
| original\_amount | integer        | Original transaction amount before refund                                                                              |
| refunded\_amount | integer        | Total refunded amount                                                                                                  |
| paid\_at         | string         | Timestamp of original payment completion (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z") |
| created\_at      | string         | Timestamp of transaction creation (ISO 8601 format)                                                                    |
| refunded\_at     | string         | Timestamp of latest refund (ISO 8601 format)                                                                           |
| payment\_state   | string         | Current payment state (refunding, refunded)                                                                            |
| payment\_type    | string         | Original payment method (credit, web\_atm, atm, cvs, line\_pay)                                                        |
| affiliate\_code  | string or null | Associated affiliate code                                                                                              |
| remark           | string or null | Additional order notes                                                                                                 |

### User Information [#user-information-1]

| Field                 | Type   | Description                        |
| --------------------- | ------ | ---------------------------------- |
| user.id               | string | Unique user identifier             |
| user.email            | string | User's email address               |
| user.name             | string | User's name                        |
| user.phone\_number    | string | User's phone number                |
| user.third\_party\_id | string | Third-party system user identifier |

### Refund History [#refund-history]

Each item in the `refund_history` array contains:

| Field        | Type    | Description                |
| ------------ | ------- | -------------------------- |
| amount       | integer | Refunded amount            |
| refunded\_at | string  | Timestamp of this refund   |
| reason       | string  | Reason provided for refund |

The `refund_history` field is an array of objects or null. Each object in the array represents a refund transaction and contains the following properties:

* `amount`: An integer representing the refunded amount.
* `refunded_at`: A string containing the timestamp of the refund in the format "YYYY-MM-DD HH:MM:SS +HHMM".
* `reason`: A string explaining the reason for the refund.

### Payment Method Details [#payment-method-details-1]

| Field                               | Type           | Description                                     |
| ----------------------------------- | -------------- | ----------------------------------------------- |
| payment\_method\_details.last\_four | string or null | Last four digits of credit card (if applicable) |
| payment\_method\_details.brand      | string or null | Credit card brand (if applicable)               |

The `brand` field can have the following values:

* `visa`: Visa credit/debit card
* `mastercard`: Mastercard credit/debit card
* `jcb`: JCB credit card
* `unionpay`: UnionPay card
* `amex`: American Express card
* `dinersclub`: Diners Club card
* `discover`: Discover card
* `unknown`: Card brand could not be determined

### Line Items [#line-items-1]

Each item in the `lineitems` array contains:

| Field                | Type           | Description                                                                                                |
| -------------------- | -------------- | ---------------------------------------------------------------------------------------------------------- |
| name                 | string         | Item name                                                                                                  |
| quantity             | integer        | Quantity purchased                                                                                         |
| amount               | integer        | Original amount for this item                                                                              |
| refunded\_amount     | integer        | Refunded amount for this item                                                                              |
| item\_type           | string         | Item type (CurriculumPlan, Ticket, MembershipPlan, DigitalProduct, OrderBump)                              |
| item\_id             | string         | Unique item identifier                                                                                     |
| item\_slug           | string         | URL-friendly item identifier                                                                               |
| product\_type        | string         | Product type (Course, Event, MembershipPlan, DigitalProduct)                                               |
| product\_id          | string         | Unique product identifier                                                                                  |
| order\_bump\_details | object or null | Additional details for OrderBump items (only present when item\_type is "OrderBump")                       |
| metadata             | object or null | Custom metadata key-value pairs for this item (only present when the External Metadata feature is enabled) |

When `item_type` is "OrderBump", the `order_bump_details` field will be present with the following structure:

| Field      | Type   | Description                                          |
| ---------- | ------ | ---------------------------------------------------- |
| item\_type | string | Type of the order bump item (e.g., "CurriculumPlan") |
| item\_id   | string | Unique identifier of the order bump item             |
| item\_slug | string | URL-friendly identifier of the order bump item       |

If `item_type` is not "OrderBump", the `order_bump_details` field will not be present in the lineitem.

The `metadata` field is a flat object of string key-value pairs. It is only present when your school has the External Metadata feature enabled and the item has metadata defined. Plan-level metadata takes precedence over product-level metadata when keys conflict.

### Additional Information [#additional-information-1]

| Field             | Type                     | Description                  |
| ----------------- | ------------------------ | ---------------------------- |
| coupon            | object or null           | Applied coupon details       |
| shipping\_address | object                   | Shipping address information |
| invoice           | object                   | Invoice details              |
| custom\_data      | array of objects         | Custom data fields           |
| refund\_history   | array of objects or null | History of refunds (if any)  |

For detailed descriptions of fields within nested objects (coupon, shipping\_address, invoice, custom\_data, refund\_history), please refer to the full documentation.

#### Invoice Details [#invoice-details-1]

| Field         | Type    | Description                                                    |
| ------------- | ------- | -------------------------------------------------------------- |
| state         | string  | Invoice state (e.g., "issued")                                 |
| number        | string  | Invoice number                                                 |
| buyer\_ubn    | string  | Buyer's Unified Business Number (null for individual buyers)   |
| buyer\_name   | string  | Name of the buyer                                              |
| category      | string  | Invoice category (b2b or b2c)                                  |
| carrier\_type | string  | Type of carrier for e-invoice (member, certificate, or mobile) |
| carrier\_num  | string  | Carrier number for e-invoice (when applicable)                 |
| donation      | boolean | Indicates if the invoice is for donation (only for b2c)        |
| love\_code    | string  | Donation institution code (only present when donation is true) |

Notes:

* The `category` field can be either "b2b" (business-to-business) or "b2c" (business-to-consumer).
* The `carrier_num` field is only present when `carrier_type` is "certificate" or "mobile".
* The `donation` field is only applicable when `category` is "b2c".
* The `love_code` field is only present when `donation` is true.

### Example Payload [#example-payload-1]

```json title='Refund Data Structure'
{
	"type": "payment.refund",
	"data": {
		"id": "550e8400-e29b-41d4-a716-446655440000",
		"user": {
			"id": "00f7407f-219e-4ada-9390-28934d7398d5",
			"email": "demo@kaik.io",
			"name": "Kaik",
			"phone_number": "+886911222333",
			"third_party_id": "123123"
		},
		"trade_no": "DEM2022053167602AF30",
		"currency": "TWD",
		"amount": 1450,
		"paid_at": "2022-05-31T11:28:31Z",
		"created_at": "2022-05-31T11:26:42Z",
		"refunded_at": "2022-06-01T14:30:00Z",
		"refunded_amount": 350,
		"original_amount": 1800,
		"payment_state": "refunded",
		"payment_type": "credit",
		"payment_method_details": {
			"last_four": "1234",
			"brand": "visa"
		},
		"affiliate_code": "newswebPAGE7",
		"remark": "Order note",
		"lineitems": [
			{
				"name": "Course Name 123",
				"quantity": 1,
				"amount": 400,
				"refunded_amount": 100,
				"item_type": "CurriculumPlan",
				"item_id": "51e07cb8-e450-4ed4-8b54-e0144d4da793",
				"item_slug": "test-slug",
				"product_type": "Course",
				"product_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
				"metadata": {
					"crm_id": "sample-crm_id",
					"source": "sample-source"
				}
			},
			{
				"name": "Course Name",
				"quantity": 1,
				"amount": 800,
				"refunded_amount": 200,
				"item_type": "CurriculumPlan",
				"item_id": "f8a7b6c5-d4e3-2f1g-9h8i-7j6k5l4m3n2o",
				"item_slug": "test-slug",
				"product_type": "Course",
				"product_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef"
			},
			{
				"name": "Course Bonus Package",
				"quantity": 1,
				"amount": 250,
				"refunded_amount": 50,
				"item_type": "OrderBump",
				"item_id": "c5d6e7f8-g9h0-i1j2-k3l4-m5n6o7p8q9r0",
				"item_slug": "course-bonus-package",
				"product_type": "Course",
				"product_id": "s1t2u3v4-w5x6-y7z8-9a0b-c1d2e3f4g5h6",
				"order_bump_details": {
					"item_type": "CurriculumPlan",
					"item_id": "h8i9j0k1-l2m3-n4o5-p6q7-r8s9t0u1v2w3",
					"item_slug": "course-bonus-package"
				}
			}
		],
		"refund_history": [
			{
				"amount": 350,
				"refunded_at": "2022-06-01T14:30:00Z",
				"reason": "Partial refund requested by customer"
			}
		],
		"coupon": {
			"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
			"name": "30% Off",
			"code": "30p-OFF"
		},
		"shipping_address": {
			"city": "Taipei",
			"district": "Songshan District",
			"postal_code": "105065",
			"address": "xxxxx",
			"full_address": "105065 Taipei City, Songshan District, xxx"
		},
		"invoice": {
			"state": "issued",
			"number": "BL90912974",
			"buyer_ubn": null,
			"buyer_name": "Kaik Demo",
			"category": "b2c",
			"carrier_type": "mobile",
			"carrier_num": "/0000001",
			"donation": false,
			"love_code": null
		},
		"custom_data": [
			{
				"field_id": "xxxxxx",
				"label": "Field One Name",
				"type": "multi_select",
				"values": ["A", "B"],
				"position": 0
			},
			{
				"field_id": "xxxxxx",
				"label": "Field Two Name",
				"type": "radio",
				"values": ["1"],
				"position": 1
			},
			{
				"field_id": "xxxxxx",
				"label": "Field Three Name",
				"type": "text",
				"values": ["xxxxx"],
				"position": 2
			}
		]
	}
}
```


---

# Post Webhooks (https://docs.loopwise.com/webhooks/post)



## post.created [#postcreated]

The `post.created` event is triggered when a new post is created in the system.

### Event Properties [#event-properties]

| Property    | Type    | Description                              |
| ----------- | ------- | ---------------------------------------- |
| id          | string  | Unique identifier for the post (UUID)    |
| title       | string  | Title of the post                        |
| subtitle    | string  | Subtitle of the post                     |
| excerpt     | string  | Brief excerpt of the post content        |
| state       | string  | Current state of the post                |
| created\_at | string  | Timestamp when the post was created      |
| updated\_at | string  | Timestamp when the post was last updated |
| slug        | string  | URL-friendly identifier for the post     |
| published   | boolean | Indicates whether the post is published  |

### Example Payload [#example-payload]

This example shows a typical payload that you'll receive when a new post is created. All timestamps are in ISO 8601 format and UTC timezone.

```json
{
  "type": "post.created",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "title": "Getting Started with Webhooks",
    "subtitle": "A comprehensive guide",
    "excerpt": "Learn how to integrate and use webhooks effectively...",
    "state": "draft",
    "created_at": "2024-03-21T13:45:30Z",
    "updated_at": "2024-03-21T13:45:30Z",
    "slug": "getting-started-with-webhooks",
    "published": false
  }
}
```

***

## post.updated [#postupdated]

The `post.updated` event is triggered when an existing post is modified in the system.

### Event Properties [#event-properties-1]

| Property    | Type    | Description                              |
| ----------- | ------- | ---------------------------------------- |
| id          | string  | Unique identifier for the post (UUID)    |
| title       | string  | Title of the post                        |
| subtitle    | string  | Subtitle of the post                     |
| excerpt     | string  | Brief excerpt of the post content        |
| state       | string  | Current state of the post                |
| created\_at | string  | Timestamp when the post was created      |
| updated\_at | string  | Timestamp when the post was last updated |
| slug        | string  | URL-friendly identifier for the post     |
| published   | boolean | Indicates whether the post is published  |

### Example Payload [#example-payload-1]

This example shows a typical payload that you'll receive when a post is updated. All timestamps are in ISO 8601 format and UTC timezone.

```json
{
  "type": "post.updated",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "title": "Getting Started with Webhooks - Updated",
    "subtitle": "A comprehensive guide to webhook integration",
    "excerpt": "Learn how to integrate and use webhooks effectively in your applications...",
    "state": "published",
    "created_at": "2024-03-21T13:45:30Z",
    "updated_at": "2024-03-21T14:30:15Z",
    "slug": "getting-started-with-webhooks",
    "published": true
  }
}
```


---

# User Webhooks (https://docs.loopwise.com/webhooks/user)



## user.created [#usercreated]

The `user.created` event is triggered when a new user is created in the system.

### Event Properties [#event-properties]

| Property         | Type           | Description                                                                                                       |
| ---------------- | -------------- | ----------------------------------------------------------------------------------------------------------------- |
| id               | string         | Unique identifier for the user (UUID)                                                                             |
| email            | string         | Email address of the user                                                                                         |
| name             | string         | Full name of the user                                                                                             |
| phone\_number    | string         | Phone number of the user                                                                                          |
| created\_at      | string         | Timestamp when the user was created (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z") |
| updated\_at      | string         | Timestamp when the user was last updated (ISO 8601 format)                                                        |
| third\_party\_id | string or null | Third-party system identifier for the user (if applicable)                                                        |

### Example Payload [#example-payload]

```json
{
  "type": "user.created",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "email": "test@example.com",
    "name": "Test User",
    "phone_number": "1234567890",
    "created_at": "2023-12-04T18:45:44Z",
    "updated_at": "2023-12-04T18:45:44Z",
    "third_party_id": null
  }
}
```

***

## user.updated [#userupdated]

The `user.updated` event fires only when one of its **trigger fields** changes — `email`, `name`, or `phone_number`. The payload also carries `id`, `created_at`, `updated_at`, and `third_party_id`, but a change to those alone does not trigger delivery — in particular `updated_at` advances on every callback-running write and never, on its own, emits the event, and `third_party_id` lives on a separate identity record that is not part of this filter. The payload is the full user object, not a diff, so treat delivery as at-least-once and make your handler idempotent. See the [webhooks overview](/webhooks/overview#userupdated) for the full contract.

### Event Properties [#event-properties-1]

| Property         | Type           | Description                                                                                                       |
| ---------------- | -------------- | ----------------------------------------------------------------------------------------------------------------- |
| id               | string         | Unique identifier for the user (UUID)                                                                             |
| email            | string         | Email address of the user                                                                                         |
| name             | string         | Full name of the user                                                                                             |
| phone\_number    | string         | Phone number of the user                                                                                          |
| created\_at      | string         | Timestamp when the user was created (ISO 8601 format, e.g. "2023-12-04T18:45:44+08:00" or "2023-12-04T10:45:44Z") |
| updated\_at      | string         | Timestamp when the user was last updated (ISO 8601 format)                                                        |
| third\_party\_id | string or null | Third-party system identifier for the user (if applicable)                                                        |

### Example Payload [#example-payload-1]

```json
{
  "type": "user.updated",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "email": "test@example.com",
    "name": "Updated Test User",
    "phone_number": "0987654321",
    "created_at": "2023-12-04T18:45:44Z",
    "updated_at": "2023-12-04T19:30:00Z",
    "third_party_id": "external_id_123"
  }
}
```


---

# Assignment Mutations (https://docs.loopwise.com/api/mutations/assignments)



The assignment mutations allow you to create, update, and delete assignments within your Loopwise courses. These operations enable you to programmatically manage student assignments and grade submissions.

All assignment mutations return an `errors` field in the response that will contain any validation or processing errors that occurred during the operation.

## Available Mutations [#available-mutations]

### createAssignment [#createassignment]

> **Note:** This mutation is still under development and will be fully documented when available.

Creates a new assignment in a course, defining deliverables and due dates for students.

### updateAssignment [#updateassignment]

> **Note:** This mutation is still under development and will be fully documented when available.

Updates an existing assignment with new properties, such as description, due date, or requirements.

### deleteAssignment [#deleteassignment]

> **Note:** This mutation is still under development and will be fully documented when available.

Deletes an assignment from a course.

### gradeSubmission [#gradesubmission]

> **Note:** This mutation is still under development and will be fully documented when available.

Grades a student's assignment submission, providing feedback and a numerical score.


---

# Consulting Mutations (https://docs.loopwise.com/api/mutations/consulting)



The consulting mutations let you programmatically manage consulting services (1-on-1 / group coaching offerings) and the time-slot meetings booked under them.

> **Endpoint and authentication.** All admin mutations live on `POST /admin/graphql` — **not** the `/graphql` endpoint, which is the public school API. Authenticate with an `sk_live_…` key in the `X-Teachify-API-Key` header. Service mutations require the `courses:write` scope; meeting-enrollment mutations require `students:write` (or `members:write`).

**Service entity mutations** (require `courses:write`):

* `createConsultingService` — Create a new consulting service under a course
* `updateConsultingService` — Partial update of an existing service
* `deleteConsultingService` — Soft-delete a service

**Meeting (time-slot) mutations** (require `courses:write`):

* `bulkCreateConsultingMeetings` — Create multiple time slots under a service in one round trip
* `updateConsultingMeeting` — Partial update of a single meeting
* `cancelConsultingMeeting` — Cancel a single meeting
* `bulkCancelConsultingMeetings` — Cancel multiple meetings in one round trip

**Meeting enrollment mutations** (require `students:write` or `members:write`):

* `enrollStudentToConsultingMeeting` — Add a student to a meeting
* `removeStudentFromConsultingMeeting` — Remove a student from a meeting
* `rescheduleStudentConsultingMeeting` — Atomically move a student from one meeting to another

All mutations return an `errors` field with any validation or processing failures. Field names use `camelCase` on the wire; type names in this document use the GraphQL schema name (e.g. `AdminConsultingServiceInput`).

***

## Create a Consulting Service [#create-a-consulting-service]

The `createConsultingService` mutation creates a new consulting service under an existing course.

### Input Parameters [#input-parameters]

| Field   | Type                           | Description  |
| ------- | ------------------------------ | ------------ |
| `input` | `AdminConsultingServiceInput!` | Input object |

### AdminConsultingServiceInput Fields [#adminconsultingserviceinput-fields]

| Field             | Type        | Required | Description                                                                                      |
| ----------------- | ----------- | -------- | ------------------------------------------------------------------------------------------------ |
| `name`            | `String!`   | Yes      | Display name of the service                                                                      |
| `courseId`        | `String!`   | Yes      | Parent course ID. Course must belong to the same school                                          |
| `slug`            | `String`    | No       | URL slug (lowercase letters, numbers, hyphens). If omitted, derived from `name` by `friendly_id` |
| `description`     | `String`    | No       | Service description                                                                              |
| `lecturerId`      | `String`    | No       | Assigned lecturer ID. Must belong to the same school                                             |
| `published`       | `Boolean`   | No       | When `true`, marks the service as published and stamps `publishedAt` to the current time         |
| `tags`            | `[String!]` | No       | Tag list stored in settings JSON. Replaces the entire list — pass all tags every time            |
| `ratingFormId`    | `String`    | No       | Linked feedback form ID                                                                          |
| `backgroundColor` | `String`    | No       | UI background color (hex)                                                                        |

### Return Type [#return-type]

```graphql
type AdminConsultingServiceCreatePayload {
  consultingService: AdminConsultingService
  errors: [String!]
}
```

### Example [#example]

```graphql
mutation CreateConsultingService {
  createConsultingService(input: {
    name: "1-on-1 Career Coaching"
    courseId: "ab6ee332-614d-475d-93b5-abc5ebb1fc84"
    slug: "career-coaching"
    description: "30-minute career coaching session"
    lecturerId: "f1b2c3d4-5678-90ef-abcd-ef1234567890"
    published: true
    tags: ["career", "coaching"]
  }) {
    consultingService {
      id
      name
      slug
      published
      publishedAt
      effectiveTimezone
    }
    errors
  }
}
```

### Sample Response [#sample-response]

```json
{
  "data": {
    "createConsultingService": {
      "consultingService": {
        "id": "35a72dba-c3cc-4a06-b7eb-d784d010386e",
        "name": "1-on-1 Career Coaching",
        "slug": "career-coaching",
        "published": true,
        "publishedAt": 1747397869,
        "effectiveTimezone": "Asia/Taipei"
      },
      "errors": null
    }
  }
}
```

### Common Errors [#common-errors]

| Error code       | Message                                                        |
| ---------------- | -------------------------------------------------------------- |
| `CONSULTING-002` | Parent course not found or not in this school                  |
| `CONSULTING-003` | Slug must only contain lowercase letters, numbers, and hyphens |
| `CONSULTING-005` | Lecturer not found or not in this school                       |
| `CONSULTING-006` | Rating form not found or not in this school                    |

***

## Update a Consulting Service [#update-a-consulting-service]

The `updateConsultingService` mutation applies a partial update. Only provided keys are changed; explicit `null` clears nullable fields (`lecturerId`, `ratingFormId`, `backgroundColor`).

> **Not updatable**: `courseId` is intentionally read-only. Reparenting a service across courses would orphan its meetings and enrollments — create a new service instead.
>
> **Publish-state semantics**: setting `published: false` does **not** clear `publishedAt`; the historical first-publish timestamp is preserved.
>
> **Lecturer reassignment**: changes the service-level lecturer only. Existing meetings keep the lecturer they were created with — update each meeting individually if you need to reassign past or scheduled slots.

### Input Parameters [#input-parameters-1]

| Field   | Type                                 | Description                            |
| ------- | ------------------------------------ | -------------------------------------- |
| `id`    | `String!`                            | ID of the consulting service to update |
| `input` | `AdminConsultingServiceUpdateInput!` | Partial-update fields                  |

### AdminConsultingServiceUpdateInput Fields [#adminconsultingserviceupdateinput-fields]

| Field             | Type        | Description                                                           |
| ----------------- | ----------- | --------------------------------------------------------------------- |
| `name`            | `String`    | Display name                                                          |
| `slug`            | `String`    | URL slug                                                              |
| `description`     | `String`    | Service description                                                   |
| `lecturerId`      | `String`    | Lecturer ID; pass `null` to remove                                    |
| `published`       | `Boolean`   | Set to `true` to publish (auto-stamps `publishedAt` on first publish) |
| `tags`            | `[String!]` | Tag list. Replaces the entire list                                    |
| `ratingFormId`    | `String`    | Linked form ID; pass `null` to remove                                 |
| `backgroundColor` | `String`    | UI background color (hex); pass `null` to remove                      |

### Example [#example-1]

```graphql
mutation UpdateConsultingService {
  updateConsultingService(
    id: "35a72dba-c3cc-4a06-b7eb-d784d010386e"
    input: {
      description: "Updated 45-minute career coaching session"
      tags: ["career", "coaching", "premium"]
    }
  ) {
    consultingService {
      id
      name
      description
      tags
    }
    errors
  }
}
```

### Common Errors [#common-errors-1]

| Error code       | Message                                                        |
| ---------------- | -------------------------------------------------------------- |
| `CONSULTING-001` | Consulting service not found                                   |
| `CONSULTING-003` | Slug must only contain lowercase letters, numbers, and hyphens |
| `CONSULTING-005` | Lecturer not found or not in this school                       |
| `CONSULTING-006` | Rating form not found or not in this school                    |

***

## Delete a Consulting Service [#delete-a-consulting-service]

The `deleteConsultingService` mutation soft-deletes (discards) a consulting service. Refuses to delete when the service still has undiscarded, non-canceled future meetings — cancel them via `bulkCancelConsultingMeetings` (or wait for them to end) first.

### Input Parameters [#input-parameters-2]

| Field | Type      | Description                            |
| ----- | --------- | -------------------------------------- |
| `id`  | `String!` | ID of the consulting service to delete |

### Example [#example-2]

```graphql
mutation DeleteConsultingService {
  deleteConsultingService(id: "35a72dba-c3cc-4a06-b7eb-d784d010386e") {
    consultingService {
      id
      discardedAt
    }
    errors
  }
}
```

### Common Errors [#common-errors-2]

| Error code       | Message                                                                                                        |
| ---------------- | -------------------------------------------------------------------------------------------------------------- |
| `CONSULTING-001` | Consulting service not found                                                                                   |
| `CONSULTING-004` | Cannot delete a consulting service that still has undiscarded, non-canceled future meetings. Cancel them first |

***

## Bulk Create Consulting Meetings [#bulk-create-consulting-meetings]

The `bulkCreateConsultingMeetings` mutation creates multiple time slots under a single consulting service in one request. `results[i]` always corresponds to `inputs[i]`.

> **⚠️ `atomic: true` + `hostingType: zoom` is rejected.** Zoom rows provision against the Zoom API per-row, which makes a clean rollback impossible. The mutation top-level-fails with `MEETING-010` if you mix them. Leave `atomic: false` (the default) whenever any row is Zoom-hosted — even an agent that defaults to `atomic: true` "for safety" will trip this on the first Zoom batch.

### Time and Timezone [#time-and-timezone]

`startedAt` and `endedAt` are **Unix timestamps** (seconds since epoch). Convert from local datetimes using the parent service's `effectiveTimezone` field (IANA name, e.g. `Asia/Taipei`) before sending.

### Input Parameters [#input-parameters-3]

| Field       | Type                                  | Description                                                                             |
| ----------- | ------------------------------------- | --------------------------------------------------------------------------------------- |
| `serviceId` | `String!`                             | Parent consulting service ID                                                            |
| `inputs`    | `[AdminConsultingMeetingBulkInput!]!` | Time-slot rows                                                                          |
| `atomic`    | `Boolean`                             | When `true`, all rows roll back if any row fails. Default `false` (per-row independent) |

### AdminConsultingMeetingBulkInput Fields [#adminconsultingmeetingbulkinput-fields]

> **Meeting host model — three independent concepts.** A consulting meeting carries three different "host-ish" identifiers, and they are not interchangeable:
>
> * `lecturerId` — the public-facing **Lecturer profile** (slug, URL routing, slot-overlap detection). Managed in the school admin's Lecturers section. List via the [`lecturers` query](/docs/api/queries/courses).
> * `hostUserId` — the **user (school owner or teaching assistant) who actually runs the session**. Surfaced to enrolled students. This is the "host" the school admin UI exposes on the meeting edit form. &#x2A;*List valid hosts up-front via [`meetingHosts`](/docs/api/queries/consulting#meetinghosts) to avoid `MEETING-012`.**
> * `hostEmail` — the **Zoom license email** used to provision the Zoom room when `hostingType: zoom`. A Zoom seat, not a person record. &#x2A;*List valid seats up-front via [`zoomHosts`](/docs/api/queries/consulting#zoomhosts) to avoid `MEETING-011`.**
>
> For a Zoom meeting you typically set all three: `lecturerId` (whose profile owns the slot), `hostUserId` (who clicks "join" on the day), and `hostEmail` (which Zoom seat hosts the room). They can intentionally be three different people/seats.

| Field                 | Type                 | Required | Description                                                                                                                                                                                                 |
| --------------------- | -------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `startedAt`           | `Int!`               | Yes      | Slot start, Unix timestamp                                                                                                                                                                                  |
| `endedAt`             | `Int!`               | Yes      | Slot end, Unix timestamp                                                                                                                                                                                    |
| `lecturerId`          | `String`             | No       | Lecturer **profile** (slug, URL routing, slot-overlap detection). NOT the person who hosts the session — use `hostUserId` for that. Inherits the service-level lecturer when omitted                        |
| `hostUserId`          | `String`             | No       | The user who actually hosts the meeting. Must be the school owner's user id OR a user with the `teaching_assistant` role in this school; otherwise `MEETING-012`. Defaults to the school owner when omitted |
| `hostingType`         | `MeetingHostingType` | No       | `zoom`, `live_session`, or `custom`                                                                                                                                                                         |
| `hostingId`           | `String`             | No       | External hosting platform meeting ID (e.g. Zoom meeting ID)                                                                                                                                                 |
| `hostEmail`           | `String`             | No       | Zoom license email for `hostingType: zoom` — see **Zoom host resolution** below. Independent of `hostUserId`                                                                                                |
| `joinUrl`             | `String`             | No       | Required when `hostingType: custom`. Ignored for `zoom`, which stores the join URL Zoom returns                                                                                                             |
| `maxAttendeeCapacity` | `Int`                | No       | `0` or `null` means unlimited                                                                                                                                                                               |
| `price`               | `Float`              | No       | Per-slot price; falls back to service-level pricing if omitted                                                                                                                                              |
| `title`               | `String`             | No       | Falls back to the service name when omitted                                                                                                                                                                 |
| `description`         | `String`             | No       |                                                                                                                                                                                                             |

### Zoom host resolution [#zoom-host-resolution]

When `hostingType: zoom`:

1. If `hostEmail` is provided, it must match one of the school's configured Zoom integration licenses (Settings → Integrations → Zoom). Prefer listing them via [`zoomHosts`](/docs/api/queries/consulting#zoomhosts) up-front.
2. If omitted and the school has exactly one Zoom license, that license is used automatically.
3. Otherwise, the row fails with `MEETING-011`. The error string carries a machine-parseable `valid_options=email1,email2` suffix so agents can recover without parsing prose.

**On successful return for Zoom rows**: the mutation provisions the Zoom meeting synchronously before responding, so `meeting.hostingId` (Zoom meeting ID) and `meeting.joinUrl` are populated by the time you read them in `results[i].meeting`. No follow-up query needed.

### Return Type [#return-type-1]

```graphql
type AdminBulkCreateConsultingMeetingsPayload {
  results: [AdminConsultingMeetingBulkResult!]
  allSucceeded: Boolean
  errors: [String!]
}

type AdminConsultingMeetingBulkResult {
  meeting: AdminConsultingMeeting   # null when the row failed
  errors: [String!]                  # null when the row succeeded
}
```

### Example [#example-3]

```graphql
mutation BulkCreateConsultingMeetings {
  bulkCreateConsultingMeetings(
    serviceId: "35a72dba-c3cc-4a06-b7eb-d784d010386e"
    atomic: false
    inputs: [
      {
        startedAt: 1748390400
        endedAt: 1748392200
        hostingType: live_session
        maxAttendeeCapacity: 1
      }
      {
        startedAt: 1748394000
        endedAt: 1748395800
        hostingType: zoom
        hostEmail: "host@example.com"          # Zoom license seat
        hostUserId: "9b8a7c65-1234-5678-90ab-cdef01234567"  # the human who runs it (owner or TA)
        maxAttendeeCapacity: 1
      }
    ]
  ) {
    allSucceeded
    results {
      meeting {
        id
        title
        state
        startedAt
        endedAt
        hostingType
        joinUrl
      }
      errors
    }
    errors
  }
}
```

### Common Errors (per row or top-level) [#common-errors-per-row-or-top-level]

| Error code       | Message                                                                                                                                                                                                                             |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CONSULTING-001` | Consulting service not found (top-level — bad `serviceId`)                                                                                                                                                                          |
| `MEETING-008`    | Custom hosting type requires `joinUrl`                                                                                                                                                                                              |
| `MEETING-009`    | School has no active Zoom integration; configure Zoom under integrations first                                                                                                                                                      |
| `MEETING-010`    | Zoom hosting type cannot be combined with `atomic: true`; use `atomic: false` to allow per-row Zoom provisioning                                                                                                                    |
| `MEETING-011`    | `hostEmail` is required or invalid — error carries `valid_options=email1,email2` suffix (capped at 20 entries; call [`zoomHosts`](/docs/api/queries/consulting#zoomhosts) for the full list)                                        |
| `MEETING-012`    | `hostUserId` must be the school owner or a teaching assistant — error carries `valid_options=user_id_1,user_id_2` suffix (capped at 20 entries; call [`meetingHosts`](/docs/api/queries/consulting#meetinghosts) for the full list) |

***

## Update a Consulting Meeting [#update-a-consulting-meeting]

The `updateConsultingMeeting` mutation applies a partial update. Time fields (`startedAt`, `endedAt`) are blocked when the meeting has enrolled students (see `MEETING-003`); remove students first, or cancel and recreate the slot, to reschedule. (To move an individual student to a different slot instead, see [rescheduleStudentConsultingMeeting](#reschedule-a-students-consulting-meeting).) &#x2A;*Other fields — including `hostUserId`, `lecturerId`, `hostingType`, `title`, `maxAttendeeCapacity`, etc. — are NOT blocked by `MEETING-003`** and can be changed on a `scheduled` meeting (e.g. to reassign hosts when staff turn over).

> **Explicit-null semantics**: explicit `null` is treated as **no change**, not "clear". Sending `{ lecturerId: null }` keeps the existing lecturer. There is currently no API path to clear an already-assigned lecturer.

### Input Parameters [#input-parameters-4]

| Field   | Type                                 | Description           |
| ------- | ------------------------------------ | --------------------- |
| `id`    | `String!`                            | Meeting ID            |
| `input` | `AdminConsultingMeetingUpdateInput!` | Partial-update fields |

### AdminConsultingMeetingUpdateInput Fields [#adminconsultingmeetingupdateinput-fields]

> The three independent host concepts (`lecturerId` / `hostUserId` / `hostEmail`) are explained in the [bulk-create section above](#adminconsultingmeetingbulkinput-fields).

| Field                 | Type                 | Description                                                                                          |
| --------------------- | -------------------- | ---------------------------------------------------------------------------------------------------- |
| `startedAt`           | `Int`                | Slot start, Unix timestamp                                                                           |
| `endedAt`             | `Int`                | Slot end, Unix timestamp                                                                             |
| `lecturerId`          | `String`             | Reassign Lecturer profile (not the actual host — see `hostUserId`)                                   |
| `hostUserId`          | `String`             | Reassign the user who runs the meeting (school owner or teaching assistant); `MEETING-012` otherwise |
| `hostingType`         | `MeetingHostingType` | `zoom`, `live_session`, or `custom`                                                                  |
| `hostingId`           | `String`             |                                                                                                      |
| `hostEmail`           | `String`             | Zoom license email — same resolution rules as bulk-create                                            |
| `joinUrl`             | `String`             |                                                                                                      |
| `maxAttendeeCapacity` | `Int`                |                                                                                                      |
| `price`               | `Float`              |                                                                                                      |
| `title`               | `String`             |                                                                                                      |
| `description`         | `String`             |                                                                                                      |

### Return Type [#return-type-2]

```graphql
type AdminUpdateConsultingMeetingPayload {
  meeting: AdminConsultingMeeting
  errors: [String!]
}
```

### Example [#example-4]

```graphql
mutation UpdateConsultingMeeting {
  updateConsultingMeeting(
    id: "0186b768-c0c0-4d75-8fb7-7fee0b3ee9c1"
    input: {
      title: "Rescheduled coaching session"
      maxAttendeeCapacity: 2
    }
  ) {
    meeting {
      id
      title
      maxAttendeeCapacity
      state
    }
    errors
  }
}
```

### Common Errors [#common-errors-3]

| Error code    | Message                                                                                                                                                                                                                             |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `MEETING-001` | Consulting meeting not found                                                                                                                                                                                                        |
| `MEETING-003` | Cannot reschedule meeting with enrolled students                                                                                                                                                                                    |
| `MEETING-007` | Meeting is already canceled                                                                                                                                                                                                         |
| `MEETING-008` | Custom hosting type requires `joinUrl`                                                                                                                                                                                              |
| `MEETING-009` | School has no active Zoom integration                                                                                                                                                                                               |
| `MEETING-011` | `hostEmail` is required or invalid — error carries `valid_options=email1,email2` suffix (capped at 20 entries; call [`zoomHosts`](/docs/api/queries/consulting#zoomhosts) for the full list)                                        |
| `MEETING-012` | `hostUserId` must be the school owner or a teaching assistant — error carries `valid_options=user_id_1,user_id_2` suffix (capped at 20 entries; call [`meetingHosts`](/docs/api/queries/consulting#meetinghosts) for the full list) |

***

## Cancel a Consulting Meeting [#cancel-a-consulting-meeting]

The `cancelConsultingMeeting` mutation cancels a single meeting via the underlying AASM state machine. Works from both `available` and `scheduled` states. For Zoom-hosted meetings, the remote Zoom meeting is also deleted; the local row keeps its hosting metadata for history.

### Input Parameters [#input-parameters-5]

| Field | Type      | Description |
| ----- | --------- | ----------- |
| `id`  | `String!` | Meeting ID  |

### Example [#example-5]

```graphql
mutation CancelConsultingMeeting {
  cancelConsultingMeeting(id: "0186b768-c0c0-4d75-8fb7-7fee0b3ee9c1") {
    meeting {
      id
      state
    }
    errors
  }
}
```

### Common Errors [#common-errors-4]

| Error code    | Message                      |
| ------------- | ---------------------------- |
| `MEETING-001` | Consulting meeting not found |
| `MEETING-007` | Meeting is already canceled  |

***

## Bulk Cancel Consulting Meetings [#bulk-cancel-consulting-meetings]

The `bulkCancelConsultingMeetings` mutation cancels multiple meetings in one round trip. `results[i]` always corresponds to `ids[i]`. Already-canceled meetings produce `MEETING-007` in their per-row errors. For Zoom-hosted meetings, the remote Zoom meeting is also deleted (same behavior as the single `cancelConsultingMeeting`); the local rows keep their hosting metadata for history.

### Input Parameters [#input-parameters-6]

| Field    | Type         | Description                                                       |
| -------- | ------------ | ----------------------------------------------------------------- |
| `ids`    | `[String!]!` | Meeting IDs; order preserved in results                           |
| `atomic` | `Boolean`    | When `true`, all rows roll back if any row fails. Default `false` |

### Example [#example-6]

```graphql
mutation BulkCancelConsultingMeetings {
  bulkCancelConsultingMeetings(
    ids: ["meeting-id-a", "meeting-id-b"]
    atomic: false
  ) {
    allSucceeded
    results {
      meeting {
        id
        state
      }
      errors
    }
  }
}
```

### Common Errors [#common-errors-5]

Same per-row codes as the single cancel: `MEETING-001`, `MEETING-007`. Top-level `MEETING-010` if Zoom-hosted meetings are present and `atomic: true`.

***

## Enroll a Student to a Consulting Meeting [#enroll-a-student-to-a-consulting-meeting]

The `enrollStudentToConsultingMeeting` mutation adds a student to a meeting. Provide either `userId` or `email` — one is required. Re-enrolling an already-enrolled student is a **no-op** and returns the existing meeting. An `available` meeting auto-transitions to `scheduled` on the first enrollment. If the student is being moved from another slot, use [rescheduleStudentConsultingMeeting](#reschedule-a-students-consulting-meeting) instead of remove + enroll.

> **Scope**: this mutation requires `students:write` (or `members:write`), **not** `courses:write`.

### Input Parameters [#input-parameters-7]

| Field       | Type      | Required | Description                                                |
| ----------- | --------- | -------- | ---------------------------------------------------------- |
| `meetingId` | `String!` | Yes      | Target meeting ID                                          |
| `userId`    | `String`  | No\*     | Existing student ID. Mutually exclusive with `email`       |
| `email`     | `String`  | No\*     | Student email; creates a school-scoped student if no match |
| `name`      | `String`  | No       | Required when creating a new user by email                 |

\*Either `userId` or `email` must be provided.

### Example [#example-7]

```graphql
mutation EnrollStudent {
  enrollStudentToConsultingMeeting(
    meetingId: "0186b768-c0c0-4d75-8fb7-7fee0b3ee9c1"
    email: "student@example.com"
    name: "John Doe"
  ) {
    meeting {
      id
      state
      attendeeCount
    }
    user {
      id
      email
      name
    }
    errors
  }
}
```

### Common Errors [#common-errors-6]

| Error code       | Message                                           |
| ---------------- | ------------------------------------------------- |
| `MEETING-001`    | Consulting meeting not found                      |
| `MEETING-004`    | Meeting has reached its maximum attendee capacity |
| `MEETING-007`    | Meeting is already canceled                       |
| `ENROLLMENT-001` | Either `userId` or `email` must be provided       |
| `ENROLLMENT-002` | Student not found                                 |
| `ENROLLMENT-005` | Failed to create student                          |
| `ENROLLMENT-006` | Invalid email                                     |
| `ENROLLMENT-007` | Name is required when creating a new user         |

***

## Remove a Student from a Consulting Meeting [#remove-a-student-from-a-consulting-meeting]

The `removeStudentFromConsultingMeeting` mutation removes a student's enrollment. If this leaves a `scheduled` meeting with zero attendees, the state auto-reverts to `available` so the slot is discoverable again via state filters. Refuses to operate on a canceled meeting (`MEETING-007`). To move a student to a different slot, do not pair this with an enroll call — use [rescheduleStudentConsultingMeeting](#reschedule-a-students-consulting-meeting), which is atomic.

> **Scope**: this mutation requires `students:write` (or `members:write`).

### Input Parameters [#input-parameters-8]

| Field       | Type      | Description       |
| ----------- | --------- | ----------------- |
| `meetingId` | `String!` | Target meeting ID |
| `userId`    | `String!` | Student to remove |

### Example [#example-8]

```graphql
mutation RemoveStudent {
  removeStudentFromConsultingMeeting(
    meetingId: "0186b768-c0c0-4d75-8fb7-7fee0b3ee9c1"
    userId: "387b0c87-0f85-44cc-833e-7306c1b5d3e6"
  ) {
    meeting {
      id
      state
      attendeeCount
    }
    errors
  }
}
```

### Common Errors [#common-errors-7]

| Error code    | Message                                 |
| ------------- | --------------------------------------- |
| `MEETING-001` | Consulting meeting not found            |
| `MEETING-006` | Student is not enrolled in this meeting |
| `MEETING-007` | Meeting is already canceled             |

***

## Reschedule a Student's Consulting Meeting [#reschedule-a-students-consulting-meeting]

The `rescheduleStudentConsultingMeeting` mutation atomically moves a student from one meeting to another in a single transaction.

> **Why not remove + enroll?** Calling `removeStudentFromConsultingMeeting` followed by `enrollStudentToConsultingMeeting` is two independent, non-atomic calls — if the enroll leg fails (e.g. the target filled up between your two calls), the student ends up in **neither** slot. `rescheduleStudentConsultingMeeting` does both steps inside one DB transaction: if the target is at capacity, the whole operation rolls back and the student remains enrolled in the source meeting.

> **Ended-meeting guard**: refuses to reschedule out of a meeting that has already ended (`MEETING-020`). Destroying the source enrollment cascades to destroy any rating already recorded for that session, so once a meeting has happened its attendees are locked in place. Moving a student *into* a meeting that has already ended is allowed (same behavior as `enrollStudentToConsultingMeeting`) — useful for back-filling attendance.

> **Idempotent / retry-safe**: if the student is already enrolled in the target meeting (e.g. a retried call after a network timeout), the create step is skipped — the student is still removed from the source if present — and the mutation returns success.

> **Cross-service moves are allowed**: `fromMeetingId` and `toMeetingId` can belong to different consulting services, as long as both resolve under this school.

> **Scope**: this mutation requires `students:write` (or `members:write`), the same scope as the other enrollment mutations.

### Input Parameters [#input-parameters-9]

| Field           | Type      | Required | Description       |
| --------------- | --------- | -------- | ----------------- |
| `userId`        | `String!` | Yes      | Student to move   |
| `fromMeetingId` | `String!` | Yes      | Source meeting ID |
| `toMeetingId`   | `String!` | Yes      | Target meeting ID |

### Return Type [#return-type-3]

```graphql
type AdminRescheduleStudentConsultingMeetingPayload {
  fromMeeting: AdminConsultingMeeting
  toMeeting: AdminConsultingMeeting
  errors: [String!]
}
```

### Example [#example-9]

```graphql
mutation RescheduleStudent {
  rescheduleStudentConsultingMeeting(
    userId: "387b0c87-0f85-44cc-833e-7306c1b5d3e6"
    fromMeetingId: "0186b768-c0c0-4d75-8fb7-7fee0b3ee9c1"
    toMeetingId: "6f6f8b2f-6e0f-4a3f-9a3d-5f4c9c1b2e3a"
  ) {
    fromMeeting {
      id
      state
      attendeeCount
    }
    toMeeting {
      id
      state
      attendeeCount
    }
    errors
  }
}
```

### Sample Response [#sample-response-1]

```json
{
  "data": {
    "rescheduleStudentConsultingMeeting": {
      "fromMeeting": {
        "id": "0186b768-c0c0-4d75-8fb7-7fee0b3ee9c1",
        "state": "available",
        "attendeeCount": 0
      },
      "toMeeting": {
        "id": "6f6f8b2f-6e0f-4a3f-9a3d-5f4c9c1b2e3a",
        "state": "scheduled",
        "attendeeCount": 1
      },
      "errors": null
    }
  }
}
```

### Common Errors [#common-errors-8]

| Error code    | Message                                                                                                                                     |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `MEETING-001` | Consulting meeting not found (either `fromMeetingId` or `toMeetingId`)                                                                      |
| `MEETING-004` | Target meeting has reached its maximum attendee capacity — the whole operation rolls back, the student stays enrolled in the source meeting |
| `MEETING-006` | Student is not enrolled in the source meeting (and not already in the target)                                                               |
| `MEETING-007` | Either meeting is already canceled                                                                                                          |
| `MEETING-019` | `fromMeetingId` and `toMeetingId` are identical                                                                                             |
| `MEETING-020` | Cannot reschedule from a meeting that has already ended                                                                                     |


---

# Course Mutations (https://docs.loopwise.com/api/mutations/courses)



The course mutations allow you to create, update, and delete courses within your Loopwise school, as well as manage student enrollments. These operations enable you to programmatically manage your course catalog and student access.

**Course entity mutations:**

* `createCourse` — Creates a new course
* `updateCourse` — Updates an existing course
* `deleteCourse` — Deletes a course

**Enrollment mutations:**

* `enrollStudentToCourse` — Enrolls a student to a course or updates an existing enrollment
* `removeStudentFromCourse` — Removes a student's enrollment from a course
* `expireStudentCourseAccess` — Marks a student's course access as expired
* `extendStudentCourseAccess` — Extends a student's access to a course

All course mutations return an `errors` field in the response that will contain any validation or processing errors that occurred during the operation.

***

## Create a Course [#create-a-course]

The `createCourse` mutation allows you to create a new course in your school with the specified properties.

### Input Parameters [#input-parameters]

| Field   | Type                | Description                                     |
| ------- | ------------------- | ----------------------------------------------- |
| `input` | `AdminCourseInput!` | Input object containing course creation details |

### AdminCourseInput Fields [#admincourseinput-fields]

| Field         | Type        | Required | Description                                                                                                      |
| ------------- | ----------- | -------- | ---------------------------------------------------------------------------------------------------------------- |
| `name`        | `String!`   | Yes      | Course name                                                                                                      |
| `slug`        | `String!`   | Yes      | URL slug for the course. Must contain only lowercase letters, numbers, and hyphens                               |
| `courseType`  | `String!`   | Yes      | Type of the course (paid, public\_access, free\_redeem, pre\_order)                                              |
| `description` | `String`    | No       | Course description                                                                                               |
| `categoryIds` | `[String!]` | No       | IDs of this school's course categories to associate with this course. Any other ID is rejected with `COURSE-008` |
| `tagList`     | `[String!]` | No       | Tags to associate with this course                                                                               |

### Return Type [#return-type]

```graphql
type AdminCourseCreatePayload {
  # The created course object, null if operation failed
  course: AdminCourse

  # Array of error messages, if any occurred during the operation
  errors: [String!]
}
```

### Example [#example]

```graphql
mutation CreateCourse {
  createCourse(input: {
    name: "GraphQL Fundamentals"
    slug: "graphql-fundamentals"
    courseType: "paid"
    description: "Learn the basics of GraphQL API development"
    categoryIds: ["cat_123"]
    tagList: ["graphql", "api", "development"]
  }) {
    course {
      id
      name
      slug
      courseType
      description
    }
    errors
  }
}
```

### Sample Response [#sample-response]

```json
{
  "data": {
    "createCourse": {
      "course": {
        "id": "course_12345",
        "name": "GraphQL Fundamentals",
        "slug": "graphql-fundamentals",
        "courseType": "paid",
        "description": "Learn the basics of GraphQL API development"
      },
      "errors": []
    }
  }
}
```

### Common Errors [#common-errors]

| Error                           | Description                                                                   |
| ------------------------------- | ----------------------------------------------------------------------------- |
| `Name cannot be empty`          | The course name is required                                                   |
| `Slug already exists`           | The provided slug is already in use                                           |
| `Invalid course type`           | The courseType must be one of: paid, public\_access, free\_redeem, pre\_order |
| `COURSE-008 Category not found` | One or more category IDs are not this school's course categories              |

***

## Update a Course [#update-a-course]

The `updateCourse` mutation allows you to update an existing course with new properties in your Loopwise school.

### Input Parameters [#input-parameters-1]

| Field   | Type                | Description                                   |
| ------- | ------------------- | --------------------------------------------- |
| `id`    | `String!`           | ID of the course to update                    |
| `input` | `AdminCourseInput!` | Input object containing course update details |

### AdminCourseInput Fields [#admincourseinput-fields-1]

| Field         | Type        | Required | Description                                                                                                                                                                                                         |
| ------------- | ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`        | `String!`   | Yes      | Course name                                                                                                                                                                                                         |
| `slug`        | `String!`   | Yes      | URL slug for the course. Must contain only lowercase letters, numbers, and hyphens                                                                                                                                  |
| `courseType`  | `String!`   | Yes      | Type of the course (paid, public\_access, free\_redeem, pre\_order)                                                                                                                                                 |
| `description` | `String`    | No       | Course description                                                                                                                                                                                                  |
| `categoryIds` | `[String!]` | No       | IDs of this school's course categories to associate with this course. Replaces the current selection; omitting it or passing `null` leaves it unchanged, `[]` clears it. Any other ID is rejected with `COURSE-008` |
| `tagList`     | `[String!]` | No       | Tags to associate with this course                                                                                                                                                                                  |

### Return Type [#return-type-1]

```graphql
type AdminCourseUpdatePayload {
  # The updated course object, null if operation failed
  course: AdminCourse

  # Array of error messages, if any occurred during the operation
  errors: [String!]
}
```

### Example [#example-1]

```graphql
mutation UpdateCourse {
  updateCourse(
    id: "course_12345"
    input: {
      name: "Advanced GraphQL Fundamentals"
      slug: "advanced-graphql-fundamentals"
      courseType: "paid"
      description: "Learn advanced GraphQL concepts and patterns"
      categoryIds: ["cat_123", "cat_456"]
      tagList: ["graphql", "advanced", "api"]
    }
  ) {
    course {
      id
      name
      slug
      courseType
      description
      categories {
        id
        name
      }
      tags
    }
    errors
  }
}
```

### Sample Response [#sample-response-1]

```json
{
  "data": {
    "updateCourse": {
      "course": {
        "id": "course_12345",
        "name": "Advanced GraphQL Fundamentals",
        "slug": "advanced-graphql-fundamentals",
        "courseType": "paid",
        "description": "Learn advanced GraphQL concepts and patterns",
        "categories": [
          {
            "id": "cat_123",
            "name": "Programming"
          },
          {
            "id": "cat_456",
            "name": "Web Development"
          }
        ],
        "tags": ["graphql", "advanced", "api"]
      },
      "errors": []
    }
  }
}
```

### Common Errors [#common-errors-1]

| Error                           | Description                                                                   |
| ------------------------------- | ----------------------------------------------------------------------------- |
| `Course not found`              | The specified course ID does not exist                                        |
| `Name cannot be empty`          | The course name is required                                                   |
| `Slug already exists`           | The provided slug is already in use by another course                         |
| `Invalid course type`           | The courseType must be one of: paid, public\_access, free\_redeem, pre\_order |
| `COURSE-008 Category not found` | One or more category IDs are not this school's course categories              |

***

## Delete a Course [#delete-a-course]

The `deleteCourse` mutation allows you to delete a course if no active enrollments exist.

> **Note:** This mutation is still under development and will be fully documented when available.

***

## Enroll a Student to a Course [#enroll-a-student-to-a-course]

The `enrollStudentToCourse` mutation allows you to enroll a student to a specified course, or update existing enrollment details. For paid or pre-order courses, this mutation automatically creates payment records using the specified curriculum plan's pricing information.

### Input Parameters [#input-parameters-2]

| Field      | Type      | Required | Description                                                                                                                                                                                                                                                                                                                                             |
| ---------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `userId`   | `String`  | No\*     | ID of the student (User) to enroll                                                                                                                                                                                                                                                                                                                      |
| `email`    | `String`  | No\*     | Email of the student. If user doesn't exist, a placeholder user will be created                                                                                                                                                                                                                                                                         |
| `name`     | `String`  | No       | Name of the student. Required when creating a new user                                                                                                                                                                                                                                                                                                  |
| `courseId` | `String!` | Yes      | ID of the course to enroll the student into                                                                                                                                                                                                                                                                                                             |
| `planId`   | `String`  | No       | ID of the curriculum plan to apply to this enrollment. If not provided, will use the course's first plan (ordered by creation date). For paid/pre-order courses, the plan's `amount` and `currency` are used to create the payment record                                                                                                               |
| `endedAt`  | `Int`     | No       | Optional expiration date for the enrollment (Unix Timestamp)                                                                                                                                                                                                                                                                                            |
| `notify`   | `Boolean` | No       | Whether to send the notification email to the student for this enrollment. Defaults to `true`. Set to `false` for a silent import (e.g. a bulk migration from your own system). Actual delivery also depends on the school's notification settings, which are not visible or overridable via the API — check `notified` in the response for the outcome |

\*Either `userId` or `email` must be provided.

### Return Type [#return-type-2]

```graphql
type AdminEnrollStudentToCoursePayload {
  # The created or updated enrollment
  enrollment: StudentCourseShip
  # Whether a notification email was enqueued by this call
  notified: Boolean!
}
```

### StudentCourseShip Object [#studentcourseship-object]

| Field            | Type           | Description                                                       |
| ---------------- | -------------- | ----------------------------------------------------------------- |
| `id`             | `String!`      | ID of the enrollment                                              |
| `completionRate` | `Float`        | The completion rate of the enrolled course which student achieved |
| `course`         | `AdminCourse!` | Information of the enrolled course                                |
| `user`           | `AdminUser!`   | User information of the enrolled course                           |
| `createdAt`      | `Int!`         | Created date of the enrollment (Unix Timestamp)                   |
| `updatedAt`      | `Int!`         | Last updated date of the enrollment (Unix Timestamp)              |
| `endedAt`        | `Int`          | Expiration date for the enrollment (Unix Timestamp)               |

### Example — Enroll a New Student [#example--enroll-a-new-student]

```graphql
mutation EnrollNewStudent {
  enrollStudentToCourse(
    courseId: "ab6ee332-614d-475d-93b5-abc5ebb1fc84"
    email: "student@example.com"
    name: "John Doe"   # Required when creating a new user
  ) {
    enrollment {
      id
      completionRate
      createdAt
      updatedAt
      endedAt
      course {
        id
        name
        slug
      }
      user {
        id
        name
        email
      }
    }
  }
}
```

### Example — Enroll Student to a Paid Course with Specific Plan [#example--enroll-student-to-a-paid-course-with-specific-plan]

```graphql
mutation EnrollStudentToPaidCourse {
  enrollStudentToCourse(
    courseId: "paid-course-123"
    email: "premium.student@example.com"
    name: "Premium Student"
    planId: "premium-plan-456"
    endedAt: 1735689600
  ) {
    enrollment {
      id
      completionRate
      endedAt
      course {
        id
        name
      }
      user {
        id
        name
        email
      }
    }
  }
}
```

> **Note:** For paid or pre-order courses, this mutation creates a payment record with `amount` and `currency` from the specified plan, `status` set to `manual_enrolled`, and a lineitem linking to the curriculum plan. For free or redeem courses, no payment record is created. If the student is already enrolled in a paid/pre-order course, the mutation returns the existing enrollment without creating a new payment.

### Sample Response [#sample-response-2]

```json
{
  "data": {
    "enrollStudentToCourse": {
      "enrollment": {
        "id": "619ad939-8591-40ad-9364-cf3825a9bf70",
        "completionRate": 0.0,
        "createdAt": 1672531200,
        "updatedAt": 1672531200,
        "endedAt": null,
        "course": {
          "id": "ab6ee332-614d-475d-93b5-abc5ebb1fc84",
          "name": "Introduction to GraphQL",
          "slug": "intro-graphql"
        },
        "user": {
          "id": "387b0c87-0f85-44cc-833e-7306c1b5d3e6",
          "name": "John Doe",
          "email": "student@example.com"
        }
      }
    }
  }
}
```

### Common Errors [#common-errors-2]

| Error                                            | Description                                     |
| ------------------------------------------------ | ----------------------------------------------- |
| `Either user_id or email must be provided`       | At least one identifier must be provided        |
| `Name is required when creating a new user`      | Required when creating a new user via email     |
| `Course not found`                               | The specified course ID does not exist          |
| `User not found`                                 | The specified user ID does not exist            |
| `Public access courses don't require enrollment` | Public access courses don't require enrollment  |
| `No valid plan found for this course`            | The specified planId is invalid for this course |

***

## Remove a Student from a Course [#remove-a-student-from-a-course]

The `removeStudentFromCourse` mutation allows you to completely remove a student's enrollment from a specified course. This action revokes the student's access to course content and removes all enrollment records.

### Input Parameters [#input-parameters-3]

| Field      | Type      | Required | Description                                        |
| ---------- | --------- | -------- | -------------------------------------------------- |
| `userId`   | `String!` | Yes      | ID of the student (User) to remove from the course |
| `courseId` | `String!` | Yes      | ID of the course to remove the student from        |

### Return Type [#return-type-3]

```graphql
type AdminRemoveStudentFromCoursePayload {
  # Additional information about the operation result
  message: String

  # Indicates whether the removal was successful
  success: Boolean!
}
```

### Example [#example-2]

```graphql
mutation RemoveStudentFromCourse {
  removeStudentFromCourse(
    userId: "a1b2c3d4-5678-90ef-ghij-klmnopqrstuv"
    courseId: "ab6ee332-614d-475d-93b5-abc5ebb1fc84"
  ) {
    success
    message
  }
}
```

### Sample Response [#sample-response-3]

```json
{
  "data": {
    "removeStudentFromCourse": {
      "success": true,
      "message": "Student successfully removed from the course"
    }
  }
}
```

### Common Errors [#common-errors-3]

| Error                                    | Description                                         |
| ---------------------------------------- | --------------------------------------------------- |
| `Student is not enrolled in this course` | The student is not enrolled in the specified course |
| `Course not found`                       | The specified course ID does not exist              |
| `User not found`                         | The specified user ID does not exist                |

***

## Extend Student Course Access [#extend-student-course-access]

The `extendStudentCourseAccess` mutation allows you to extend a student's access to a course by updating the ended\_at date. This is useful when you want to grant additional time for course completion.

### Input Parameters [#input-parameters-4]

| Field           | Type      | Required | Description                                                                                                           |
| --------------- | --------- | -------- | --------------------------------------------------------------------------------------------------------------------- |
| `userId`        | `String!` | Yes      | ID of the student (User) whose access should be extended                                                              |
| `courseId`      | `String!` | Yes      | ID of the course to extend access for                                                                                 |
| `extensionDays` | `Int`     | No\*     | Number of days to extend the access from the current ended\_at date                                                   |
| `newEndedAt`    | `Int`     | No\*     | New expiration date as Unix Timestamp (seconds since epoch). Takes precedence over extensionDays if both are provided |
| `indefinite`    | `Boolean` | No       | If true, removes the access end date, granting unlimited access. Takes precedence over all other time parameters      |

\*At least one of `extensionDays`, `newEndedAt`, or `indefinite` must be provided.

### Return Type [#return-type-4]

```graphql
type AdminExtendStudentCourseAccessPayload {
  # The updated enrollment with extended access
  enrollment: StudentCourseShip
}
```

### StudentCourseShip Object [#studentcourseship-object-1]

| Field            | Type           | Description                                                                               |
| ---------------- | -------------- | ----------------------------------------------------------------------------------------- |
| `id`             | `String!`      | ID of the enrollment                                                                      |
| `completionRate` | `Float`        | The completion rate of the enrolled course which student achieved                         |
| `course`         | `AdminCourse!` | Information of the enrolled course                                                        |
| `user`           | `AdminUser!`   | User information of the enrolled course                                                   |
| `createdAt`      | `Int!`         | Created date of the enrollment (Unix Timestamp)                                           |
| `updatedAt`      | `Int!`         | Last updated date of the enrollment (Unix Timestamp)                                      |
| `endedAt`        | `Int`          | Expiration date for the enrollment (Unix Timestamp). Null if indefinite access is granted |

### Example — Extend by Days [#example--extend-by-days]

```graphql
mutation ExtendStudentAccess {
  extendStudentCourseAccess(
    userId: "387b0c87-0f85-44cc-833e-7306c1b5d3e6"
    courseId: "9a1216f7-36de-4c50-8094-2ebfb7d3c383"
    extensionDays: 30
  ) {
    enrollment {
      id
      completionRate
      createdAt
      updatedAt
      endedAt
      course {
        id
        name
        slug
      }
      user {
        id
        name
        email
      }
    }
  }
}
```

### Example — Set Specific End Date [#example--set-specific-end-date]

```graphql
mutation ExtendStudentAccessWithDate {
  extendStudentCourseAccess(
    userId: "387b0c87-0f85-44cc-833e-7306c1b5d3e6"
    courseId: "9a1216f7-36de-4c50-8094-2ebfb7d3c383"
    newEndedAt: 1735689600
  ) {
    enrollment {
      id
      endedAt
      course {
        id
        name
      }
      user {
        id
        name
      }
    }
  }
}
```

### Example — Grant Indefinite Access [#example--grant-indefinite-access]

```graphql
mutation GrantIndefiniteAccess {
  extendStudentCourseAccess(
    userId: "387b0c87-0f85-44cc-833e-7306c1b5d3e6"
    courseId: "9a1216f7-36de-4c50-8094-2ebfb7d3c383"
    indefinite: true
  ) {
    enrollment {
      id
      endedAt
      course {
        id
        name
      }
      user {
        id
        name
      }
    }
  }
}
```

### Sample Response [#sample-response-4]

```json
{
  "data": {
    "extendStudentCourseAccess": {
      "enrollment": {
        "id": "619ad939-8591-40ad-9364-cf3825a9bf70",
        "completionRate": 0.5,
        "createdAt": 1672531200,
        "updatedAt": 1750076336,
        "endedAt": 1750076336,
        "course": {
          "id": "9a1216f7-36de-4c50-8094-2ebfb7d3c383",
          "name": "Introduction to GraphQL",
          "slug": "intro-graphql"
        },
        "user": {
          "id": "387b0c87-0f85-44cc-833e-7306c1b5d3e6",
          "name": "Student",
          "email": "student@example.com"
        }
      }
    }
  }
}
```

### Common Errors [#common-errors-4]

| Error                                                                             | Description                                                    |
| --------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| `Student is not enrolled in this course`                                          | The student is not enrolled in the specified course            |
| `Current enrollment has no end date`                                              | Cannot extend an enrollment that already has indefinite access |
| `The new end date is too far in the past. Please provide a timestamp after 2020.` | The provided newEndedAt date is invalid                        |

***

## Expire Student Course Access [#expire-student-course-access]

The `expireStudentCourseAccess` mutation allows you to mark a student's course access as expired while retaining their course data. This is useful when you want to temporarily revoke a student's access without removing their progress and enrollment records.

### Input Parameters [#input-parameters-5]

| Field           | Type      | Required | Description                                                                                                                                |
| --------------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `userId`        | `String!` | Yes      | ID of the student (User) whose access should be expired                                                                                    |
| `courseId`      | `String!` | Yes      | ID of the course to expire access for                                                                                                      |
| `customEndedAt` | `Int`     | No       | Custom expiration date as Unix Timestamp (seconds since epoch). Must be a positive integer after January 1, 2020. Defaults to current time |
| `reason`        | `String`  | No       | Optional reason for expiring the access                                                                                                    |

### Return Type [#return-type-5]

```graphql
type AdminExpireStudentCourseAccessPayload {
  # The updated enrollment with expired access
  enrollment: StudentCourseShip
}
```

### StudentCourseShip Object [#studentcourseship-object-2]

| Field            | Type           | Description                                                       |
| ---------------- | -------------- | ----------------------------------------------------------------- |
| `id`             | `String!`      | ID of the enrollment                                              |
| `completionRate` | `Float`        | The completion rate of the enrolled course which student achieved |
| `course`         | `AdminCourse!` | Information of the enrolled course                                |
| `user`           | `AdminUser!`   | User information of the enrolled course                           |
| `createdAt`      | `Int!`         | Created date of the enrollment (Unix Timestamp)                   |
| `updatedAt`      | `Int!`         | Last updated date of the enrollment (Unix Timestamp)              |
| `endedAt`        | `Int`          | Expiration date for the enrollment (Unix Timestamp)               |

### Example [#example-3]

```graphql
mutation ExpireStudentAccess {
  expireStudentCourseAccess(
    userId: "a1b2c3d4-5678-90ef-ghij-klmnopqrstuv"
    courseId: "ab6ee332-614d-475d-93b5-abc5ebb1fc84"
  ) {
    enrollment {
      id
      completionRate
      createdAt
      updatedAt
      endedAt
      course {
        id
        name
        slug
      }
      user {
        id
        name
        email
      }
    }
  }
}
```

### Example — With Custom Expiration Date [#example--with-custom-expiration-date]

```graphql
mutation ExpireStudentAccessWithCustomDate {
  expireStudentCourseAccess(
    userId: "a1b2c3d4-5678-90ef-ghij-klmnopqrstuv"
    courseId: "ab6ee332-614d-475d-93b5-abc5ebb1fc84"
    customEndedAt: 1735689600
    reason: "Course access expired due to non-payment"
  ) {
    enrollment {
      id
      endedAt
      course {
        id
        name
      }
      user {
        id
        name
      }
    }
  }
}
```

### Sample Response [#sample-response-5]

```json
{
  "data": {
    "expireStudentCourseAccess": {
      "enrollment": {
        "id": "619ad939-8591-40ad-9364-cf3825a9bf70",
        "completionRate": 0.25,
        "createdAt": 1672531200,
        "updatedAt": 1747297936,
        "endedAt": 1747297936,
        "course": {
          "id": "9a1216f7-36de-4c50-8094-2ebfb7d3c383",
          "name": "Introduction to GraphQL",
          "slug": "intro-graphql"
        },
        "user": {
          "id": "387b0c87-0f85-44cc-833e-7306c1b5d3e6",
          "name": "Student",
          "email": "student@example.com"
        }
      }
    }
  }
}
```

### Common Errors [#common-errors-5]

| Error                                                                             | Description                                         |
| --------------------------------------------------------------------------------- | --------------------------------------------------- |
| `Student is not enrolled in this course`                                          | The student is not enrolled in the specified course |
| `Course not found`                                                                | The specified course ID does not exist              |
| `User not found`                                                                  | The specified user ID does not exist                |
| `The new end date is too far in the past. Please provide a timestamp after 2020.` | The provided customEndedAt date is invalid          |


---

# Event Mutations (https://docs.loopwise.com/api/mutations/events)



The event mutations allow you to create, update, and delete calendar events within your Loopwise school. These operations enable you to programmatically manage scheduled events such as webinars, office hours, or special sessions.

All event mutations return an `errors` field in the response that will contain any validation or processing errors that occurred during the operation.

## Available Mutations [#available-mutations]

### createEvent [#createevent]

> **Note:** This mutation is still under development and will be fully documented when available.

Creates a new calendar event, specifying details such as title, description, start and end times, and location or online meeting URL.

### updateEvent [#updateevent]

> **Note:** This mutation is still under development and will be fully documented when available.

Updates an existing calendar event with new properties, such as changing the schedule or location.

### deleteEvent [#deleteevent]

> **Note:** This mutation is still under development and will be fully documented when available.

Deletes a calendar event from your school.


---

# Loopwise Admin API Mutations (https://docs.loopwise.com/api/mutations)



## Overview [#overview]

The Loopwise Admin API provides a variety of mutation operations to modify data in your school. These mutations enable you to create, update, and delete resources programmatically, giving you powerful automation capabilities.

## Available Resources [#available-resources]

The API provides mutations for the following resources:

* **Courses** — Create, update, and delete courses
* **Students** — Create students and update their profile and admin tags
* **Posts** — Create, update, and delete posts
* **Assignments** — Create and grade assignments
* **Events** — Manage calendar events
* **Subscriptions** — Manage membership subscriptions
* **Send Custom Email** — Send custom emails to users

## Common Patterns [#common-patterns]

### Error Handling [#error-handling]

All mutations return an `errors` field that contains any validation or processing errors:

```graphql
mutation {
  createCourse(input: { name: "" }) {
    errors {
      field
      message
    }
    course {
      id
      name
    }
  }
}
```

Response:

```json
{
  "data": {
    "createCourse": {
      "errors": [
        {
          "field": "name",
          "message": "Name cannot be empty"
        }
      ],
      "course": null
    }
  }
}
```

### Input Objects [#input-objects]

Most mutations accept a single `input` parameter containing all required fields:

```graphql
mutation {
  createCourse(input: {
    name: "Introduction to GraphQL"
    description: "Learn the basics of GraphQL"
    startDate: "2023-06-01"
  }) {
    course {
      id
      name
    }
    errors {
      field
      message
    }
  }
}
```

## Basic Example [#basic-example]

Here's a simple example of creating a new course:

```graphql
mutation {
  createCourse(input: {
    name: "GraphQL Fundamentals"
    description: "Learn how to use GraphQL APIs"
    published: true
  }) {
    course {
      id
      name
      description
    }
    errors {
      field
      message
    }
  }
}
```

## Authentication [#authentication]

All mutation operations require authentication with an API key. See the Authentication section for details on how to authenticate your requests.

***

## Input Types [#input-types]

Most mutations in the Loopwise Admin API accept structured input objects that encapsulate all the data needed for the operation. These input types provide a consistent pattern for submitting data and help organize complex mutation parameters.

### Input Type Structure [#input-type-structure]

Input types follow these common patterns:

1. **Named Input Objects**: Most mutations accept a single parameter named `input`
2. **Required vs Optional Fields**: Fields are marked as required (`!`) or optional
3. **Nested Objects**: Complex operations may include nested input structures

### Example Input Structure [#example-input-structure]

Here's an example of a typical mutation with an input type:

```graphql
mutation {
  createCourse(input: {
    name: "Advanced GraphQL"
    description: "Deep dive into GraphQL concepts"
    startDate: "2023-07-01"
    endDate: "2023-09-30"
    categoryIds: ["cat_123", "cat_456"]
    lecturerIds: ["user_789"]
  }) {
    course {
      id
      name
    }
    errors {
      field
      message
    }
  }
}
```

### Default Values [#default-values]

Some input fields have default values that are applied if the field is omitted:

```graphql
type CreateCourseInput {
  name: String!
  description: String
  isPublished: Boolean = false  # Default is false if omitted
  maxStudents: Int = 100        # Default is 100 if omitted
}
```

### Nullable Fields [#nullable-fields]

Fields without the `!` suffix are nullable and can be explicitly set to `null`:

```graphql
mutation {
  updateCourse(input: {
    id: "course_123"
    description: null  # Explicitly clearing the description
  }) {
    course {
      id
      description
    }
  }
}
```

### Nested Input Types [#nested-input-types]

Some operations require nested input structures:

```graphql
mutation {
  createCourse(input: {
    name: "Complete Web Development"
    sections: [
      {
        title: "HTML Basics"
        position: 1
        lectures: [
          { title: "Introduction to HTML", content: "..." },
          { title: "HTML Forms", content: "..." }
        ]
      },
      {
        title: "CSS Fundamentals"
        position: 2
        lectures: [
          { title: "Styling Basics", content: "..." }
        ]
      }
    ]
  }) {
    course {
      id
      name
    }
  }
}
```

### Using Variables with Input Types [#using-variables-with-input-types]

For client applications, using variables with input types is recommended to make code more maintainable:

```graphql
mutation CreateCourse($input: CreateCourseInput!) {
  createCourse(input: $input) {
    course {
      id
      name
    }
    errors {
      field
      message
    }
  }
}
```

Variables:

```json
{
  "input": {
    "name": "GraphQL Fundamentals",
    "description": "Learn the basics of GraphQL",
    "startDate": "2023-08-01"
  }
}
```

### Input Type Reuse [#input-type-reuse]

Some input types are reused across multiple mutations:

* `CourseInput` might be used by both `createCourse` and `updateCourse`
* Common structures like `AddressInput` or `DateRangeInput` may be reused across many mutations

This consistency makes the API more predictable and easier to work with.

***

## Input Validation [#input-validation]

The Loopwise Admin API implements comprehensive input validation for all mutation operations. This validation ensures data integrity and provides clear feedback when input requirements aren't met.

### Validation Process [#validation-process]

When you submit a mutation, the API performs the following validation steps:

1. **Type Checking**: Ensures all input values match their expected types
2. **Required Fields**: Verifies all required fields are present
3. **Format Validation**: Validates that fields match expected formats (e.g., email addresses, dates)
4. **Business Logic**: Applies business rules specific to the resource (e.g., enrollment capacity limits)

### Error Response Format [#error-response-format]

All mutations return an `errors` field that contains validation issues. Each error includes:

| Field     | Description                                                                       |
| --------- | --------------------------------------------------------------------------------- |
| `field`   | The name of the input field that failed validation (or `null` for general errors) |
| `message` | A human-readable description of the error                                         |

#### Example Error Response [#example-error-response]

```json
{
  "data": {
    "createCourse": {
      "errors": [
        {
          "field": "name",
          "message": "Name cannot be empty"
        },
        {
          "field": "startDate",
          "message": "Start date must be in the future"
        }
      ],
      "course": null
    }
  }
}
```

### Common Validation Rules [#common-validation-rules]

The following validation rules are commonly applied across mutations:

#### String Fields [#string-fields]

* **Required strings**: Cannot be empty or contain only whitespace
* **Length limits**: Most string fields have maximum lengths (typically 255 characters)
* **Format validation**: Fields like emails, URLs, and phone numbers must match expected formats

#### Numeric Fields [#numeric-fields]

* **Range validation**: Values must be within specified minimums and maximums
* **Precision limits**: Decimal values have precision constraints

#### Date Fields [#date-fields]

* **Format**: Dates must be in ISO 8601 format (e.g., "2023-06-01T00:00:00Z")
* **Range checks**: Certain dates must be in the future or past depending on context

#### Relationships [#relationships]

* **Existence**: Referenced resources (by ID) must exist
* **Permission checks**: You must have access to the referenced resources

### Handling Validation Errors [#handling-validation-errors]

When developing with the API, we recommend:

1. **Check for errors before assuming success** — Always check the `errors` array before processing results
2. **Display user-friendly messages** — The error messages are designed to be helpful to end-users
3. **Implement client-side validation** — Implement similar rules in your client to provide immediate feedback

During development, you can intentionally submit invalid data to understand the API's validation requirements. This can be a helpful way to explore the API's expectations without consulting documentation for every field.


---

# Post Mutations (https://docs.loopwise.com/api/mutations/posts)



The post mutations allow you to create, update, and delete posts within your Loopwise school. These operations enable you to programmatically manage your blog content and article publishing.

**Available mutations:**

* `createPost` — Creates a new post
* `updatePost` — Updates an existing post
* `deletePost` — Deletes a post (soft delete)

All post mutations return an `errors` field in the response that will contain any validation or processing errors that occurred during the operation.

## Post Access Types [#post-access-types]

Posts support different access types:

* `login_required` — Users must be logged in to access
* `paid` — Users must have purchased access
* `public_access` — Available to all users

## Body Content Format [#body-content-format]

The `body` field is an **HTML string**. Posts are also editable in the school dashboard with a rich text editor, which supports standard article markup: headings (`h1`–`h6`), paragraphs, lists, blockquotes, links, images, tables, and code blocks.

> **Compatibility note:** if you write HTML through the API that the dashboard editor does not recognize (custom tags, inline scripts, unusual attributes), it may be normalized or removed the next time someone edits the post in the dashboard. Stick to standard article markup for content that will be co-edited in the dashboard.

To embed images inside the body, upload them first with the `uploadImage` mutation and use the returned URL in an `<img>` tag.

## Cover Photos [#cover-photos]

Set a cover photo by passing `coverPhotoUrl` in the input of `createPost` or `updatePost`:

1. Upload the image with the `uploadImage` mutation.
2. Pass the returned image URL as `coverPhotoUrl`.

Only URLs served from the Loopwise CDN (as returned by `uploadImage`) are accepted; other hosts are rejected with `UPLOAD-008`.

***

## Create a Post [#create-a-post]

The `createPost` mutation allows you to create a new post in your Loopwise school with the specified properties.

### Input Parameters [#input-parameters]

| Field   | Type              | Description                                   |
| ------- | ----------------- | --------------------------------------------- |
| `input` | `AdminPostInput!` | Input object containing post creation details |

### AdminPostInput Fields [#adminpostinput-fields]

| Field           | Type        | Required | Description                                                                                                                      |
| --------------- | ----------- | -------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `title`         | `String`    | Yes      | Post title                                                                                                                       |
| `subtitle`      | `String`    | No       | Post subtitle                                                                                                                    |
| `body`          | `String`    | Yes      | Post body content as HTML (see [Body Content Format](#body-content-format))                                                      |
| `excerpt`       | `String`    | No       | Post excerpt                                                                                                                     |
| `slug`          | `String`    | Yes      | URL slug for the post. Must contain only lowercase letters, numbers, and hyphens                                                 |
| `accessType`    | `String`    | Yes      | Access type for the post (login\_required, paid, public\_access)                                                                 |
| `published`     | `Boolean`   | No       | Whether the post is published (default: false)                                                                                   |
| `publishedAt`   | `Int`       | No       | Unix timestamp when the post should be published                                                                                 |
| `categoryId`    | `String`    | No       | ID of one of this school's post categories (list them with the `postCategories` query). Any other ID is rejected with `POST-007` |
| `tagList`       | `[String!]` | No       | Tags to associate with this post                                                                                                 |
| `noindex`       | `Boolean`   | No       | Exclude this post from search engine indexing                                                                                    |
| `userId`        | `String`    | No       | ID of the user (author) for this post (default: school owner)                                                                    |
| `coverPhotoUrl` | `String`    | No       | Cover photo URL returned by `uploadImage` (see [Cover Photos](#cover-photos))                                                    |

> `title`, `body`, `slug`, and `accessType` are declared as nullable in the schema (the same input type is shared with `updatePost`), but they are required when creating a post. Missing fields are rejected with error code `POST-006`.

### Return Type [#return-type]

```graphql
type AdminPostCreatePayload {
  # Array of error messages, if any occurred during the operation
  errors: [String!]

  # The created post object, null if operation failed
  post: AdminPost
}
```

### Example [#example]

```graphql
mutation CreatePost {
  createPost(input: {
    title: "Getting Started with GraphQL"
    subtitle: "A comprehensive guide for beginners"
    body: "GraphQL is a query language for APIs..."
    excerpt: "Learn the basics of GraphQL"
    slug: "getting-started-with-graphql"
    accessType: "public_access"
    published: true
    tagList: ["graphql", "tutorial", "api"]
  }) {
    post {
      id
      title
      subtitle
      slug
      accessType
      published
      tags
    }
    errors
  }
}
```

### Sample Response [#sample-response]

```json
{
  "data": {
    "createPost": {
      "post": {
        "id": "post_12345",
        "title": "Getting Started with GraphQL",
        "subtitle": "A comprehensive guide for beginners",
        "slug": "getting-started-with-graphql",
        "accessType": "public_access",
        "published": true,
        "tags": ["graphql", "tutorial", "api"]
      },
      "errors": []
    }
  }
}
```

### Common Errors [#common-errors]

| Error                                | Description                                                          |
| ------------------------------------ | -------------------------------------------------------------------- |
| `POST-006 Missing required field(s)` | `title`, `body`, `slug`, or `accessType` was not provided            |
| `POST-007 Post category not found`   | `categoryId` is not one of this school's post categories             |
| `Title cannot be empty`              | The post title is required                                           |
| `Body cannot be empty`               | The post body content is required                                    |
| `Slug already exists`                | The provided slug is already in use                                  |
| `Invalid access type`                | The accessType must be one of: login\_required, paid, public\_access |
| `User not found`                     | The specified user ID does not exist                                 |

***

## Update a Post [#update-a-post]

The `updatePost` mutation updates an existing post in your Loopwise school. It has **partial-update (PATCH) semantics**: only the fields you include in the input are changed, and omitted fields keep their current values. You can update a single field — for example the title — without resending the body.

### Input Parameters [#input-parameters-1]

| Field   | Type              | Description                                         |
| ------- | ----------------- | --------------------------------------------------- |
| `id`    | `String!`         | ID of the post to update                            |
| `input` | `AdminPostInput!` | Fields to change; omitted fields are left untouched |

### AdminPostInput Fields [#adminpostinput-fields-1]

All fields are optional on update.

| Field           | Type        | Description                                                                                                               |
| --------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------- |
| `title`         | `String`    | Post title (cannot be set to null)                                                                                        |
| `subtitle`      | `String`    | Post subtitle. Pass `null` to clear it                                                                                    |
| `body`          | `String`    | Post body content as HTML (cannot be set to null; see [Body Content Format](#body-content-format))                        |
| `excerpt`       | `String`    | Post excerpt. Pass `null` to clear it                                                                                     |
| `slug`          | `String`    | URL slug. Must contain only lowercase letters, numbers, and hyphens                                                       |
| `accessType`    | `String`    | Access type (login\_required, paid, public\_access)                                                                       |
| `published`     | `Boolean`   | Whether the post is published                                                                                             |
| `publishedAt`   | `Int`       | Unix timestamp of the publish time (see note below)                                                                       |
| `categoryId`    | `String`    | ID of one of this school's post categories (any other ID is rejected with `POST-007`). Pass `null` to detach the category |
| `tagList`       | `[String!]` | Replaces the post's tags. Pass `[]` to clear all tags                                                                     |
| `noindex`       | `Boolean`   | Exclude this post from search engine indexing                                                                             |
| `userId`        | `String`    | ID of the user (author) for this post                                                                                     |
| `coverPhotoUrl` | `String`    | Cover photo URL returned by `uploadImage` (see [Cover Photos](#cover-photos))                                             |

> **`publishedAt` follows `published`:** unpublishing a post clears its `publishedAt`, and publishing a post without a timestamp sets `publishedAt` to the current time. It cannot be cleared independently while the post is published.

### Return Type [#return-type-1]

```graphql
type AdminPostUpdatePayload {
  # Array of error messages, if any occurred during the operation
  errors: [String!]

  # The updated post object, null if operation failed
  post: AdminPost
}
```

### Example [#example-1]

Update only the title and tags — every other field, including the body, is left untouched:

```graphql
mutation UpdatePost {
  updatePost(
    id: "post_12345"
    input: {
      title: "Advanced GraphQL Techniques"
      tagList: ["graphql", "advanced", "optimization"]
    }
  ) {
    post {
      id
      title
      subtitle
      slug
      accessType
      published
      publishedAt
      tags
      updatedAt
    }
    errors
  }
}
```

### Sample Response [#sample-response-1]

```json
{
  "data": {
    "updatePost": {
      "post": {
        "id": "post_12345",
        "title": "Advanced GraphQL Techniques",
        "subtitle": "A comprehensive guide for beginners",
        "slug": "getting-started-with-graphql",
        "accessType": "public_access",
        "published": true,
        "publishedAt": 1687436400,
        "tags": ["graphql", "advanced", "optimization"],
        "updatedAt": 1687436500
      },
      "errors": []
    }
  }
}
```

### Common Errors [#common-errors-1]

| Error                              | Description                                                          |
| ---------------------------------- | -------------------------------------------------------------------- |
| `Post not found`                   | The specified post ID does not exist                                 |
| `Title cannot be empty`            | The post title is required                                           |
| `Body cannot be empty`             | The post body content is required                                    |
| `Slug already exists`              | The provided slug is already in use by another post                  |
| `Invalid access type`              | The accessType must be one of: login\_required, paid, public\_access |
| `POST-007 Post category not found` | `categoryId` is not one of this school's post categories             |
| `User not found`                   | The specified user ID does not exist                                 |

***

## Delete a Post [#delete-a-post]

The `deletePost` mutation allows you to delete a post from your Loopwise school. This is a soft delete operation, meaning the post data is retained but marked as deleted.

### Input Parameters [#input-parameters-2]

| Field | Type      | Description              |
| ----- | --------- | ------------------------ |
| `id`  | `String!` | ID of the post to delete |

### Return Type [#return-type-2]

```graphql
type AdminPostDeletePayload {
  # Array of error messages, if any occurred during the operation
  errors: [String!]

  # Boolean indicating whether the deletion was successful
  success: Boolean
}
```

### Example [#example-2]

```graphql
mutation DeletePost {
  deletePost(id: "post_12345") {
    success
    errors
  }
}
```

### Sample Response [#sample-response-2]

```json
{
  "data": {
    "deletePost": {
      "success": true,
      "errors": []
    }
  }
}
```

### Error Response [#error-response]

If the deletion fails, you might receive a response like this:

```json
{
  "data": {
    "deletePost": {
      "success": false,
      "errors": ["Post not found"]
    }
  }
}
```

### Common Errors [#common-errors-2]

| Error                      | Description                                   |
| -------------------------- | --------------------------------------------- |
| `Post not found`           | The specified post ID does not exist          |
| `Post already deleted`     | The post has already been deleted             |
| `Insufficient permissions` | You don't have permission to delete this post |

### Important Notes [#important-notes]

* This is a **soft delete** operation — the post data is retained in the system but marked as deleted
* Deleted posts will not appear in regular queries
* The post can potentially be restored by system administrators if needed
* All associated data (comments, ratings, etc.) will also be hidden when the post is deleted


---

# Send Custom Email (https://docs.loopwise.com/api/mutations/send-custom-email)



The `sendCustomEmail` mutation allows you to send custom emails to users through the Loopwise platform. This enables you to communicate directly with your students and users.

## Input Parameters [#input-parameters]

| Field               | Type      | Description                               |
| ------------------- | --------- | ----------------------------------------- |
| `email`             | `String!` | Email address of the recipient            |
| `subject`           | `String!` | The subject of the email (Base64 encoded) |
| `content`           | `String!` | The content of the email (Base64 encoded) |
| `templateVariables` | `JSON`    | Template variables for dynamic content    |

## Return Type [#return-type]

```graphql
type AdminSendCustomEmailPayload {
  # Success message or error details
  message: String

  # Boolean indicating whether the email was sent successfully
  success: Boolean!
}
```

## Example [#example]

```graphql
mutation SendCustomEmail {
  sendCustomEmail(
    email: "student@example.com"
    subject: "V2VsY29tZSB0byBvdXIgY291cnNlIQ=="  # Base64 for "Welcome to our course!"
    content: "SGkgSm9obiwgd2VsY29tZSB0byBvdXIgR3JhcGhRTCBjb3Vyc2UhIFdlJ3JlIGV4Y2l0ZWQgdG8gaGF2ZSB5b3UuLi4="  # Base64 encoded content
    templateVariables: {
      userName: "John"
      courseName: "GraphQL Fundamentals"
    }
  ) {
    success
    message
  }
}
```

## Sample Response [#sample-response]

```json
{
  "data": {
    "sendCustomEmail": {
      "success": true,
      "message": "Email sent successfully"
    }
  }
}
```

## Error Response [#error-response]

If the email fails to send:

```json
{
  "data": {
    "sendCustomEmail": {
      "success": false,
      "message": "Invalid email address"
    }
  }
}
```

## Base64 Encoding [#base64-encoding]

The `subject` and `content` fields must be Base64 encoded. Here's how to encode them:

### JavaScript Example [#javascript-example]

```javascript
const subject = btoa("Welcome to our course!");
const content = btoa(`
Hi {{userName}},

Welcome to {{courseName}}! We're excited to have you join us.

Best regards,
The Loopwise Team
`);
```

### Python Example [#python-example]

```python
import base64

subject = base64.b64encode("Welcome to our course!".encode()).decode()
content = base64.b64encode("""
Hi {{userName}},

Welcome to {{courseName}}! We're excited to have you join us.

Best regards,
The Loopwise Team
""".encode()).decode()
```

## Template Variables [#template-variables]

The `templateVariables` field allows you to pass dynamic content that can be used in the email template. Common variables include:

| Variable     | Description                         |
| ------------ | ----------------------------------- |
| `userName`   | The recipient's name                |
| `courseName` | Name of a course                    |
| `schoolName` | Name of your school                 |
| `customData` | Any custom data you want to include |

Variable values are inserted into `content` as text: HTML in a value is escaped, so a value such as `<b>John</b>` appears in the email literally rather than as bold text. Put links, images and other markup in `content` itself. The subject is plain text.

## Common Errors [#common-errors]

| Error                       | Description                                           |
| --------------------------- | ----------------------------------------------------- |
| `Invalid email address`     | The provided email address is not valid               |
| `Subject required`          | The email subject cannot be empty                     |
| `Content required`          | The email content cannot be empty                     |
| `Invalid Base64 encoding`   | The subject or content is not properly Base64 encoded |
| `Email service unavailable` | The email service is temporarily unavailable          |

## Important Notes [#important-notes]

* Both `subject` and `content` must be Base64 encoded
* Template variables can be used within the content using double curly braces (e.g., `{{userName}}`)
* Emails are sent asynchronously — a successful response means the email was queued for delivery
* Consider rate limiting when sending bulk emails


---

# Student Mutations (https://docs.loopwise.com/api/mutations/students)



The student mutations allow you to create students and update an existing student's profile fields and admin-managed tags.

**Student entity mutations:**

* `createStudent` — Creates a new student, or returns the existing user if the email already matches one
* `updateStudent` — Updates a student's name, phone number, and/or admin tags

Both mutations require a token with the `students:write` scope.

> **Note:** Admin tags can gate access to tag-restricted consulting services, so tag writes are an access-granting operation — grant `students:write` accordingly.

***

## Create a Student [#create-a-student]

The `createStudent` mutation creates a new student in your school, or returns the existing user if the email already matches one. It is idempotent — safe to retry — and does NOT send any email.

### Input Parameters [#input-parameters]

| Field         | Type      | Required | Description                                                                                                                                                                                                |
| ------------- | --------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `email`       | `String!` | Yes      | Email of the student. Used as the idempotency key within the school.                                                                                                                                       |
| `name`        | `String`  | No       | Display name of the student. When omitted or blank, the email is used as the display name. For existing users, an incoming name is ignored unless the existing name is blank or the placeholder "Student". |
| `phoneNumber` | `String`  | No       | Phone number. Ignored if the user already exists.                                                                                                                                                          |

### Return Type [#return-type]

```graphql
type AdminCreateStudentPayload {
  # The created or existing student
  student: AdminUser!

  # True if a new user was created, false if the email matched an existing user
  created: Boolean!
}
```

### Example [#example]

```graphql
mutation CreateStudent {
  createStudent(
    email: "jane@example.com"
    name: "Jane Doe"
    phoneNumber: "0912345678"
  ) {
    student {
      id
      email
      name
      phoneNumber
    }
    created
  }
}
```

### Sample Response [#sample-response]

```json
{
  "data": {
    "createStudent": {
      "student": {
        "id": "user_12345",
        "email": "jane@example.com",
        "name": "Jane Doe",
        "phoneNumber": "+886912345678"
      },
      "created": true
    }
  }
}
```

### Common Errors [#common-errors]

| Code          | Description               |
| ------------- | ------------------------- |
| `STUDENT-002` | Invalid email format      |
| `STUDENT-004` | Failed to create new user |

***

## Update a Student [#update-a-student]

The `updateStudent` mutation performs a partial update on an existing student in your school. Only the input keys you provide are applied — omitted keys leave the corresponding field unchanged. All writes are absolute sets, so the mutation is idempotent — safe to retry.

> **Note:** `email` is intentionally NOT updatable through this mutation. Email is the idempotency key used by `createStudent` and is never changed through the Admin API.

**Who is updatable:** any user holding the student role in the school. Teaching assistants without the student role and unknown or out-of-school IDs return a not-found error.

### Input Parameters [#input-parameters-1]

| Field   | Type                       | Description                       |
| ------- | -------------------------- | --------------------------------- |
| `id`    | `String!`                  | ID of the student to update       |
| `input` | `AdminStudentUpdateInput!` | Partial-update fields (see below) |

### AdminStudentUpdateInput Fields [#adminstudentupdateinput-fields]

| Field         | Type        | Required | Description                                                                                                                                                                                                                                                                                                                       |
| ------------- | ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`        | `String`    | No       | Display name. Omit to leave unchanged. Explicit `null` or a blank string is rejected — students must keep a display name.                                                                                                                                                                                                         |
| `phoneNumber` | `String`    | No       | Phone number. Omit to leave unchanged; pass `null` to clear it. Numbers are normalized with a TW default country code and echoed back normalized (e.g. `0912345678` → `+886912345678`).                                                                                                                                           |
| `tags`        | `[String!]` | No       | Admin tags. &#x2A;*Replaces the entire list — pass all tags every time.** An empty array (`[]`) clears all admin tags; explicit `null` is a no-op, same as omitting the key. Tags containing commas are rejected. Tag names match case-insensitively but preserve the casing of first use. System-managed tags are never touched. |

To modify tags safely, read the current list first from the `tags` field on `AdminUser` (see [Users Query](/docs/api/queries/users)), modify it, and write the full list back.

### Return Type [#return-type-1]

```graphql
type AdminUpdateStudentPayload {
  # The updated student, null if the update failed
  student: AdminUser

  # Validation errors, if any occurred during the update
  errors: [String!]
}
```

### Example [#example-1]

```graphql
mutation UpdateStudent {
  updateStudent(
    id: "user_12345"
    input: {
      name: "Jane Doe"
      phoneNumber: "0912345678"
      tags: ["vip", "beta-tester"]
    }
  ) {
    student {
      id
      name
      phoneNumber
      tags
    }
    errors
  }
}
```

### Sample Response [#sample-response-1]

```json
{
  "data": {
    "updateStudent": {
      "student": {
        "id": "user_12345",
        "name": "Jane Doe",
        "phoneNumber": "+886912345678",
        "tags": ["beta-tester", "vip"]
      },
      "errors": null
    }
  }
}
```

### Partial Update Example [#partial-update-example]

Omitted keys (including `tags`) are left untouched:

```graphql
mutation UpdateStudentNameOnly {
  updateStudent(id: "user_12345", input: { name: "Jane Smith" }) {
    student {
      id
      name
      phoneNumber   # unchanged
      tags          # unchanged
    }
    errors
  }
}
```

### Clearing All Tags [#clearing-all-tags]

Pass an empty array to remove all admin tags from a student (`tags: null` would be a no-op):

```graphql
mutation ClearStudentTags {
  updateStudent(id: "user_12345", input: { tags: [] }) {
    student {
      id
      tags
    }
    errors
  }
}
```

### Common Errors [#common-errors-1]

| Code          | Description                                                                                                                                                                         |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `STUDENT-005` | User not found — the `id` does not resolve to a user with the student role in the current school (unknown ID, out-of-school user, or a teaching assistant without the student role) |
| `STUDENT-003` | Name cannot be blank — explicit `null` or blank `name` is rejected                                                                                                                  |
| `STUDENT-007` | Invalid tag value — tags must be non-blank and must not contain commas                                                                                                              |
| `STUDENT-006` | Failed to update user                                                                                                                                                               |

Model validation failures (e.g. an invalid phone number) are returned in the `errors` field of the payload rather than as GraphQL errors.


---

# Subscription Mutations (https://docs.loopwise.com/api/mutations/subscriptions)



The subscription mutations allow you to create and manage user subscriptions to membership plans within your Loopwise school. These operations enable you to programmatically handle subscription lifecycle events.

**Available mutations:**

| Operation            | Description                                  |
| -------------------- | -------------------------------------------- |
| `createSubscription` | Create a new subscription for a user         |
| `updateSubscription` | Update an existing subscription's end period |
| `cancelSubscription` | Cancel an existing subscription for a user   |

## Common Use Cases [#common-use-cases]

### User Enrollment Automation [#user-enrollment-automation]

Use the subscription mutations to automatically enroll users in membership plans when they complete certain actions in your application or meet specific criteria.

### Subscription Extension [#subscription-extension]

Extend subscription periods for loyal customers or as part of a promotion campaign.

### Trial Management [#trial-management]

Manage trial periods by creating time-limited subscriptions and extending or shortening them based on user engagement.

### Lifetime Access [#lifetime-access]

Create lifetime subscriptions for users who purchase permanent access plans. Lifetime subscriptions:

* Grant permanent access with no expiration (`endAt` is `null`)
* Have no billing periods (`currentPeriodEnd` is `null`)
* Cannot be cancelled or updated (`isCancellable` is `false`)
* Are one-time purchases with no recurring charges

## Plan Types [#plan-types]

Different plan types have different behaviors when creating subscriptions:

| Plan Type         | Description                                 | `endAt`    | `currentPeriodEnd` | Cancellable |
| ----------------- | ------------------------------------------- | ---------- | ------------------ | ----------- |
| `recurring`       | Regular subscription with recurring billing | Calculated | Billing period end | Yes         |
| `fixed_date`      | Expires on a specific date                  | Set date   | Set date           | Yes         |
| `specific_length` | Expires after a specific duration           | Calculated | Calculated         | Yes         |
| `lifetime`        | Permanent access, one-time purchase         | `null`     | `null`             | No          |

***

## Create a Subscription [#create-a-subscription]

The `createSubscription` mutation allows you to programmatically create a new subscription for a user to a specific membership plan. This enables automatic enrollment in premium content or membership benefits.

### Input Parameters [#input-parameters]

| Field             | Type      | Description                                                                |
| ----------------- | --------- | -------------------------------------------------------------------------- |
| `email`           | `String!` | Email of the user to create subscription for                               |
| `name`            | `String`  | Name of the user (required if user doesn't exist)                          |
| `planId`          | `String!` | ID of the membership plan                                                  |
| `expireAt`        | `Int`     | Expiration date for fixed\_date or specific\_length plans (Unix Timestamp) |
| `initialChargeAt` | `Int`     | Initial charge date for recurring plans (Unix Timestamp)                   |

> **Note:** For lifetime plans, neither `expireAt` nor `initialChargeAt` parameters are applicable as lifetime subscriptions grant permanent access with no expiration or recurring billing.

### Return Type [#return-type]

```graphql
type AdminCreateSubscriptionPayload {
  # Array of error messages, if any occurred during the operation
  errors: [String!]!

  # The created subscription object, null if operation failed
  subscription: AdminSubscription
}
```

### AdminSubscription Object [#adminsubscription-object]

```graphql
type AdminSubscription {
  # Optional reason for subscription cancellation
  cancelReason: String

  # Type of cancellation, if applicable
  cancelType: String

  # When the subscription was created
  createdAt: Int!

  # End of the current billing period
  currentPeriodEnd: Int

  # Start of the current billing period
  currentPeriodStart: Int

  # Unix timestamp when the subscription ends
  endAt: Int

  # Unique identifier for the subscription
  id: String!

  # Indicates whether this subscription will be cancelled in the next billing cycle
  isCanceling: Boolean!

  # Indicates whether this subscription can be cancelled
  isCancellable: Boolean!

  # Timestamp of the next scheduled charge (null for non-recurring or inactive subscriptions)
  nextChargeDate: Int

  # The membership plan associated with this subscription
  plan: MembershipPlan!

  # The ID of the membership plan
  planId: String!

  # Unix timestamp when the subscription starts
  startAt: Int

  # The current state of the subscription
  state: String!

  # When the subscription was last updated
  updatedAt: Int!

  # The user who owns this subscription
  user: User!
}
```

### Example [#example]

```graphql
mutation CreateSubscription($email: String!, $planId: String!, $name: String) {
  createSubscription(
    email: $email
    name: $name
    planId: $planId
  ) {
    errors
    subscription {
      id
      state
      planId
      startAt
      endAt
      currentPeriodStart
      currentPeriodEnd
      nextChargeDate
      user {
        id
        email
        name
      }
      plan {
        id
        name
        interval
        intervalCount
      }
    }
  }
}
```

### Variables [#variables]

```json
{
  "email": "john@example.com",
  "name": "John Doe",
  "planId": "plan_456"
}
```

### Sample Response [#sample-response]

```json
{
  "data": {
    "createSubscription": {
      "errors": [],
      "subscription": {
        "id": "sub_12345",
        "state": "active",
        "planId": "plan_456",
        "startAt": 1687436400,
        "endAt": null,
        "currentPeriodStart": 1687436400,
        "currentPeriodEnd": 1690028799,
        "nextChargeDate": 1690028799,
        "user": {
          "id": "user_789",
          "email": "john@example.com",
          "name": "John Doe"
        },
        "plan": {
          "id": "plan_456",
          "name": "Premium Monthly",
          "interval": "month",
          "intervalCount": 1
        }
      }
    }
  }
}
```

### Common Errors [#common-errors]

| Error                                  | Description                                                        |
| -------------------------------------- | ------------------------------------------------------------------ |
| `Plan not found`                       | The specified plan ID does not exist                               |
| `User already subscribed to this plan` | The user already has an active subscription to this plan           |
| `Name is required for new users`       | When creating a subscription for a new user, name must be provided |
| `Invalid plan type`                    | The expireAt parameter is only valid for fixed\_date plan types    |
| `Unauthorized`                         | The API key does not have permission to create subscriptions       |

### Usage Scenarios [#usage-scenarios]

#### Creating a Subscription for an Existing User [#creating-a-subscription-for-an-existing-user]

```graphql
mutation CreateExistingUserSubscription {
  createSubscription(
    email: "existing@example.com",
    planId: "plan_monthly_123"
  ) {
    errors
    subscription {
      id
      state
      user { email }
      plan { name }
    }
  }
}
```

#### Creating a Subscription with Specific Expiration [#creating-a-subscription-with-specific-expiration]

For fixed\_date or specific\_length plan types, you can specify when the subscription should expire:

```graphql
mutation CreateFixedSubscription {
  createSubscription(
    email: "student@example.com",
    name: "New Student",
    planId: "plan_course_456",
    expireAt: 1704067199  # December 31, 2023 23:59:59 UTC
  ) {
    errors
    subscription {
      id
      endAt
    }
  }
}
```

#### Creating a Lifetime Subscription [#creating-a-lifetime-subscription]

For lifetime plans, the subscription grants permanent access with no expiration. No additional parameters like `expireAt` or `initialChargeAt` are needed:

```graphql
mutation CreateLifetimeSubscription {
  createSubscription(
    email: "member@example.com",
    name: "Premium Member",
    planId: "plan_lifetime_123"
  ) {
    errors
    subscription {
      id
      state
      endAt              # Will be null (permanent access)
      currentPeriodEnd   # Will be null (no billing period)
      nextChargeDate     # Will be null (one-time payment)
      plan {
        id
        name
        planType         # Will be "lifetime"
        isLifetime       # Will be true
      }
    }
  }
}
```

**Key characteristics of lifetime subscriptions:**

* `endAt` is `null` — the subscription never expires
* `currentPeriodEnd` is `null` — there is no billing period
* `nextChargeDate` is `null` — there are no recurring charges
* `isCancellable` is `false` — lifetime subscriptions cannot be cancelled

***

## Update a Subscription [#update-a-subscription]

The `updateSubscription` mutation allows you to update an existing subscription's end period. This mutation is particularly useful for extending or shortening subscription periods based on business rules or customer service needs.

### Input Parameters [#input-parameters-1]

| Field              | Type      | Description                                                       |
| ------------------ | --------- | ----------------------------------------------------------------- |
| `id`               | `String!` | The ID of the subscription to update                              |
| `currentPeriodEnd` | `Int!`    | New end date for the current subscription period (Unix Timestamp) |

> **Note:** Lifetime subscriptions cannot have their period updated. Attempting to update a lifetime subscription will return an error, as lifetime plans grant permanent access and do not have billing periods.

> **Note:** On a `recurring` plan whose subscription still renews (`active`, `trialing`, `incomplete` or `past_due`), a future `currentPeriodEnd` never adds an end date to course access that has none. The member keeps unlimited access for as long as the subscription renews, and such access is restored if it had expired. Course access that already has an end date moves to the new `currentPeriodEnd`. So does all course access on `fixed_date` and `specific_length` plans, and on subscriptions that are `canceled`, `expired` or `incomplete_expired`. To set a course end date directly, use `extendStudentCourseAccess`.

### Return Type [#return-type-1]

```graphql
type AdminUpdateSubscriptionPayload {
  # Array of error messages, if any occurred during the operation
  errors: [String!]!

  # The updated subscription object, null if operation failed
  subscription: Subscription
}
```

### Subscription Object [#subscription-object]

```graphql
type Subscription {
  # The unique identifier for the subscription
  id: String!

  # The timestamp when the current billing period ends
  currentPeriodEnd: Int

  # The timestamp when the current billing period started
  currentPeriodStart: Int

  # The timestamp when the subscription will end (for non-recurring subscriptions)
  endAt: Int

  # Indicates whether this subscription will be cancelled at the end of the current period
  isCanceling: Boolean!

  # Indicates whether this subscription can be cancelled
  isCancellable: Boolean!

  # The timestamp of the next scheduled charge (null for non-recurring subscriptions)
  nextChargeDate: Int

  # List of payments associated with this subscription
  payments: [Payment!]

  # The membership plan associated with this subscription
  plan: MembershipPlan!

  # The ID of the membership plan
  planId: String!

  # The timestamp when the subscription started
  startAt: Int

  # The current state of the subscription
  # Possible values: active, incomplete, incomplete_expired, trialing, past_due, canceled, expired
  state: String!

  # The user who owns this subscription
  user: User!
}
```

### Example [#example-1]

```graphql
mutation UpdateSubscription {
  updateSubscription(
    id: "sub_12345",
    currentPeriodEnd: 1704067199
  ) {
    errors
    subscription {
      id
      currentPeriodEnd
      currentPeriodStart
      state
      isCanceling
      user {
        id
        name
        email
      }
      plan {
        id
        name
      }
    }
  }
}
```

### Sample Response [#sample-response-1]

```json
{
  "data": {
    "updateSubscription": {
      "errors": [],
      "subscription": {
        "id": "sub_12345",
        "currentPeriodEnd": "1704067199",
        "currentPeriodStart": "1701388800",
        "state": "active",
        "isCanceling": false,
        "user": {
          "id": "user_789",
          "name": "John Doe",
          "email": "john@example.com"
        },
        "plan": {
          "id": "plan_456",
          "name": "Premium Annual"
        }
      }
    }
  }
}
```

### Restrictions for Canceling Subscriptions [#restrictions-for-canceling-subscriptions]

If a subscription is in a `canceling` state (i.e., `isCanceling: true` — the user has already requested cancellation but it's scheduled for a future date), all update operations are blocked. This is consistent with the UI behavior.

| Operation          | Allowed? | Error Message                                                                                         |
| ------------------ | -------- | ----------------------------------------------------------------------------------------------------- |
| Extend period      | No       | "Cannot update a subscription that is pending cancellation. Use cancelSubscription mutation instead." |
| Shorten period     | No       | "Cannot update a subscription that is pending cancellation. Use cancelSubscription mutation instead." |
| Set past timestamp | No       | "Cannot update a subscription that is pending cancellation. Use cancelSubscription mutation instead." |

> **Note:** To immediately cancel a subscription that is pending cancellation, use the `cancelSubscription` mutation instead. The `cancelSubscription` mutation will immediately terminate the subscription regardless of the originally scheduled cancellation date.

### Common Errors [#common-errors-1]

| Error                                                                                                 | Description                                                                                                          |
| ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `Subscription not found`                                                                              | The specified subscription ID does not exist                                                                         |
| `Cannot update period for lifetime subscriptions`                                                     | Lifetime plans grant permanent access and do not have billing periods that can be updated                            |
| `Cannot update an already cancelled subscription`                                                     | The subscription has already been fully cancelled (`state: canceled`)                                                |
| `Cannot update a subscription that is pending cancellation. Use cancelSubscription mutation instead.` | The subscription is in `canceling` state; all operations are blocked. Use CancelSubscription for early cancellation. |
| `Timestamp cannot be more than 10 years in the future`                                                | The provided timestamp exceeds the maximum allowed value                                                             |
| `Timestamp cannot be more than 1 year in the past`                                                    | The provided timestamp is too far in the past                                                                        |
| `Cannot set end date earlier than current period start`                                               | The new end date cannot be before the subscription's current period start date                                       |

### Usage Scenarios [#usage-scenarios-1]

#### Extending a Subscription [#extending-a-subscription]

Extend a subscription that's about to expire for a loyal customer:

```graphql
mutation ExtendSubscription {
  updateSubscription(
    id: "sub_12345",
    currentPeriodEnd: 1706745599  # Example: January 31, 2024 23:59:59 UTC
  ) {
    subscription {
      id
      currentPeriodEnd
      user { name }
    }
    errors
  }
}
```

#### Shortening a Trial Period [#shortening-a-trial-period]

Adjust the end date of a trial subscription:

```graphql
mutation ShortenTrial {
  updateSubscription(
    id: "sub_trial_789",
    currentPeriodEnd: 1689465599  # Example: July 15, 2023 23:59:59 UTC
  ) {
    subscription {
      id
      currentPeriodEnd
      state
    }
    errors
  }
}
```

***

## Cancel a Subscription [#cancel-a-subscription]

The `cancelSubscription` mutation allows you to programmatically cancel an active subscription for a user. This enables you to revoke access to premium content or membership benefits at the end of the current billing period or immediately.

### Input Parameters [#input-parameters-2]

| Field               | Type      | Required | Description                                                                                                   |
| ------------------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------- |
| `id`                | `String!` | Yes      | ID of the subscription to cancel                                                                              |
| `cancelAtPeriodEnd` | `Boolean` | No       | If true, cancels at period end; if false, cancels immediately or at specified time (default: true)            |
| `customEndedAt`     | `Int`     | No       | Specific time to end the subscription as Unix Timestamp (seconds since epoch). Overrides the default behavior |

> **Note:** Lifetime subscriptions cannot be cancelled as they represent one-time purchases with permanent access. The `isCancellable` field will return `false` for lifetime subscriptions.

### Return Type [#return-type-2]

```graphql
type AdminCancelSubscriptionPayload {
  # Array of error messages, if any occurred during the operation
  errors: [String!]!

  # The cancelled subscription object, null if operation failed
  subscription: Subscription
}
```

### Subscription Object [#subscription-object-1]

```graphql
type Subscription {
  id: String!

  # Unix Timestamp. The date when the subscription was cancelled. Null if not cancelled.
  canceledAt: Int

  # Unix Timestamp. The end date of the current billing period. For active subscriptions, this represents when the next payment will be due.
  currentPeriodEnd: Int

  # Unix Timestamp. The start date of the current billing period.
  currentPeriodStart: Int

  # Unix Timestamp. The date when the subscription ends. For cancelled subscriptions, this represents the final termination date.
  endAt: Int

  # Indicates whether this subscription will be cancelled in the next billing cycle
  isCanceling: Boolean!

  # Indicates whether this subscription can be cancelled
  isCancellable: Boolean!

  # Timestamp of the next scheduled charge. Null for non-recurring or inactive subscriptions.
  nextChargeDate: Int

  payments: [Payment!]
  plan: MembershipPlan!
  planId: String!

  # Unix Timestamp. The date when the subscription starts.
  startAt: Int

  # Possible values: active, incomplete, incomplete_expired, trialing, past_due, canceled, expired
  state: String!

  # The user who owns this subscription
  user: User!
}
```

### Example [#example-2]

```graphql
mutation CancelSubscription {
  cancelSubscription(
    id: "sub_12345"
    cancelAtPeriodEnd: true
  ) {
    errors
    subscription {
      id
      planId
      startAt
      endAt
      isCanceling
      state
      user {
        id
        name
        email
      }
    }
  }
}
```

### Example — Immediate Cancellation [#example--immediate-cancellation]

```graphql
mutation CancelSubscriptionImmediately {
  cancelSubscription(
    id: "sub_12345"
    cancelAtPeriodEnd: false
  ) {
    errors
    subscription {
      id
      state
      endAt
      canceledAt
    }
  }
}
```

### Early Cancellation (for subscriptions pending cancellation) [#early-cancellation-for-subscriptions-pending-cancellation]

If a subscription is already in a `canceling` state (i.e., `isCanceling: true` — the user has already requested cancellation but it's scheduled for a future date), you can use this mutation to immediately cancel the subscription.

#### Behavior [#behavior]

When calling `cancelSubscription` on a subscription that is already `canceling`:

| Aspect                        | Behavior                                                    |
| ----------------------------- | ----------------------------------------------------------- |
| `cancelAtPeriodEnd` parameter | **Ignored** — always cancels immediately                    |
| `customEndedAt` parameter     | **Ignored** — always cancels immediately                    |
| Result                        | Subscription is immediately cancelled (`state: "canceled"`) |
| `cancelAt`                    | Set to `null` (scheduled cancellation is cleared)           |
| `endAt`                       | Set to current time                                         |

#### Example — Early Cancel a Pending Cancellation [#example--early-cancel-a-pending-cancellation]

```graphql
mutation EarlyCancelSubscription {
  cancelSubscription(
    id: "sub_12345"
  ) {
    errors
    subscription {
      id
      state
      isCanceling
      cancelAt
      endAt
      canceledAt
    }
  }
}
```

#### Sample Response — Early Cancellation [#sample-response--early-cancellation]

```json
{
  "data": {
    "cancelSubscription": {
      "errors": [],
      "subscription": {
        "id": "1af2d4fc-1bfb-4e03-a11d-6254bf175adb",
        "state": "canceled",
        "isCanceling": false,
        "cancelAt": null,
        "endAt": 1736956800,
        "canceledAt": 1736956800
      }
    }
  }
}
```

> **Note:** This is useful when a student has already initiated a cancellation request, but an administrator needs to immediately terminate the subscription (e.g., due to a refund agreement or policy violation).

### Sample Response [#sample-response-2]

```json
{
  "data": {
    "cancelSubscription": {
      "errors": [],
      "subscription": {
        "id": "1af2d4fc-1bfb-4e03-a11d-6254bf175adb",
        "planId": "sub_id_12345",
        "startAt": 1745561281,
        "endAt": 1748153281,
        "isCanceling": true,
        "state": "active",
        "user": {
          "id": "abaed4c4-4d48-4118-a3e8-34d89d540335",
          "name": "Student",
          "email": "student@example.com"
        }
      }
    }
  }
}
```

### Common Errors [#common-errors-2]

| Error                             | Description                                                                                                                           |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `Subscription not found`          | The specified subscription ID does not exist                                                                                          |
| `Subscription already cancelled`  | The subscription is already in a cancelled state                                                                                      |
| `Subscription is not cancellable` | The subscription cannot be cancelled. This applies to lifetime subscriptions which represent one-time purchases with permanent access |


---

# Assignments Query (https://docs.loopwise.com/api/queries/assignments)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Assignments API allows you to retrieve information about assignments in your school. You can list all assignments, get details for a specific assignment, and access related data like student submissions and grades.

## Available Queries [#available-queries]

### `assignments` [#assignments]

Returns a paginated list of assignments for the school.

**Parameters:**

| Parameter | Type             | Description                                       |
| --------- | ---------------- | ------------------------------------------------- |
| `first`   | Int              | Number of items to return (default: 20, max: 100) |
| `after`   | String           | Cursor for pagination                             |
| `filter`  | AssignmentFilter | Filter criteria (see [Filtering](#filtering))     |

**Returns:**

* Connection object with:
  * `nodes`: Array of Assignment objects
  * `pageInfo`: Pagination metadata

**Example:**

```graphql
query {
  assignments(first: 10) {
    nodes {
      id
      title
      description
      dueDate
      pointsPossible
      course {
        id
        name
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

### `assignment` [#assignment]

Returns a single assignment by ID.

**Parameters:**

| Parameter | Type    | Description                         |
| --------- | ------- | ----------------------------------- |
| `id`      | String! | The ID of the assignment (required) |

**Returns:**

* Assignment object or null if not found

**Example:**

```graphql
query {
  assignment(id: "assignment-123") {
    id
    title
    description
    dueDate
    pointsPossible
    course {
      id
      name
    }
    submissions {
      nodes {
        id
        student {
          id
          name
        }
        submittedAt
        grade
      }
    }
  }
}
```

## Assignment Object [#assignment-object]

The Assignment object contains the following fields:

| Field            | Type                 | Description                                   |
| ---------------- | -------------------- | --------------------------------------------- |
| `id`             | String               | Unique identifier                             |
| `title`          | String               | Assignment title                              |
| `description`    | String               | Assignment description                        |
| `dueDate`        | DateTime             | When the assignment is due                    |
| `pointsPossible` | Float                | Maximum points possible                       |
| `isPublished`    | Boolean              | Whether the assignment is visible to students |
| `createdAt`      | DateTime             | When the assignment was created               |
| `updatedAt`      | DateTime             | When the assignment was last updated          |
| `course`         | Course               | The course this assignment belongs to         |
| `submissions`    | SubmissionConnection | Paginated list of student submissions         |

## Submission Object [#submission-object]

The Submission object contains the following fields:

| Field         | Type             | Description                            |
| ------------- | ---------------- | -------------------------------------- |
| `id`          | String           | Unique identifier                      |
| `student`     | Student          | The student who submitted              |
| `assignment`  | Assignment       | The assignment this submission is for  |
| `submittedAt` | DateTime         | When the submission was made           |
| `grade`       | Float            | Points awarded (null if not graded)    |
| `feedback`    | String           | Teacher feedback                       |
| `attachments` | \[Attachment]    | Attached files                         |
| `status`      | SubmissionStatus | Status (SUBMITTED, GRADED, LATE, etc.) |

## Filtering [#filtering]

The `assignments` query accepts a `filter` parameter of type `AssignmentFilter`. This allows you to narrow down results based on various criteria.

### Available Filters [#available-filters]

| Filter Field  | Type           | Description                                  |
| ------------- | -------------- | -------------------------------------------- |
| `id`          | IDFilter       | Filter by assignment ID                      |
| `title`       | StringFilter   | Filter by assignment title                   |
| `description` | StringFilter   | Filter by assignment description             |
| `dueDate`     | DateTimeFilter | Filter by due date                           |
| `courseId`    | IDFilter       | Filter by course ID                          |
| `isPublished` | Boolean        | Filter for published/unpublished assignments |
| `createdAt`   | DateTimeFilter | Filter by creation date                      |

### Filter Examples [#filter-examples]

**Find assignments due in the next week:**

```graphql
query {
  assignments(
    filter: {
      dueDate: {
        after: "2023-09-01T00:00:00Z",
        before: "2023-09-08T23:59:59Z"
      }
    }
  ) {
    nodes {
      id
      title
      dueDate
      course {
        id
        name
      }
    }
  }
}
```

**Find assignments for a specific course:**

```graphql
query {
  assignments(
    filter: {
      courseId: { equals: "course-123" }
    }
  ) {
    nodes {
      id
      title
      dueDate
    }
  }
}
```

**Search for assignments by title:**

```graphql
query {
  assignments(
    filter: {
      title: { contains: "Midterm" }
    }
  ) {
    nodes {
      id
      title
      dueDate
    }
  }
}
```


---

# Consulting Queries (https://docs.loopwise.com/api/queries/consulting)



> **Endpoint and authentication.** All admin queries live on `POST /admin/graphql` — **not** the `/graphql` endpoint, which is the public school API. Authenticate with an `sk_live_…` key in the `X-Teachify-API-Key` header. All consulting queries require the `courses:read` scope.

## Overview [#overview]

The Consulting API exposes:

* **Consulting services** — coaching/consulting offerings attached to a course
* **Consulting meetings** — individual time slots booked under a service

Both resources support paginated list queries with filters, plus singular lookups by ID.

## Available Queries [#available-queries]

| Query                        | Returns                       | Description                                                                 |
| ---------------------------- | ----------------------------- | --------------------------------------------------------------------------- |
| `consultingServices(filter)` | `AdminConsultingServicePage!` | Paginated list of consulting services                                       |
| `consultingService(id)`      | `AdminConsultingService`      | Single service by ID; `null` if not found                                   |
| `consultingMeetings(filter)` | `AdminConsultingMeetingPage!` | Paginated list of meetings under consulting services                        |
| `consultingMeeting(id)`      | `AdminConsultingMeeting`      | Single meeting by ID; `null` if not found or not under a consulting service |

***

## consultingServices [#consultingservices]

Returns a paginated list of consulting services for the school. Ordered by `createdAt DESC, id DESC`.

### Filter Parameters (`AdminConsultingServiceFilter`) [#filter-parameters-adminconsultingservicefilter]

| Field       | Type      | Description                                                                                      |
| ----------- | --------- | ------------------------------------------------------------------------------------------------ |
| `courseId`  | `String`  | Filter by parent course ID                                                                       |
| `slug`      | `String`  | Exact slug match (school-scoped)                                                                 |
| `published` | `Boolean` | Filter by published flag. Checks the boolean column directly, not the time-gated effective state |
| `keyword`   | `String`  | Case-insensitive substring match against `name` or `slug`                                        |

### Example [#example]

```graphql
query ConsultingServices {
  consultingServices(filter: { published: true, keyword: "coaching" }) {
    nodes {
      id
      name
      slug
      published
      publishedAt
      courseId
      lecturerId
      lecturer {
        id
        name
      }
      effectiveTimezone
      meetingCount(state: available)
      tags
      createdAt
      updatedAt
    }
    currentPage
    totalPages
    hasNextPage
  }
}
```

### AdminConsultingService Fields [#adminconsultingservice-fields]

| Field                 | Type            | Description                                                                                                                    |
| --------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `id`                  | `String!`       |                                                                                                                                |
| `name`                | `String!`       | Display name                                                                                                                   |
| `slug`                | `String!`       | URL-friendly identifier (school-scoped)                                                                                        |
| `description`         | `String`        |                                                                                                                                |
| `published`           | `Boolean!`      | Whether the service is marked as published                                                                                     |
| `publishedAt`         | `Int`           | Unix timestamp; `null` if never published                                                                                      |
| `tags`                | `[String!]`     | Tag list stored in settings JSON                                                                                               |
| `backgroundColor`     | `String`        | UI background color (hex)                                                                                                      |
| `ratingFormId`        | `String`        | ID of the linked feedback form, if any                                                                                         |
| `courseId`            | `String`        | Parent course ID. Resolve details via the `courses` admin query                                                                |
| `lecturerId`          | `String`        | Assigned lecturer ID                                                                                                           |
| `lecturer`            | `AdminLecturer` | Assigned lecturer object (preferred over `lecturerId` for one-shot fetches)                                                    |
| `effectiveTimezone`   | `String!`       | IANA timezone (e.g. `Asia/Taipei`). Use when converting local datetimes to Unix timestamps for meeting `startedAt` / `endedAt` |
| `meetingCount(state)` | `Int!`          | Number of undiscarded meetings under this service, optionally filtered by AASM state                                           |
| `discardedAt`         | `Int`           | Unix timestamp; non-null when soft-deleted                                                                                     |
| `createdAt`           | `Int!`          | Unix timestamp                                                                                                                 |
| `updatedAt`           | `Int!`          | Unix timestamp                                                                                                                 |

***

## consultingService [#consultingservice]

Returns a single consulting service by ID, scoped to the current school. Returns `null` if not found or not in this school.

### Example [#example-1]

```graphql
query ConsultingService {
  consultingService(id: "35a72dba-c3cc-4a06-b7eb-d784d010386e") {
    id
    name
    slug
    effectiveTimezone
    meetingCount(state: scheduled)
    lecturer {
      id
      name
    }
  }
}
```

***

## consultingMeetings [#consultingmeetings]

Returns a paginated list of meetings under the school's consulting services. Ordered by `startedAt DESC, id DESC`.

### Filter Parameters (`AdminConsultingMeetingFilter`) [#filter-parameters-adminconsultingmeetingfilter]

| Field           | Type           | Description                                                                                                                                                     |
| --------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `serviceId`     | `String`       | Filter by parent `ConsultingService` ID                                                                                                                         |
| `lecturerId`    | `String`       | Filter by assigned lecturer ID                                                                                                                                  |
| `hostUserId`    | `String`       | Filter by the hosting user (owner or teaching assistant) recorded as the meeting's host. Use this — not `lecturerId` — to find slots a given host actually runs |
| `state`         | `MeetingState` | AASM state: `available`, `scheduled`, or `canceled`                                                                                                             |
| `startedAfter`  | `Int`          | Unix timestamp; matches meetings with `startedAt >= value`                                                                                                      |
| `startedBefore` | `Int`          | Unix timestamp; matches meetings with `startedAt <= value`                                                                                                      |

### Example [#example-2]

```graphql
query ConsultingMeetings {
  consultingMeetings(filter: {
    serviceId: "35a72dba-c3cc-4a06-b7eb-d784d010386e"
    state: scheduled
    startedAfter: 1747200000
  }) {
    nodes {
      id
      title
      state
      startedAt
      endedAt
      serviceId
      lecturerId
      hostUserId
      hostEmail
      hostingType
      joinUrl
      maxAttendeeCapacity
      attendeeCount
      attendees {
        id
        email
        name
      }
    }
    currentPage
    totalPages
    hasNextPage
  }
}
```

### AdminConsultingMeeting Fields [#adminconsultingmeeting-fields]

| Field                 | Type            | Description                                                                                                                                                                      |
| --------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                  | `String!`       |                                                                                                                                                                                  |
| `title`               | `String`        | Meeting title                                                                                                                                                                    |
| `description`         | `String`        |                                                                                                                                                                                  |
| `state`               | `String!`       | AASM state: `available`, `scheduled`, `canceled`                                                                                                                                 |
| `startedAt`           | `Int`           | Unix timestamp                                                                                                                                                                   |
| `endedAt`             | `Int`           | Unix timestamp                                                                                                                                                                   |
| `serviceId`           | `String`        | Parent `ConsultingService` ID. Resolve details via `consultingService(id)`                                                                                                       |
| `lecturerId`          | `String`        | Lecturer **profile** id (slug, URL routing, slot-overlap detection). NOT the person who runs the session — see `hostUserId`. Resolve via the `lecturers` admin query             |
| `hostUserId`          | `String`        | User id (school owner or teaching assistant) of the person who actually hosts the meeting. Sourced from `meetings.hosts[0].id`; `null` on legacy rows where no host was selected |
| `hostEmail`           | `String`        | Zoom license email used when `hostingType: zoom`. `null` for non-Zoom hosting types or when the school had no Zoom license configured                                            |
| `hostingType`         | `String`        | `zoom`, `live_session`, or `custom`                                                                                                                                              |
| `hostingId`           | `String`        | External hosting platform meeting ID (e.g. Zoom meeting ID)                                                                                                                      |
| `joinUrl`             | `String`        | Join URL: the one Zoom returned for `zoom`, the one typed in for `custom`                                                                                                        |
| `maxAttendeeCapacity` | `Int`           | Maximum students allowed; `null` or `0` means unlimited                                                                                                                          |
| `price`               | `Float`         |                                                                                                                                                                                  |
| `currency`            | `String!`       |                                                                                                                                                                                  |
| `attendeeCount`       | `Int!`          | Current number of enrolled students                                                                                                                                              |
| `attendees`           | `[AdminUser!]!` | Enrolled students                                                                                                                                                                |
| `discardedAt`         | `Int`           | Unix timestamp; non-null when soft-deleted                                                                                                                                       |
| `createdAt`           | `Int!`          | Unix timestamp                                                                                                                                                                   |
| `updatedAt`           | `Int!`          | Unix timestamp                                                                                                                                                                   |

### Meeting States [#meeting-states]

| State       | Meaning                                                       |
| ----------- | ------------------------------------------------------------- |
| `available` | Slot is open; no students enrolled (or all have been removed) |
| `scheduled` | At least one student has been confirmed for this slot         |
| `canceled`  | Slot has been canceled                                        |

***

## consultingMeeting [#consultingmeeting]

Returns a single consulting meeting by ID, scoped to the current school. Returns `null` if not found, not in this school, or not under a consulting service.

### Example [#example-3]

```graphql
query ConsultingMeeting {
  consultingMeeting(id: "0186b768-c0c0-4d75-8fb7-7fee0b3ee9c1") {
    id
    state
    startedAt
    endedAt
    attendeeCount
    attendees {
      id
      email
      name
    }
  }
}
```

***

## meetingHosts [#meetinghosts]

Returns the school owner plus all undiscarded teaching assistants — the exact user pool accepted by `hostUserId` on `bulkCreateConsultingMeetings` and `updateConsultingMeeting`. Use this **before** writing a meeting to populate UI host pickers or to pre-validate, rather than relying on the [`MEETING-012` `valid_options=` recovery suffix](/docs/api/mutations/consulting#bulk-create-consulting-meetings) after a bad write.

Each row carries an explicit `role` discriminator (`owner` or `teaching_assistant`) — **filter by `role` rather than relying on response ordering** when you only want one or the other. The owner is deduplicated to a single `role: owner` row when they also hold the teaching\_assistant role; TAs are returned in `user.createdAt` ascending order so you can pick the most-tenured by index.

### Example [#example-4]

```graphql
query MeetingHosts {
  meetingHosts {
    role
    user {
      id
      name
      email
      createdAt   # use to pick "most senior TA" when needed
    }
  }
}
```

### AdminMeetingHost Fields [#adminmeetinghost-fields]

| Field  | Type                    | Description                                                     |
| ------ | ----------------------- | --------------------------------------------------------------- |
| `role` | `AdminMeetingHostRole!` | `owner` (the school owner) or `teaching_assistant`              |
| `user` | `AdminUser!`            | The user record. Pass `user.id` as `hostUserId` on the mutation |

### Notes [#notes]

* Scope: school-wide. Returns a non-paginated array — the pool is intentionally small (1 owner + N TAs).
* The admin API does NOT gate on the school admin UI's `:learning_center` feature flag; TAs are always returned regardless of the flag's state. The school admin UI may show a narrower pool.
* Required OAuth scope: `courses:read` (the same scope as the other consulting queries).
* **Empty result** means the school has no eligible hosts (owner was soft-deleted AND no teaching assistants exist). Consulting meeting mutations will fail `MEETING-012` with empty `valid_options=` until either the owner is restored or a teaching assistant is invited via the school admin UI.

***

## zoomHosts [#zoomhosts]

Returns the Zoom license seats configured under the school's active Zoom integration — the exact set of values accepted by `hostEmail` on consulting meeting mutations when `hostingType: zoom`. Use this **before** writing a Zoom meeting, instead of relying on the [`MEETING-011` `valid_options=` recovery suffix](/docs/api/mutations/consulting#bulk-create-consulting-meetings) after a bad write.

Returns an empty list when the school has no active Zoom integration (the same precondition that `MEETING-009` enforces on the mutation) or when the integration has no license metadata recorded. Order matches Settings → Integrations → Zoom in the admin UI.

### Example [#example-5]

```graphql
query ZoomHosts {
  zoomHosts {
    email
    name
  }
}
```

### AdminZoomHost Fields [#adminzoomhost-fields]

| Field   | Type      | Description                                                             |
| ------- | --------- | ----------------------------------------------------------------------- |
| `email` | `String!` | Zoom license email. Pass as `hostEmail` on consulting meeting mutations |
| `name`  | `String`  | Display name configured for this license seat; `null` if not set        |

### Notes [#notes-1]

* Scope: school-wide. Required OAuth scope: `courses:read`.
* Result reflects only the **active** Zoom integration. Inactive integrations are intentionally hidden so callers can't accidentally provision against a disabled seat.


---

# Coupons Query (https://docs.loopwise.com/api/queries/coupons)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Coupon API allows you to retrieve information about discount coupons in your school. Coupons enable you to offer promotional discounts on your courses, events, and other products. This API provides access to coupon details, usage statistics, and filtering capabilities.

## Available Queries [#available-queries]

### `coupons` [#coupons]

Returns a paginated list of coupons for the authenticated school.

**Parameters:**

| Parameter | Type              | Description                                     |
| --------- | ----------------- | ----------------------------------------------- |
| `filter`  | AdminCouponFilter | Filter criteria (see [Filtering](#filtering))   |
| `page`    | Int               | Page number for pagination                      |
| `perPage` | Int               | Number of items per page (default: 20, max: 50) |
| `limit`   | Int               | Alternative to perPage                          |

**Returns:**

* AdminCouponPage object with:
  * `nodes`: Array of AdminCoupon objects
  * `currentPage`: Current page number
  * `hasNextPage`: Whether there are more pages
  * `hasPreviousPage`: Whether there are previous pages
  * `nodesCount`: Total number of items in the current page
  * `totalPages`: Total number of pages

**Example:**

```graphql
query {
  coupons(
    filter: {
      active: true,
      code: { like: "SUMMER%" }
    },
    page: 1,
    perPage: 10
  ) {
    nodes {
      id
      name
      code
      amount
      couponType
      active
      appliedCount
      expiredAt
    }
    currentPage
    hasNextPage
    hasPreviousPage
    nodesCount
    totalPages
  }
}
```

## AdminCoupon Object [#admincoupon-object]

The AdminCoupon object contains the following fields based on the schema:

| Field             | Type     | Description                                                           |
| ----------------- | -------- | --------------------------------------------------------------------- |
| `id`              | String!  | Unique identifier                                                     |
| `name`            | String!  | Name of the coupon                                                    |
| `code`            | String!  | Unique coupon code that users enter to apply the discount             |
| `description`     | String   | Optional description of the coupon                                    |
| `amount`          | Float!   | Discount amount (in currency units or percentage based on couponType) |
| `couponType`      | String!  | Type of discount: "fixed\_amount" or "percentage"                     |
| `currency`        | String!  | Currency code (e.g., USD, EUR) in ISO 4217 format                     |
| `currencySymbol`  | String!  | Currency symbol (e.g., $, €, £, ¥)                                    |
| `active`          | Boolean! | Whether the coupon is currently active                                |
| `singleProduct`   | Boolean! | Whether coupon applies to a single product only                       |
| `appliedCount`    | Int!     | Number of times the coupon has been used                              |
| `redemptionLimit` | Int      | Maximum number of times the coupon can be used (null for unlimited)   |
| `startedAt`       | Int      | When the coupon becomes valid                                         |
| `expiredAt`       | Int      | When the coupon expires                                               |
| `state`           | String!  | Current state of the coupon                                           |
| `items`           | \[JSON!] | Related products the coupon can be applied to                         |
| `createdAt`       | Int!     | When the coupon was created                                           |
| `updatedAt`       | Int!     | When the coupon was last updated                                      |

## Filtering [#filtering]

The `coupons` query supports filtering through the `filter` parameter. The following filter fields are available:

| Filter Field    | Type           | Description                                       |
| --------------- | -------------- | ------------------------------------------------- |
| `id`            | StringOperator | Filter by coupon ID                               |
| `code`          | StringOperator | Filter by coupon code                             |
| `name`          | StringOperator | Filter by coupon name                             |
| `couponType`    | StringOperator | Filter by coupon type (fixed\_amount, percentage) |
| `state`         | StringOperator | Filter by coupon state                            |
| `active`        | Boolean        | Filter for active/inactive coupons                |
| `singleProduct` | Boolean        | Filter for single product coupons                 |

### StringOperator Filters [#stringoperator-filters]

String fields can be filtered using the following operators:

| Operator | Description                       | Example                                        |
| -------- | --------------------------------- | ---------------------------------------------- |
| `eq`     | Equal to                          | `{ code: { eq: "SUMMER2023" } }`               |
| `neq`    | Not equal to                      | `{ code: { neq: "SUMMER2023" } }`              |
| `in`     | In a list of values               | `{ code: { in: ["SUMMER2023", "FALL2023"] } }` |
| `nin`    | Not in a list of values           | `{ code: { nin: ["EXPIRED2022"] } }`           |
| `like`   | Pattern matching (case-sensitive) | `{ code: { like: "SUMMER%" } }`                |

### Filter Examples [#filter-examples]

**Find active percentage-based coupons:**

```graphql
query {
  coupons(
    filter: {
      active: true,
      couponType: { eq: "percentage" }
    }
  ) {
    nodes {
      id
      name
      code
      amount
      appliedCount
    }
  }
}
```

**Find coupons by name pattern:**

```graphql
query {
  coupons(
    filter: {
      name: { like: "Summer%" }
    }
  ) {
    nodes {
      id
      name
      code
      amount
      couponType
    }
  }
}
```

## Relationships [#relationships]

The Coupon API indirectly relates to:

* **Products**: Coupons can be applied to one or more products (courses, events, etc.)
* **Payments**: Payments track the application of coupons as adjustments
* **Users**: Users apply coupons during checkout

## Detailed Query Structure [#detailed-query-structure]

Below is a comprehensive view of fields available in the coupons query based on the schema:

```graphql
query {
  coupons(
    filter: {
      id: { eq: "coupon_123" }             # Filter by ID (StringOperator)
      code: { like: "WELCOME%" }           # Filter by code pattern (StringOperator)
      name: { like: "Welcome%" }           # Filter by name pattern (StringOperator)
      couponType: { eq: "percentage" }     # Filter by coupon type (StringOperator)
      state: { eq: "active" }              # Filter by state (StringOperator)
      active: true                         # Filter for active coupons (Boolean)
      singleProduct: false                 # Filter for multi-product coupons (Boolean)
    },
    page: 1,                               # Page number (Int)
    perPage: 20                            # Items per page (Int)
  ) {
    nodes {
      id                                   # Unique identifier (String!)
      name                                 # Coupon name (String!)
      code                                 # Coupon code (String!)
      description                          # Optional description (String)

      # Discount information
      amount                               # Discount amount (Float!)
      couponType                           # Type of discount: fixed_amount or percentage (String!)
      currency                             # Currency code (String!)
      currencySymbol                       # Currency symbol (String!)

      # Status fields
      active                               # Whether the coupon is active (Boolean!)
      singleProduct                        # Whether coupon applies to single product only (Boolean!)

      # Usage statistics
      appliedCount                         # Number of times used (Int!)
      redemptionLimit                      # Maximum usage limit (Int)

      # Time-related fields
      startedAt                            # When the coupon becomes valid (Int)
      expiredAt                            # When the coupon expires (Int)
      state                                # Current state (String!)
      createdAt                            # Creation timestamp (Int!)
      updatedAt                            # Last update timestamp (Int!)

      # Related items
      items                                # Products the coupon can be applied to ([JSON!])
    }

    # Pagination information
    currentPage                            # Current page number (Int!)
    hasNextPage                            # Whether there are more pages (Boolean!)
    hasPreviousPage                        # Whether there are previous pages (Boolean!)
    nodesCount                             # Number of items on current page (Int!)
    totalPages                             # Total number of pages (Int!)
  }
}
```


---

# Courses Query (https://docs.loopwise.com/api/queries/courses)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Courses API allows you to retrieve information about courses in your school. You can list all courses, get details for a specific course, and access related data.

## Available Queries [#available-queries]

### `courses` [#courses]

Returns a paginated list of courses for the school.

**Parameters:**

| Parameter | Type         | Description                                     |
| --------- | ------------ | ----------------------------------------------- |
| `filter`  | CourseFilter | Filter criteria (see [Filtering](#filtering))   |
| `page`    | Int          | Page number for pagination                      |
| `perPage` | Int          | Number of items per page (default: 20, max: 50) |
| `limit`   | Int          | Alternative to perPage                          |

**Returns:**

* CoursePage object with:
  * `nodes`: Array of Course objects
  * `currentPage`: Current page number
  * `hasNextPage`: Whether there are more pages
  * `hasPreviousPage`: Whether there are previous pages
  * `nodesCount`: Total number of items in the current page
  * `totalPages`: Total number of pages

**Example:**

```graphql
query {
  courses(
    page: 1
    perPage: 10
  ) {
    nodes {
      id
      name
      description
      slug
      featured
    }
    currentPage
    hasNextPage
    totalPages
  }
}
```

## Course Object [#course-object]

The Course object contains the following fields based on the schema:

| Field            | Type               | Description                                                       |
| ---------------- | ------------------ | ----------------------------------------------------------------- |
| `id`             | String!            | Unique identifier                                                 |
| `name`           | String!            | Course name                                                       |
| `slug`           | String!            | URL-friendly identifier                                           |
| `description`    | String             | Course description                                                |
| `image`          | String             | Course image URL                                                  |
| `featured`       | Boolean!           | Whether the course is featured                                    |
| `invisible`      | Boolean!           | Whether the course is hidden                                      |
| `publishedAt`    | Int                | Unix timestamp when the course was published                      |
| `courseType`     | String!            | Possible values: paid, public\_access, free\_redeem or pre\_order |
| `contentType`    | String!            | Content type of the course                                        |
| `template`       | String!            | Possible values: default, video\_on\_top                          |
| `playerTheme`    | String!            | Possible values: classic, theater                                 |
| `sections`       | \[Section!]!       | List of course sections                                           |
| `categories`     | \[Category!]       | List of course categories                                         |
| `tags`           | \[String!]         | List of course tags                                               |
| `lecturer`       | Lecturer           | Primary lecturer                                                  |
| `lecturers`      | \[Lecturer!]       | All lecturers for the course                                      |
| `assignments`    | \[Assignment!]     | List of course assignments                                        |
| `totalHours`     | Float              | Total duration of the course in hours                             |
| `lecturesCount`  | Int                | Number of lectures in the course                                  |
| `courseFeatures` | CourseFeatures     | Additional course features                                        |
| `preOrderInfo`   | CoursePreOrderInfo | Pre-order information if applicable                               |
| `rating`         | Rating             | Course rating information                                         |
| `faqSections`    | \[FaqSection!]     | FAQ sections for the course                                       |
| `plans`          | \[CurriculumPlan!] | Available pricing plans for the course                            |
| `users`          | UserPage           | Paginated list of users for this course                           |

## Users Field [#users-field]

The UserPage object includes user information through the `user` field. This returns a paginated list of users associated with the course.

* UserPage object with:
  * `nodes`: Array of Course objects
  * `currentPage`: Current page number
  * `hasNextPage`: Whether there are more pages
  * `hasPreviousPage`: Whether there are previous pages
  * `nodesCount`: Total number of items in the current page
  * `totalPages`: Total number of pages

### User Information in Users [#user-information-in-users]

Each subscription includes user information through the `user` field:

| Field   | Type    | Description              |
| ------- | ------- | ------------------------ |
| `id`    | String! | User's unique identifier |
| `name`  | String  | User's full name         |
| `email` | String  | User's email address     |

### Users Filter Parameters [#users-filter-parameters]

| Parameter | Type           | Description            |
| --------- | -------------- | ---------------------- |
| `id`      | StringOperator | Filter by user ID      |
| `email`   | StringOperator | Filter by user's email |
| `name`    | StringOperator | Filter by user's name  |

**Example with filtered users:**

```graphql
query {
  courses(
    page: 1
    perPage: 10
  ) {
    nodes {
      id
      name
      description
      slug
      featured

      users(
        filter: {
          email: { eq: "student@example.com" }
        }
      ) {
        nodes {
          id
          name
        }
      }
    }
    currentPage
    hasNextPage
    totalPages
  }
}
```

## Detailed Query Structure [#detailed-query-structure]

Below is a comprehensive view of fields available in the courses query based on the schema:

```graphql
query {
  courses(
    filter: {
      id: { eq: "course-123" }
      tags: ["beginner"]
      featured: true
      state: { eq: "published" }
    }
    page: 1
    perPage: 20
  ) {
    nodes {
      id                          # Unique identifier (String!)
      name                        # Course name (String!)
      slug                        # URL-friendly identifier (String!)
      description                 # Course description (String)
      image                       # Course image URL (String)

      # Course settings
      featured                    # Whether the course is featured (Boolean!)
      invisible                   # Whether the course is hidden (Boolean!)
      publishedAt                 # When the course was published (Int)
      courseType                  # Type of course (String!)
      contentType                 # Content type (String!)
      template                    # Template style (String!)
      playerTheme                 # Player theme (String!)

      # Course content
      sections {                  # Course sections ([Section!]!)
        id
        title
        position
        duration
        lectures {                # Lectures within sections
          id
          title
          position
          duration
          isFreePreview
          isLocked
        }
      }

      # Categorization
      categories {                # Course categories ([Category!])
        id
        name
        slug
      }
      tags                        # Course tags ([String!])

      # Instructors
      lecturer {                  # Primary lecturer (Lecturer)
        id
        name
        avatar
        slug
      }
      lecturers {                 # All lecturers ([Lecturer!])
        id
        name
        avatar
        slug
      }

      # Assignments
      assignments {               # Course assignments ([Assignment!])
        id
        name
        description
        dueAt
      }

      # Course metrics
      totalHours                  # Total duration in hours (Float)
      lecturesCount               # Number of lectures (Int)

      # Additional information
      courseFeatures {            # Course features (CourseFeatures)
        studentsCount
        lecturesCount
        videoTotalHours
        audioTotalHours
        downloadableResourcesCount
        certificateOfCompletion
        lifetimeAccess
        moneyBackGuarantee
      }

      # Pre-order information
      preOrderInfo {              # Pre-order details (CoursePreOrderInfo)
        startedAt
        endedAt
        releasedAt
        buyersGoal
        buyersPledged
        moneyGoal
        moneyPledged
        goalType
        achievedPercentage
      }

      # Ratings
      rating {                    # Course rating (Rating)
        average
        total
      }

      # FAQ sections
      faqSections {               # FAQ sections ([FaqSection!])
        id
        name
        position
        faqContents {
          id
          title
          body
          position
          isPublished
        }
      }

      # Pricing plans
      plans {                     # Pricing plans ([CurriculumPlan!])
        id
        name
        description
        amount
        compareAtPrice
        currency
        currencySymbol
        planType
        position
        quantity
        interval
        intervalCount
        groupSize
        displayRemainingCount
        displaySoldCount
        remainingItemsCount
        soldItemsCount
        repeatPurchasable
        endedAt
        releaseAt
        coverPhoto
        createdAt
      }

      # Users                   # Users (UserPage)
      users (
        filter: {
          email: { eq: "student@example.com" }
        }
      ) {
        nodes {
          id
          name
          email
        }
      }
    }

    # Pagination information
    currentPage                   # Current page number (Int!)
    hasNextPage                   # Whether there are more pages (Boolean!)
    hasPreviousPage               # Whether there are previous pages (Boolean!)
    nodesCount                    # Number of items in current page (Int!)
    totalPages                    # Total number of pages (Int!)
  }
}
```

## Plans Field [#plans-field]

The `plans` field returns an array of CurriculumPlan objects representing the available pricing plans for the course. Each plan defines how students can access the course (free, one-time purchase, subscription, etc.).

### CurriculumPlan Fields [#curriculumplan-fields]

| Field                   | Type     | Description                                                                                                               |
| ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------- |
| `id`                    | String!  | Unique identifier for the plan                                                                                            |
| `name`                  | String   | Display name of the pricing plan                                                                                          |
| `description`           | String   | Detailed description of what's included                                                                                   |
| `amount`                | Float    | Price amount for the plan                                                                                                 |
| `compareAtPrice`        | Int      | Original price before discount/sale                                                                                       |
| `currency`              | String!  | ISO currency code (e.g., TWD, USD)                                                                                        |
| `currencySymbol`        | String!  | Currency symbol (e.g., $, €, £)                                                                                           |
| `planType`              | String!  | Plan type: free, one\_time\_purchase, subscription, pre\_order, group\_buy, fixed\_date, specific\_length, web3\_discount |
| `position`              | Int      | Display order position                                                                                                    |
| `quantity`              | Int      | Available quantity for purchase                                                                                           |
| `interval`              | String   | Billing interval for subscription plans                                                                                   |
| `intervalCount`         | Int      | Number of intervals between billing                                                                                       |
| `groupSize`             | Int      | Required group size for group\_buy plans                                                                                  |
| `displayRemainingCount` | Boolean  | Whether to show remaining quantity                                                                                        |
| `displaySoldCount`      | Boolean  | Whether to show sold count                                                                                                |
| `remainingItemsCount`   | Int      | Number of items remaining                                                                                                 |
| `soldItemsCount`        | Int      | Number of items sold                                                                                                      |
| `repeatPurchasable`     | Boolean! | Whether plan can be purchased multiple times                                                                              |
| `endedAt`               | Int      | Unix timestamp when plan expires                                                                                          |
| `releaseAt`             | Int      | Unix timestamp when plan becomes available                                                                                |
| `coverPhoto`            | String   | Plan cover image URL                                                                                                      |
| `createdAt`             | Int!     | Unix timestamp when plan was created                                                                                      |

**Example with plans:**

```graphql
query {
  courses {
    nodes {
      id
      name
      plans {
        id
        name
        description
        amount
        currencySymbol
        planType
        remainingItemsCount
        soldItemsCount
      }
    }
  }
}
```

## Filtering [#filtering]

The `courses` query accepts a `filter` parameter of type `CourseFilter`. This allows you to narrow down results based on various criteria.

### Available Filters [#available-filters]

| Filter Field     | Type           | Description                                                               |
| ---------------- | -------------- | ------------------------------------------------------------------------- |
| `id`             | StringOperator | Filter by course ID                                                       |
| `tags`           | \[String!]     | Filter by course tags                                                     |
| `categoryIds`    | \[String!]     | Filter by category IDs                                                    |
| `categorySlugs`  | \[String!]     | Filter by category slugs                                                  |
| `featured`       | Boolean        | Filter for featured courses                                               |
| `state`          | StringOperator | Filter by course state (unpublished, published)                           |
| `preOrderState`  | String         | Filter by pre-order state (upcoming, started, to\_be\_released, released) |
| `hasAssignments` | Boolean        | Filter for courses with published assignments                             |

### StringOperator [#stringoperator]

The `StringOperator` used in filters has these operations:

| Operation | Description                                                          |
| --------- | -------------------------------------------------------------------- |
| `eq`      | Equal to                                                             |
| `neq`     | Not equal to                                                         |
| `in`      | In a list of values                                                  |
| `nin`     | Not in a list of values                                              |
| `like`    | Match text values against a pattern using wildcards (case-sensitive) |

### Filter Examples [#filter-examples]

**Find courses with specific tags:**

```graphql
query {
  courses(
    filter: {
      tags: ["beginner", "programming"]
    }
  ) {
    nodes {
      id
      name
      tags
    }
  }
}
```

**Find featured courses in specific categories:**

```graphql
query {
  courses(
    filter: {
      featured: true,
      categorySlugs: ["programming", "web-development"]
    }
  ) {
    nodes {
      id
      name
      featured
      categories {
        name
        slug
      }
    }
  }
}
```

**Find courses by ID:**

```graphql
query {
  courses(
    filter: {
      id: { eq: "course-123" }
    }
  ) {
    nodes {
      id
      name
    }
  }
}
```

**Find courses by state:**

```graphql
query {
  courses(
    filter: {
      state: { eq: "published" }
    }
  ) {
    nodes {
      id
      name
      publishedAt
    }
  }
}
```

**Find courses with multiple states:**

```graphql
query {
  courses(
    filter: {
      state: { in: ["published", "unpublished"] }
    }
  ) {
    nodes {
      id
      name
      publishedAt
    }
  }
}
```


---

# Events Query (https://docs.loopwise.com/api/queries/events)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Events API allows you to retrieve information about calendar events in your school. You can list all events, get details for a specific event, and filter events by date range, type, or associated courses.

## Available Queries [#available-queries]

### `events` [#events]

Returns a paginated list of events for the school.

**Parameters:**

| Parameter | Type        | Description                                       |
| --------- | ----------- | ------------------------------------------------- |
| `first`   | Int         | Number of items to return (default: 20, max: 100) |
| `after`   | String      | Cursor for pagination                             |
| `filter`  | EventFilter | Filter criteria (see [Filtering](#filtering))     |

**Returns:**

* Connection object with:
  * `nodes`: Array of Event objects
  * `pageInfo`: Pagination metadata

**Example:**

```graphql
query {
  events(first: 10) {
    nodes {
      id
      title
      description
      startTime
      endTime
      location
      eventType
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

### `event` [#event]

Returns a single event by ID.

**Parameters:**

| Parameter | Type    | Description                    |
| --------- | ------- | ------------------------------ |
| `id`      | String! | The ID of the event (required) |

**Returns:**

* Event object or null if not found

**Example:**

```graphql
query {
  event(id: "event-123") {
    id
    title
    description
    startTime
    endTime
    location
    eventType
    course {
      id
      name
    }
    attendees {
      id
      name
      email
    }
  }
}
```

## Event Object [#event-object]

The Event object contains the following fields:

| Field         | Type      | Description                                                                                                                                                                                                                                       |
| ------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`          | String    | Unique identifier                                                                                                                                                                                                                                 |
| `title`       | String    | Event title                                                                                                                                                                                                                                       |
| `description` | String    | Event description                                                                                                                                                                                                                                 |
| `startTime`   | DateTime  | Event start time                                                                                                                                                                                                                                  |
| `endTime`     | DateTime  | Event end time                                                                                                                                                                                                                                    |
| `location`    | String    | Physical or virtual location                                                                                                                                                                                                                      |
| `eventType`   | EventType | Type of event (see [Event Types](#event-types))                                                                                                                                                                                                   |
| `isAllDay`    | Boolean   | Whether the event is an all-day event                                                                                                                                                                                                             |
| `createdAt`   | DateTime  | When the event was created                                                                                                                                                                                                                        |
| `updatedAt`   | DateTime  | When the event was last updated                                                                                                                                                                                                                   |
| `course`      | Course    | Associated course (if applicable)                                                                                                                                                                                                                 |
| `attendees`   | \[User]   | List of event attendees                                                                                                                                                                                                                           |
| `metadata`    | JSON      | Custom external metadata as a JSON object of string key-value pairs, configured under Settings → Advanced → Product Custom Fields. Returns `null` when the school does not have the `external_metadata` feature enabled, and when nothing is set. |

## Event Types [#event-types]

The `eventType` field can have one of the following values:

| Type             | Description               |
| ---------------- | ------------------------- |
| `CLASS_SESSION`  | Regular class session     |
| `EXAM`           | Test or exam              |
| `ASSIGNMENT_DUE` | Assignment due date       |
| `SCHOOL_HOLIDAY` | School holiday or closure |
| `SPECIAL_EVENT`  | Special school event      |
| `STAFF_MEETING`  | Staff or faculty meeting  |
| `OTHER`          | Other event type          |

## Filtering [#filtering]

The `events` query accepts a `filter` parameter of type `EventFilter`. This allows you to narrow down results based on various criteria.

### Available Filters [#available-filters]

| Filter Field  | Type            | Description                    |
| ------------- | --------------- | ------------------------------ |
| `id`          | IDFilter        | Filter by event ID             |
| `title`       | StringFilter    | Filter by event title          |
| `description` | StringFilter    | Filter by event description    |
| `startTime`   | DateTimeFilter  | Filter by start time           |
| `endTime`     | DateTimeFilter  | Filter by end time             |
| `location`    | StringFilter    | Filter by location             |
| `eventType`   | EventTypeFilter | Filter by event type           |
| `courseId`    | IDFilter        | Filter by associated course ID |
| `isAllDay`    | Boolean         | Filter for all-day events      |

### Filter Examples [#filter-examples]

**Find events for a specific date range:**

```graphql
query {
  events(
    filter: {
      startTime: {
        between: ["2023-10-01T00:00:00Z", "2023-10-31T23:59:59Z"]
      }
    }
  ) {
    nodes {
      id
      title
      startTime
      endTime
    }
  }
}
```

**Find class sessions for a specific course:**

```graphql
query {
  events(
    filter: {
      eventType: { equals: CLASS_SESSION },
      courseId: { equals: "course-123" }
    }
  ) {
    nodes {
      id
      title
      startTime
      endTime
    }
  }
}
```

**Find upcoming exams:**

```graphql
query {
  events(
    filter: {
      eventType: { equals: EXAM },
      startTime: { after: "2023-09-01T00:00:00Z" }
    }
  ) {
    nodes {
      id
      title
      startTime
      course {
        id
        name
      }
    }
  }
}
```


---

# Loopwise Admin API Queries (https://docs.loopwise.com/api/queries)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Loopwise Admin API provides a variety of query operations to retrieve data from your school. This section documents all available queries, along with concepts like pagination and filtering that apply across multiple query types.

## Available Resources [#available-resources]

The API provides queries for the following resources:

* [**Courses**](./courses): Access course information
* [**Students**](./users): Retrieve student data
* [**Assignments**](./assignments): Get assignment details
* [**Events**](./events): Access school calendar events
* [**Coupons**](./coupons): Retrieve discount coupon information
* [**Membership Plans**](./membership-plans): Access subscription plan details
* [**Payments**](./payments): Query payment transactions and refunds
* [**Product Revenues**](./product-revenues): Per-product revenue analytics
* [**Subscriptions**](./subscriptions): Retrieve user subscription information
* [**Users**](./users): Retrieve user information

## Common Parameters [#common-parameters]

All queries accept the following common parameters:

| Parameter | Type   | Description                                       |
| --------- | ------ | ------------------------------------------------- |
| `first`   | Int    | Number of items to return (default: 20, max: 100) |
| `after`   | String | Cursor for pagination                             |

## Basic Example [#basic-example]

Here's a simple example of querying for school information:

```graphql
query {
  school {
    id
    name
    createdAt
  }
}
```

For more detailed examples and resource-specific queries, explore the resource pages linked above.

***

## Pagination [#pagination]

The Loopwise Admin API uses cursor-based pagination to efficiently handle large datasets. This approach allows you to retrieve data in manageable chunks while maintaining consistent results across requests.

### Pagination Structure [#pagination-structure]

All paginated responses follow a consistent structure:

```graphql
{
  "data": {
    "resourceName": {
      "nodes": [
        // Array of resource objects
      ],
      "pageInfo": {
        "hasNextPage": true,
        "endCursor": "cursor-string"
      }
    }
  }
}
```

The key components are:

* `nodes`: An array containing the requested resources for the current page
* `pageInfo`: Metadata about the current page and navigation
  * `hasNextPage`: Boolean indicating if more results exist beyond this page
  * `endCursor`: A string cursor that can be used to fetch the next page

### Pagination Parameters [#pagination-parameters]

When querying paginated resources, you can use these parameters:

| Parameter | Type   | Description                                       |
| --------- | ------ | ------------------------------------------------- |
| `first`   | Int    | Number of items to return (default: 20, max: 100) |
| `after`   | String | Cursor string from a previous query's `endCursor` |

### Pagination Example [#pagination-example]

#### Initial Query [#initial-query]

To fetch the first page of courses:

```graphql
query {
  courses(first: 10) {
    nodes {
      id
      name
      description
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

#### Subsequent Pages [#subsequent-pages]

To fetch the next page, use the `endCursor` from the previous response:

```graphql
query {
  courses(first: 10, after: "previous-end-cursor") {
    nodes {
      id
      name
      description
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

### JavaScript Pagination Example [#javascript-pagination-example]

Here's how to implement pagination in JavaScript:

```javascript
async function fetchAllCourses(apiKey) {
  const endpoint = 'https://teachify.io/admin/graphql';
  let hasNextPage = true;
  let after = null;
  let allCourses = [];

  while (hasNextPage) {
    const query = `
      query Courses($first: Int, $after: String) {
        courses(first: 25, after: $after) {
          nodes {
            id
            name
            description
          }
          pageInfo {
            hasNextPage
            endCursor
          }
        }
      }
    `;

    const response = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Teachify-API-Key': apiKey
      },
      body: JSON.stringify({
        query,
        variables: { first: 25, after }
      })
    });

    const result = await response.json();
    const { nodes, pageInfo } = result.data.courses;

    allCourses = [...allCourses, ...nodes];
    hasNextPage = pageInfo.hasNextPage;
    after = pageInfo.endCursor;

    console.log(`Fetched ${nodes.length} courses. Total so far: ${allCourses.length}`);
  }

  return allCourses;
}
```

### Pagination Best Practices [#pagination-best-practices]

1. **Use reasonable page sizes**: Request only what you need. Smaller page sizes (10-25 items) are better for interactive UIs, while larger sizes (50-100) may be more efficient for data processing.

2. **Always check `hasNextPage`**: Don't assume there are more pages based on the number of items returned.

3. **Store the `endCursor`**: Save the cursor between user interactions or application states to maintain pagination position.

4. **Handle empty results**: Your code should gracefully handle cases where no results are returned.

5. **Avoid fetching all pages at once**: For very large datasets, consider implementing "load more" or traditional page navigation rather than automatically loading all pages.

***

## Filtering [#filtering]

The Loopwise Admin API supports powerful filtering capabilities that allow you to narrow down query results to exactly what you need. Filtering is performed on the server side, which improves performance by reducing the amount of data transferred.

### Filter Structure [#filter-structure]

Filters are provided as input objects to queries. Each resource type has its own filter input type with fields specific to that resource. For example:

* `CourseFilter` for filtering courses
* `StudentFilter` for filtering students
* `AssignmentFilter` for filtering assignments

### Common Filter Types [#common-filter-types]

#### String Filters [#string-filters]

String fields typically support these filtering operations:

| Operation    | Description           | Example                            |
| ------------ | --------------------- | ---------------------------------- |
| `equals`     | Exact match           | `{ name: { equals: "Math 101" } }` |
| `contains`   | Contains substring    | `{ name: { contains: "Math" } }`   |
| `startsWith` | Starts with substring | `{ name: { startsWith: "Math" } }` |
| `endsWith`   | Ends with substring   | `{ name: { endsWith: "101" } }`    |

#### Number Filters [#number-filters]

Number fields support range operations:

| Operation | Description           | Example                                      |
| --------- | --------------------- | -------------------------------------------- |
| `equals`  | Exact match           | `{ enrollmentCount: { equals: 25 } }`        |
| `gt`      | Greater than          | `{ enrollmentCount: { gt: 20 } }`            |
| `gte`     | Greater than or equal | `{ enrollmentCount: { gte: 20 } }`           |
| `lt`      | Less than             | `{ enrollmentCount: { lt: 30 } }`            |
| `lte`     | Less than or equal    | `{ enrollmentCount: { lte: 30 } }`           |
| `between` | Between two values    | `{ enrollmentCount: { between: [20, 30] } }` |

#### Date Filters [#date-filters]

Date fields support similar operations to number fields:

| Operation | Description       | Example                                                    |
| --------- | ----------------- | ---------------------------------------------------------- |
| `equals`  | Exact date match  | `{ startDate: { equals: "2023-09-01" } }`                  |
| `before`  | Before date       | `{ startDate: { before: "2023-09-01" } }`                  |
| `after`   | After date        | `{ startDate: { after: "2023-09-01" } }`                   |
| `between` | Between two dates | `{ startDate: { between: ["2023-09-01", "2023-12-31"] } }` |

#### Boolean Filters [#boolean-filters]

Boolean fields can be filtered directly:

```graphql
{
  isActive: true
}
```

#### ID Filters [#id-filters]

ID fields support exact match or inclusion in a list:

| Operation | Description    | Example                                        |
| --------- | -------------- | ---------------------------------------------- |
| `equals`  | Exact ID match | `{ id: { equals: "course-123" } }`             |
| `in`      | ID in list     | `{ id: { in: ["course-123", "course-456"] } }` |

### Combining Filters [#combining-filters]

You can combine multiple filters in a single query. By default, all conditions must be met (AND logic):

```graphql
query {
  courses(
    filter: {
      name: { contains: "Math" }
      startDate: { after: "2023-01-01" }
      enrollmentCount: { gt: 10 }
    }
  ) {
    nodes {
      id
      name
    }
  }
}
```

### Logical Operators [#logical-operators]

For more complex filtering, you can use logical operators:

#### AND [#and]

```graphql
query {
  courses(
    filter: {
      AND: [
        { name: { contains: "Math" } },
        { enrollmentCount: { gt: 10 } }
      ]
    }
  ) {
    nodes {
      id
      name
    }
  }
}
```

#### OR [#or]

```graphql
query {
  courses(
    filter: {
      OR: [
        { name: { contains: "Math" } },
        { name: { contains: "Science" } }
      ]
    }
  ) {
    nodes {
      id
      name
    }
  }
}
```

#### NOT [#not]

```graphql
query {
  courses(
    filter: {
      NOT: {
        name: { contains: "Archived" }
      }
    }
  ) {
    nodes {
      id
      name
    }
  }
}
```

### Filtering on Related Resources [#filtering-on-related-resources]

You can filter based on related resources. For example, finding courses with specific instructors:

```graphql
query {
  courses(
    filter: {
      instructors: {
        some: {
          name: { contains: "Smith" }
        }
      }
    }
  ) {
    nodes {
      id
      name
    }
  }
}
```

### Resource-Specific Filters [#resource-specific-filters]

Each resource type has specific filter fields. For detailed information on available filters for each resource, see the resource-specific documentation:

* [Course Filters](./courses#filtering)
* [Assignment Filters](./assignments#filtering)
* [Event Filters](./events#filtering)
* [Payment Filters](./payments#filtering)
* [Subscription Filters](./subscriptions#filtering)

### Filtering Best Practices [#filtering-best-practices]

1. **Filter on the server**: Always use API filtering instead of retrieving large datasets and filtering client-side.

2. **Be specific**: Use the most specific filter operations available to minimize data transfer.

3. **Combine with pagination**: Use filtering together with pagination for the most efficient queries.

4. **Test complex filters**: Complex logical combinations should be thoroughly tested to ensure they return the expected results.


---

# Membership Plans Query (https://docs.loopwise.com/api/queries/membership-plans)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Membership Plans API allows you to retrieve information about subscription options available to students in your school. Each plan has specific features, pricing, and duration settings.

## Available Queries [#available-queries]

### `membershipPlans` [#membershipplans]

Returns a paginated list of membership plans for the authenticated school.

**Parameters:**

| Parameter | Type                      | Description                                     |
| --------- | ------------------------- | ----------------------------------------------- |
| `filter`  | AdminMembershipPlanFilter | Filter criteria (see [Filtering](#filtering))   |
| `page`    | Int                       | Page number for pagination                      |
| `perPage` | Int                       | Number of items per page (default: 20, max: 50) |
| `limit`   | Int                       | Alternative to perPage                          |

**Returns:**

* AdminMembershipPlanPage object with:
  * `nodes`: Array of AdminMembershipPlan objects
  * `currentPage`: Current page number
  * `hasNextPage`: Whether there are more pages
  * `hasPreviousPage`: Whether there are previous pages
  * `nodesCount`: Total number of items in the current page
  * `totalPages`: Total number of pages

**Example:**

```graphql
query {
  membershipPlans(
    filter: {
      active: true
    },
    page: 1,
    perPage: 10
  ) {
    nodes {
      id
      name
      description
      planType
      isLifetime
      price
      currency
      interval
      intervalCount
      active
      visible
      createdAt
      updatedAt
      totalRevenue
      subscriptions (
        filter: {
          planId: { eq: "abc123-983dsf8" }
        }
      ) {
        nodes {
          id
          planId
          state
          createdAt
        }
      }
    }
    currentPage
    hasNextPage
    hasPreviousPage
    nodesCount
    totalPages
  }
}
```

## Membership Plan Object [#membership-plan-object]

The AdminMembershipPlan object contains the following fields based on the schema:

| Field            | Type                          | Description                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ---------------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`             | String!                       | Unique identifier                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `name`           | String!                       | Plan name                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `description`    | String                        | Plan description                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `planType`       | String!                       | Plan type. Possible values: `recurring`, `fixed_date`, `specific_length`, `lifetime`                                                                                                                                                                                                                                                                                                                                                          |
| `isLifetime`     | Boolean!                      | Indicates whether this is a lifetime (permanent access) plan                                                                                                                                                                                                                                                                                                                                                                                  |
| `price`          | Float!                        | Price of the plan                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `currency`       | String!                       | Currency code (e.g., USD, EUR) in ISO 4217 format                                                                                                                                                                                                                                                                                                                                                                                             |
| `interval`       | String!                       | Billing interval (month, year, day)                                                                                                                                                                                                                                                                                                                                                                                                           |
| `intervalCount`  | Int!                          | Number of intervals (e.g., 1, 3, 6)                                                                                                                                                                                                                                                                                                                                                                                                           |
| `active`         | Boolean!                      | Whether the plan is active                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `visible`        | Boolean!                      | Whether the plan is visible to students                                                                                                                                                                                                                                                                                                                                                                                                       |
| `createdAt`      | Int!                          | When the plan was created                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `updatedAt`      | Int!                          | When the plan was last updated                                                                                                                                                                                                                                                                                                                                                                                                                |
| `soldItemsCount` | Int                           | Number of sold subscriptions                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `totalRevenue`   | Float                         | Total revenue generated by this plan                                                                                                                                                                                                                                                                                                                                                                                                          |
| `subscriptions`  | AdminSubscriptionPage         | Paginated list of subscriptions for this plan                                                                                                                                                                                                                                                                                                                                                                                                 |
| `courses`        | AdminMembershipPlanCoursePage | Paginated. Courses this plan grants access to, oldest first — each node carries `id`, `name`, `slug`, `courseType` and `invisible`, and nothing else. Excludes deleted courses; unpublished and hidden ones are listed, except to a publishable key, which sees published, visible courses only. Empty for a plan that gates only post categories. Use the `id` with the `courses` query (which requires `courses:read`) for the full record. |
| `metadata`       | JSON                          | Custom external metadata as a JSON object of string key-value pairs, configured under Settings → Advanced → Product Custom Fields. Returns `null` when the school does not have the `external_metadata` feature enabled, and when nothing is set.                                                                                                                                                                                             |

## Subscriptions Fields [#subscriptions-fields]

The AdminMembershipPlan object includes subscription information through the `subscriptions` field. This returns a paginated list of subscriptions associated with the plan.

| Field                | Type     | Description                                            |
| -------------------- | -------- | ------------------------------------------------------ |
| `id`                 | String!  | Unique identifier for the subscription                 |
| `state`              | String!  | Current state of the subscription                      |
| `startAt`            | Int      | When the subscription starts                           |
| `endAt`              | Int      | When the subscription ends                             |
| `currentPeriodStart` | Int      | Start of current billing period                        |
| `currentPeriodEnd`   | Int      | End of current billing period                          |
| `isCanceling`        | Boolean! | Whether the subscription is scheduled for cancellation |
| `isCancellable`      | Boolean! | Whether the subscription can be cancelled              |

### User Information in Subscriptions [#user-information-in-subscriptions]

Each subscription includes user information through the `user` field:

| Field   | Type    | Description              |
| ------- | ------- | ------------------------ |
| `id`    | String! | User's unique identifier |
| `name`  | String  | User's full name         |
| `email` | String  | User's email address     |

### Subscriptions Filter Parameters [#subscriptions-filter-parameters]

| Parameter | Type           | Description                    |
| --------- | -------------- | ------------------------------ |
| `id`      | StringOperator | Filter by subscription ID      |
| `planId`  | StringOperator | Filter by subscription plan ID |
| `state`   | StringOperator | Filter by subscription state   |

**Example with filtered subscriptions:**

```graphql
query {
  membershipPlans(page: 1, perPage: 10) {
    nodes {
      id
      name
      subscriptions (
        filter: {
          state: {
            eq: "active"
          }
        }
      ) {
        nodes {
          id
          state
          startAt
          endAt
          currentPeriodStart
          currentPeriodEnd
          isCanceling
          isCancellable
          user {
            id
            name
            email
          }
        }
        currentPage
        nodesCount
      }
    }
  }
}
```

## Detailed Query Structure [#detailed-query-structure]

Below is a comprehensive view of fields available in the membershipPlans query based on the schema:

```graphql
query {
  membershipPlans(
    filter: {
      id: { eq: "plan-123" },
      active: true,
      visible: true
    },
    page: 1,
    perPage: 20
  ) {
    nodes {
      id                          # Unique identifier (String!)
      name                        # Plan name (String!)
      description                 # Plan description (String)

      # Plan type
      planType                    # Plan type: recurring, fixed_date, specific_length, lifetime (String!)
      isLifetime                  # Whether this is a lifetime plan (Boolean!)

      # Plan pricing details
      price                       # Price amount (Float!)
      currency                    # Currency code (String!)

      # Subscription details
      interval                    # Billing interval (String!)
      intervalCount               # Number of intervals (Int!)

      # Plan status
      active                      # Whether the plan is active (Boolean!)
      visible                     # Whether the plan is visible (Boolean!)

      # Timestamps
      createdAt                   # When the plan was created (Int!)
      updatedAt                   # When the plan was last updated (Int!)

      # Statistics
      soldItemsCount              # Number of sold subscriptions (Int)
      totalRevenue                # Total revenue generated (Float)

      # Related subscriptions
      subscriptions (
        filter: {
          planId: { eq: "abc123-983dsf8" }
        }
      ) {
        # Subscriptions for this plan (AdminSubscriptionPage)
        nodes {
          id
          state
          startAt
          endAt
          currentPeriodStart
          currentPeriodEnd
          isCanceling
          isCancellable
          user {
            id
            name
            email
          }
        }
        currentPage
        hasNextPage
        nodesCount
      }
    }

    # Pagination information
    currentPage                   # Current page number (Int!)
    hasNextPage                   # Whether there are more pages (Boolean!)
    hasPreviousPage               # Whether there are previous pages (Boolean!)
    nodesCount                    # Number of items in current page (Int!)
    totalPages                    # Total number of pages (Int!)
  }
}
```

## Filtering [#filtering]

The `membershipPlans` query accepts a `filter` parameter of type `AdminMembershipPlanFilter`. This allows you to narrow down results based on various criteria.

### Available Filters [#available-filters]

| Filter Field | Type           | Description                                                                                    |
| ------------ | -------------- | ---------------------------------------------------------------------------------------------- |
| `id`         | StringOperator | Filter by plan ID                                                                              |
| `active`     | Boolean        | Filter by active status                                                                        |
| `visible`    | Boolean        | Filter by visibility                                                                           |
| `planType`   | StringOperator | Filter by plan type. Possible values: `recurring`, `fixed_date`, `specific_length`, `lifetime` |

### StringOperator [#stringoperator]

The `StringOperator` used in filters has these operations:

| Operation | Description                                                          |
| --------- | -------------------------------------------------------------------- |
| `eq`      | Equal to                                                             |
| `neq`     | Not equal to                                                         |
| `in`      | In a list of values                                                  |
| `nin`     | Not in a list of values                                              |
| `like`    | Match text values against a pattern using wildcards (case-sensitive) |

### Filter Examples [#filter-examples]

**Find active membership plans:**

```graphql
query {
  membershipPlans(
    filter: {
      active: true
    }
  ) {
    nodes {
      id
      name
      price
      currency
    }
    nodesCount
  }
}
```

**Find visible membership plans:**

```graphql
query {
  membershipPlans(
    filter: {
      visible: true
    }
  ) {
    nodes {
      id
      name
      price
      currency
    }
    nodesCount
  }
}
```

**Find membership plans by ID:**

```graphql
query {
  membershipPlans(
    filter: {
      id: { eq: "plan-123" }
    }
  ) {
    nodes {
      id
      name
      price
      currency
    }
    nodesCount
  }
}
```

**Find lifetime membership plans:**

```graphql
query {
  membershipPlans(
    filter: {
      planType: { eq: "lifetime" }
    }
  ) {
    nodes {
      id
      name
      planType
      isLifetime
      price
      currency
    }
    nodesCount
  }
}
```

**Find recurring or lifetime plans:**

```graphql
query {
  membershipPlans(
    filter: {
      planType: { in: ["recurring", "lifetime"] }
    }
  ) {
    nodes {
      id
      name
      planType
    }
    nodesCount
  }
}
```

**Find all non-recurring plans:**

```graphql
query {
  membershipPlans(
    filter: {
      planType: { neq: "recurring" }
    }
  ) {
    nodes {
      id
      name
      planType
    }
    nodesCount
  }
}
```


---

# Payments Query (https://docs.loopwise.com/api/queries/payments)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Payments API allows you to retrieve information about payments in your school. Payments represent financial transactions made by users when purchasing courses, memberships, events, digital downloads, and other products. This API provides access to payment details, refund information, and filtering capabilities.

## Available Queries [#available-queries]

### `payments` [#payments]

Returns a paginated list of payments for the authenticated school.

**Parameters:**

| Parameter | Type               | Description                                                                                                                                           |
| --------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `filter`  | AdminPaymentFilter | Filter criteria (see [Filtering](#filtering))                                                                                                         |
| `page`    | Int                | Page number for pagination                                                                                                                            |
| `perPage` | Int                | Number of items per page (default: 20, max: 200 — this query raises the global 50 cap for export use; values above the cap are clamped, not rejected) |
| `limit`   | Int                | Alternative to perPage                                                                                                                                |

**Returns:**

* AdminPaymentPage object with:
  * `nodes`: Array of AdminPayment objects
  * `currentPage`: Current page number
  * `hasNextPage`: Whether there are more pages
  * `hasPreviousPage`: Whether there are previous pages
  * `nodesCount`: Total number of items in the current page
  * `totalPages`: Total number of pages

**Example:**

```graphql
query {
  payments(
    filter: {
      paymentState: { eq: "paid" },
      paidAt: { gte: 1704067200 }
    },
    page: 1,
    perPage: 10
  ) {
    nodes {
      id
      tradeNo
      amount
      currency
      paymentType
      paidAt
      user {
        id
        email
        name
      }
      lineitems {
        name
        amount
        itemType
      }
    }
    currentPage
    hasNextPage
    hasPreviousPage
    nodesCount
    totalPages
  }
}
```

## AdminPayment Object [#adminpayment-object]

The AdminPayment object contains the following fields:

| Field            | Type        | Description                                                                                       |
| ---------------- | ----------- | ------------------------------------------------------------------------------------------------- |
| `id`             | String!     | Unique identifier                                                                                 |
| `user`           | AdminUser!  | The user who made the payment                                                                     |
| `tradeNo`        | String      | Unique trade/transaction number from the payment gateway                                          |
| `currency`       | String!     | Currency code (e.g., TWD, USD) in ISO 4217 format                                                 |
| `currencySymbol` | String!     | Currency symbol (e.g., $, NT$)                                                                    |
| `amount`         | Float!      | Payment amount                                                                                    |
| `refundedAmount` | Float       | Amount that has been refunded                                                                     |
| `refundAmount`   | Float!      | Returns the refund amount if the payment is refunding, otherwise returns the refunded amount      |
| `discountAmount` | Float       | Discount amount applied to this payment                                                           |
| `paymentType`    | String      | Payment method (e.g., credit, atm, cvs, web\_atm, barcode, line\_pay)                             |
| `paymentState`   | String      | Payment lifecycle state (not\_paid, paid, expired, failed, manual\_enrolled, refunding, refunded) |
| `paidAt`         | Int         | Unix timestamp when the payment was completed                                                     |
| `refundedAt`     | Int         | Unix timestamp when the payment was refunded                                                      |
| `expiredAt`      | Int         | Unix timestamp when the payment expired                                                           |
| `affiliateCode`  | String      | Affiliate tracking code, if applicable                                                            |
| `remark`         | String      | Additional remarks or notes                                                                       |
| `lineitems`      | \[Lineitem] | List of purchased items in this payment                                                           |
| `invoice`        | Invoice     | Associated invoice, if issued                                                                     |
| `installment`    | Int         | Installment period for credit card payments, if applicable                                        |
| `createdAt`      | Int!        | Unix timestamp when the payment record was created                                                |
| `updatedAt`      | Int!        | Unix timestamp when the payment record was last updated                                           |

## Filtering [#filtering]

The `payments` query supports filtering through the `filter` parameter. The following filter fields are available:

| Filter Field   | Type           | Description                                                                                                                                                               |
| -------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`           | StringOperator | Filter by payment ID                                                                                                                                                      |
| `amount`       | FloatOperator  | Filter by payment amount                                                                                                                                                  |
| `paymentState` | StringOperator | Filter by payment state (not\_paid, paid, expired, failed, manual\_enrolled, refunding, refunded)                                                                         |
| `paidAt`       | IntOperator    | Filter by payment timestamp (Unix timestamp)                                                                                                                              |
| `refundedAt`   | IntOperator    | Filter by refund timestamp (Unix timestamp)                                                                                                                               |
| `createdAt`    | IntOperator    | Filter by creation timestamp (Unix timestamp)                                                                                                                             |
| `updatedAt`    | BigIntOperator | Filter by last-modified timestamp (Unix timestamp; BigInt, so values past 2038 are accepted) — see [Incremental sync](#incremental-sync-recommended-for-periodic-exports) |
| `tradeNo`      | StringOperator | Filter by trade/transaction number                                                                                                                                        |

### StringOperator Filters [#stringoperator-filters]

| Operator   | Description                           | Example                                            |
| ---------- | ------------------------------------- | -------------------------------------------------- |
| `eq`       | Equal to                              | `{ tradeNo: { eq: "T20250101001" } }`              |
| `neq`      | Not equal to                          | `{ paymentState: { neq: "expired" } }`             |
| `in`       | In a list of values                   | `{ paymentState: { in: ["paid", "refunding"] } }`  |
| `nin`      | Not in a list of values               | `{ paymentState: { nin: ["expired", "failed"] } }` |
| `like`     | Contains substring (case-sensitive)   | `{ tradeNo: { like: "T2025" } }`                   |
| `contains` | Contains substring (case-insensitive) | `{ tradeNo: { contains: "T2025" } }`               |

### IntOperator Filters [#intoperator-filters]

| Operator | Description           | Example                           |
| -------- | --------------------- | --------------------------------- |
| `eq`     | Equal to              | `{ paidAt: { eq: 1704067200 } }`  |
| `gt`     | Greater than          | `{ paidAt: { gt: 1704067200 } }`  |
| `gte`    | Greater than or equal | `{ paidAt: { gte: 1704067200 } }` |
| `lt`     | Less than             | `{ paidAt: { lt: 1735689600 } }`  |
| `lte`    | Less than or equal    | `{ paidAt: { lte: 1735689600 } }` |

### FloatOperator Filters [#floatoperator-filters]

| Operator | Description           | Example                       |
| -------- | --------------------- | ----------------------------- |
| `eq`     | Equal to              | `{ amount: { eq: 999.0 } }`   |
| `gt`     | Greater than          | `{ amount: { gt: 500.0 } }`   |
| `gte`    | Greater than or equal | `{ amount: { gte: 500.0 } }`  |
| `lt`     | Less than             | `{ amount: { lt: 2000.0 } }`  |
| `lte`    | Less than or equal    | `{ amount: { lte: 2000.0 } }` |

### Incremental sync (recommended for periodic exports) [#incremental-sync-recommended-for-periodic-exports]

If you sync payments into an external system on a schedule, do **not** re-read every page on every run — walking the full list repeats work the server has already done and gets slower as your school grows. Instead, remember when your last successful sync started and ask only for what changed since then:

```graphql
query SyncChangedPayments($since: Int!, $page: Int!) {
  payments(
    filter: { updatedAt: { gte: $since } },
    page: $page,
    perPage: 100
  ) {
    nodes {
      id
      tradeNo
      amount
      paymentState
      refundedAmount
      updatedAt
      # ...the fields your system mirrors
    }
    hasNextPage
    currentPage
  }
}
```

* `updatedAt` changes whenever the payment record changes — including state transitions such as a payment becoming `refunding` or `refunded` — so refunds of old payments are picked up without re-reading history.
* Record the sync **start** time (not end time) as the next run's `$since`, so writes that land mid-run are not missed. Rows updated in the overlap window appear twice; upsert by `id`.
* Most runs return zero or a handful of rows and a single request, instead of a full page walk.

### Filter Examples [#filter-examples]

**Find all paid payments in a date range:**

```graphql
query {
  payments(
    filter: {
      paymentState: { eq: "paid" },
      paidAt: { gte: 1704067200, lte: 1735689600 }
    }
  ) {
    nodes {
      id
      tradeNo
      amount
      currency
      paidAt
      user {
        id
        email
      }
    }
  }
}
```

**Find refunded payments in a specific period:**

```graphql
query {
  payments(
    filter: {
      paymentState: { eq: "refunded" },
      refundedAt: { gte: 1704067200, lte: 1735689600 }
    }
  ) {
    nodes {
      id
      tradeNo
      amount
      refundedAmount
      refundedAt
      user {
        id
        email
      }
    }
  }
}
```

**Look up a specific payment by trade number:**

```graphql
query {
  payments(
    filter: {
      tradeNo: { eq: "T20250101001" }
    }
  ) {
    nodes {
      id
      tradeNo
      amount
      currency
      paymentType
      paidAt
    }
  }
}
```

**Find high-value payments:**

```graphql
query {
  payments(
    filter: {
      paymentState: { in: ["paid", "refunding"] },
      amount: { gte: 10000.0 }
    }
  ) {
    nodes {
      id
      amount
      currency
      paymentType
      user {
        id
        name
        email
      }
    }
  }
}
```

## Relationships [#relationships]

The Payment API relates to:

* **Users**: Each payment belongs to a user
* **Lineitems**: A payment contains one or more line items representing purchased products
* **Invoices**: A payment may have an associated invoice

## Detailed Query Structure [#detailed-query-structure]

Below is a comprehensive view of fields available in the payments query:

```graphql
query {
  payments(
    filter: {
      id: { eq: "payment_123" }              # Filter by ID (StringOperator)
      amount: { gte: 100.0 }                 # Filter by amount (FloatOperator)
      paymentState: { eq: "paid" }           # Filter by state (StringOperator)
      paidAt: { gte: 1704067200 }            # Filter by paid timestamp (IntOperator)
      refundedAt: { gte: 1704067200 }        # Filter by refund timestamp (IntOperator)
      createdAt: { gte: 1704067200 }         # Filter by creation timestamp (IntOperator)
      updatedAt: { gte: 1704067200 }         # Filter by last-modified timestamp (BigIntOperator)
      tradeNo: { eq: "T20250101001" }        # Filter by trade number (StringOperator)
    },
    page: 1,                                  # Page number (Int)
    perPage: 20                               # Items per page (Int)
  ) {
    nodes {
      id                                      # Unique identifier (String!)
      tradeNo                                 # Trade/transaction number (String)

      # Financial information
      amount                                  # Payment amount (Float!)
      currency                                # Currency code (String!)
      currencySymbol                          # Currency symbol (String!)
      discountAmount                          # Discount applied (Float)
      refundedAmount                          # Amount refunded (Float)
      refundAmount                            # Current refund amount (Float!)

      # Payment details
      paymentType                             # Payment method (String)
      installment                             # Credit card installment period (Int)
      affiliateCode                           # Affiliate tracking code (String)
      remark                                  # Additional notes (String)

      # Timestamps (Unix)
      paidAt                                  # When payment was completed (Int)
      refundedAt                              # When payment was refunded (Int)
      expiredAt                               # When payment expired (Int)
      createdAt                               # When record was created (Int!)
      updatedAt                               # When record was last updated (Int!)

      # Related objects
      user {                                  # Payment user (AdminUser!)
        id
        email
        name
      }
      lineitems {                             # Purchased items ([Lineitem])
        name
        amount
        itemType
      }
      invoice {                               # Associated invoice (Invoice)
        id
        number
        state
      }
    }

    # Pagination information
    currentPage                               # Current page number (Int!)
    hasNextPage                               # Whether there are more pages (Boolean!)
    hasPreviousPage                           # Whether there are previous pages (Boolean!)
    nodesCount                                # Number of items on current page (Int!)
    totalPages                                # Total number of pages (Int!)
  }
}
```


---

# Posts Query (https://docs.loopwise.com/api/queries/posts)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Post API allows you to retrieve blog posts and articles published in your school, along with their categories. Use it to sync content to external systems, build custom front ends, or audit your content library.

## Available Queries [#available-queries]

### `posts` [#posts]

Returns a paginated list of posts for the authenticated school.

**Parameters:**

| Parameter | Type            | Description                                     |
| --------- | --------------- | ----------------------------------------------- |
| `filter`  | AdminPostFilter | Filter criteria (see [Filtering](#filtering))   |
| `page`    | Int             | Page number for pagination                      |
| `perPage` | Int             | Number of items per page (default: 20, max: 50) |

**Example:**

```graphql
query {
  posts(
    filter: {
      published: true,
      tags: ["news"]
    },
    page: 1,
    perPage: 10
  ) {
    nodes {
      id
      title
      slug
      accessType
      published
      publishedAt
      tags
      category {
        id
        name
      }
    }
    currentPage
    hasNextPage
    nodesCount
    totalPages
  }
}
```

### `post` [#post]

Returns a single post by ID, or `null` if the post does not exist in your school.

**Parameters:**

| Parameter | Type    | Description    |
| --------- | ------- | -------------- |
| `id`      | String! | ID of the post |

**Example:**

```graphql
query {
  post(id: "post_12345") {
    id
    title
    subtitle
    body
    excerpt
    slug
    accessType
    published
    publishedAt
    noindex
    coverPhoto
    tags
    category {
      id
      name
    }
    commentCount
    unrepliedCommentCount
  }
}
```

### `postCategories` [#postcategories]

Returns the post categories of your school. Use the returned IDs as `categoryId` when creating or updating posts, and as `categoryIds` when filtering posts.

**Example:**

```graphql
query {
  postCategories {
    nodes {
      id
      name
      slug
    }
  }
}
```

## AdminPost Object [#adminpost-object]

| Field                   | Type       | Description                                                                                     |
| ----------------------- | ---------- | ----------------------------------------------------------------------------------------------- |
| `id`                    | String!    | Unique identifier                                                                               |
| `title`                 | String!    | Post title                                                                                      |
| `subtitle`              | String     | Post subtitle                                                                                   |
| `body`                  | String!    | Post body content as HTML (see [Body content format](/api/mutations/posts#body-content-format)) |
| `excerpt`               | String     | Post excerpt                                                                                    |
| `slug`                  | String!    | URL slug                                                                                        |
| `coverPhoto`            | String     | URL of the cover photo                                                                          |
| `published`             | Boolean!   | Whether the post is published                                                                   |
| `publishedAt`           | Int        | Unix timestamp of the publish time                                                              |
| `noindex`               | Boolean!   | Whether the post is excluded from search engine indexing                                        |
| `accessType`            | String!    | `login_required`, `paid`, or `public_access`                                                    |
| `author`                | Lecturer   | The post author                                                                                 |
| `tags`                  | \[String!] | Tag names                                                                                       |
| `category`              | Category   | The post category                                                                               |
| `commentCount`          | Int!       | Total number of top-level comments                                                              |
| `unrepliedCommentCount` | Int!       | Number of top-level comments with no replies                                                    |
| `createdAt`             | Int!       | Unix timestamp                                                                                  |
| `updatedAt`             | Int!       | Unix timestamp                                                                                  |

## Filtering [#filtering]

The `filter` parameter accepts an `AdminPostFilter` object:

| Field         | Type            | Description                                                         |
| ------------- | --------------- | ------------------------------------------------------------------- |
| `id`          | OperatorString  | Filter by post ID                                                   |
| `title`       | OperatorString  | Filter by title (supports `eq`, `contains`, `like`, ...)            |
| `slug`        | OperatorString  | Filter by slug                                                      |
| `accessType`  | OperatorString  | Filter by access type                                               |
| `published`   | Boolean         | Filter by published flag                                            |
| `tags`        | \[String!]      | Return posts tagged with any of the given tags                      |
| `categoryIds` | \[String!]      | Return posts in the given categories, including their subcategories |
| `publishedAt` | OperatorInteger | Filter by publish time (Unix timestamp; supports `gt`, `lt`, ...)   |
| `createdAt`   | OperatorInteger | Filter by creation time                                             |
| `updatedAt`   | OperatorInteger | Filter by last update time                                          |

**Example — unpublished drafts in a category:**

```graphql
query {
  posts(filter: { published: false, categoryIds: ["cat_123"] }) {
    nodes {
      id
      title
    }
    nodesCount
  }
}
```

## Required Scope [#required-scope]

These queries require the `posts:read` scope.


---

# Product Revenues Query (https://docs.loopwise.com/api/queries/product-revenues)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Product Revenues API returns revenue metrics **broken down by product**, ranked by revenue. Where `revenueSummary` returns a single school-wide aggregate, `productRevenues` attributes revenue to each individual course, membership plan, digital product, event, or order bump.

Revenue is computed from paid line items (payment states `paid`, `refunding`, `refunded`) and windowed by `payment.paidAt`. Line items roll up to their canonical product:

* **CurriculumPlan** line items roll up to their parent **Course**.
* **Ticket** line items roll up to their parent **Event**.
* **OrderBump** is treated as its own product category.

This query requires the `analytics:read` [scope](../../reference/scopes).

## Available Queries [#available-queries]

### `productRevenues` [#productrevenues]

Returns a ranked list of products with their revenue metrics for the given period. Unlike most list queries, `productRevenues` is **not paginated** — it returns a plain array capped by `limit`.

**Parameters:**

| Parameter       | Type                       | Description                                                                                                         |
| --------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `since`         | Int                        | Start of the period as a Unix timestamp. Defaults to 30 days ago.                                                   |
| `until`         | Int                        | End of the period as a Unix timestamp. Defaults to now.                                                             |
| `productType`   | AdminProductType           | Restrict results to a single product category (see [Product Types](#product-types)).                                |
| `productIds`    | \[ID!]                     | Restrict results to specific canonical product ids. &#x2A;*Requires `productType`** — omitting it returns an error. |
| `paymentFilter` | AdminPaymentFilter         | Payment-level filters applied to the underlying payments (see [Payment Filtering](#payment-filtering)).             |
| `orderBy`       | AdminProductRevenueOrderBy | Sort key. Defaults to `TOTAL_REVENUE_DESC`.                                                                         |
| `limit`         | Int                        | Maximum number of products to return. Default `50`, clamped to a maximum of `200`.                                  |

**Returns:**

An array of `AdminProductRevenue` objects, ordered by `orderBy`.

**Example:**

```graphql
query {
  productRevenues(
    since: 1704067200,
    until: 1735689600,
    productType: COURSE,
    limit: 10
  ) {
    productId
    productType
    productName
    totalRevenue
    refundedAmount
    ordersCount
    currency
    periodStart
    periodEnd
  }
}
```

## AdminProductRevenue Object [#adminproductrevenue-object]

| Field            | Type    | Description                                                                                                                                                                                     |
| ---------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `productId`      | ID!     | Canonical product identifier (Course / Event / MembershipPlan / DigitalProduct / OrderBump).                                                                                                    |
| `productType`    | String! | Canonical product class name (`Course`, `Event`, `MembershipPlan`, `DigitalProduct`, or `OrderBump`).                                                                                           |
| `productName`    | String! | Human-readable product name.                                                                                                                                                                    |
| `totalRevenue`   | Float!  | Sum of post-discount line item amounts. Does **not** subtract `refundedAmount` — matches `revenueSummary.totalRevenue` semantics. Subtract `refundedAmount` yourself for net-of-refund revenue. |
| `refundedAmount` | Float!  | Sum of refunded line item amounts. Windowed by `payment.paidAt` like `totalRevenue` — this diverges from `revenueSummary`, which windows refunds by `refundedAt`.                               |
| `ordersCount`    | Int!    | Number of distinct payments containing this product.                                                                                                                                            |
| `currency`       | String! | Currency code in ISO 4217 format (e.g., TWD, USD).                                                                                                                                              |
| `periodStart`    | String! | Start of the requested period (ISO 8601).                                                                                                                                                       |
| `periodEnd`      | String! | End of the requested period (ISO 8601).                                                                                                                                                         |

> **Net revenue:** `totalRevenue` is gross of refunds. To compute net revenue for a product, subtract `refundedAmount` from `totalRevenue` on the client.

## Product Types [#product-types]

The `productType` argument and the `productType` field use the `AdminProductType` enum:

| Value             | Description                                                                           |
| ----------------- | ------------------------------------------------------------------------------------- |
| `COURSE`          | Course, aggregated across all of its curriculum plans.                                |
| `MEMBERSHIP_PLAN` | Membership plan.                                                                      |
| `DIGITAL_PRODUCT` | Digital download product.                                                             |
| `EVENT`           | Event, aggregated across all of its ticket types.                                     |
| `ORDER_BUMP`      | Order bump upsell SKU (its own product, not rolled into the underlying course/event). |

## Sorting [#sorting]

The `orderBy` argument uses the `AdminProductRevenueOrderBy` enum:

| Value                | Description                                                  |
| -------------------- | ------------------------------------------------------------ |
| `TOTAL_REVENUE_DESC` | Order by `totalRevenue`, highest first. This is the default. |

## Payment Filtering [#payment-filtering]

The `paymentFilter` argument reuses the same `AdminPaymentFilter` input type as the [`payments`](./payments#filtering) query, applied to the payments underlying each product's line items. This lets you compute revenue for a slice of payments — for example, only those attributed to a given affiliate, or only a specific payment method.

| Filter Field    | Type           | Description                                                                                                                                                                     |
| --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`            | StringOperator | Filter by payment ID.                                                                                                                                                           |
| `amount`        | FloatOperator  | Filter by payment amount.                                                                                                                                                       |
| `paymentState`  | StringOperator | Filter by payment state.                                                                                                                                                        |
| `paymentType`   | StringOperator | Filter by payment method (e.g., `credit`, `atm`, `cvs`, `web_atm`, `barcode`, `line_pay`). Only `eq`, `neq`, `in`, and `nin` are supported; values must be valid payment types. |
| `affiliateCode` | StringOperator | Filter by affiliate tracking code.                                                                                                                                              |
| `paidAt`        | IntOperator    | Filter by payment timestamp (Unix).                                                                                                                                             |
| `refundedAt`    | IntOperator    | Filter by refund timestamp (Unix).                                                                                                                                              |
| `createdAt`     | IntOperator    | Filter by creation timestamp (Unix).                                                                                                                                            |
| `tradeNo`       | StringOperator | Filter by trade/transaction number.                                                                                                                                             |

See the [Payments query](./payments#filtering) for the full operator reference (`StringOperator`, `FloatOperator`, `IntOperator`).

> **Note:** The `since`/`until` arguments already constrain payments by `paidAt`. Use `paymentFilter` for the non-time attributes above.

### Filter Examples [#filter-examples]

**Revenue per course attributed to a specific affiliate:**

```graphql
query {
  productRevenues(
    productType: COURSE,
    paymentFilter: {
      affiliateCode: { eq: "summer-promo" }
    }
  ) {
    productId
    productName
    totalRevenue
    ordersCount
  }
}
```

**Top-selling products paid by credit card or LINE Pay:**

```graphql
query {
  productRevenues(
    paymentFilter: {
      paymentType: { in: ["credit", "line_pay"] }
    },
    limit: 20
  ) {
    productId
    productType
    productName
    totalRevenue
    refundedAmount
  }
}
```

**Revenue for specific courses by id (requires `productType`):**

```graphql
query {
  productRevenues(
    productType: COURSE,
    productIds: ["123", "456"]
  ) {
    productId
    productName
    totalRevenue
    refundedAmount
    ordersCount
  }
}
```

## Related Queries [#related-queries]

* `revenueSummary`: Returns school-wide aggregated revenue metrics for a period. Use `productRevenues` when you need the per-product breakdown.

## Detailed Query Structure [#detailed-query-structure]

```graphql
query {
  productRevenues(
    since: 1704067200,                      # Period start, Unix timestamp (Int) — default 30 days ago
    until: 1735689600,                      # Period end, Unix timestamp (Int) — default now
    productType: COURSE,                    # Product category (AdminProductType)
    productIds: ["123"],                    # Canonical ids; requires productType ([ID!])
    paymentFilter: {                        # Payment-level filters (AdminPaymentFilter)
      affiliateCode: { eq: "summer-promo" }
      paymentType: { in: ["credit", "line_pay"] }
    },
    orderBy: TOTAL_REVENUE_DESC,            # Sort key (AdminProductRevenueOrderBy)
    limit: 50                               # Max products, clamped to 200 (Int)
  ) {
    productId                               # Canonical product id (ID!)
    productType                             # Canonical class name (String!)
    productName                             # Product name (String!)
    totalRevenue                            # Gross-of-refund revenue (Float!)
    refundedAmount                          # Refunded amount (Float!)
    ordersCount                             # Distinct payment count (Int!)
    currency                                # ISO 4217 currency code (String!)
    periodStart                             # Period start, ISO 8601 (String!)
    periodEnd                               # Period end, ISO 8601 (String!)
  }
}
```


---

# Student Course Progress Query (https://docs.loopwise.com/api/queries/student-course-progress)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Student Course Progress API allows you to retrieve information about student learning progress in a specific course. You can view completion rates, enrollment status, and access expiration details for all students enrolled in a course.

## Available Queries [#available-queries]

### `studentCourseProgress` [#studentcourseprogress]

Returns a paginated list of student progress records for a specific course.

**Parameters:**

| Parameter  | Type                        | Required | Description                                     |
| ---------- | --------------------------- | -------- | ----------------------------------------------- |
| `courseId` | String!                     | Yes      | The unique identifier of the course             |
| `filter`   | StudentCourseProgressFilter | No       | Filter criteria (see [Filtering](#filtering))   |
| `page`     | Int                         | No       | Page number for pagination                      |
| `perPage`  | Int                         | No       | Number of items per page (default: 20, max: 50) |
| `limit`    | Int                         | No       | Alternative to perPage                          |

**Returns:**

* StudentCourseShipPage object with:
  * `nodes`: Array of StudentCourseShip objects
  * `currentPage`: Current page number
  * `hasNextPage`: Whether there are more pages
  * `hasPreviousPage`: Whether there are previous pages
  * `nodesCount`: Total number of items in the current page
  * `totalPages`: Total number of pages

**Example:**

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    page: 1
    perPage: 20
  ) {
    nodes {
      id
      user {
        id
        name
        email
      }
      course {
        id
        name
      }
      completionRate
      completionPercentage
      deliveryState
      endedAt
      createdAt
      updatedAt
    }
    currentPage
    hasNextPage
    totalPages
    nodesCount
  }
}
```

## StudentCourseShip Object [#studentcourseship-object]

The StudentCourseShip object contains the following fields:

| Field                  | Type    | Description                                                                         |
| ---------------------- | ------- | ----------------------------------------------------------------------------------- |
| `id`                   | String! | Unique identifier for the enrollment record                                         |
| `user`                 | User!   | The student user object                                                             |
| `course`               | Course! | The course object                                                                   |
| `completionRate`       | Float   | Completion rate as decimal (0.0-1.0)                                                |
| `completionPercentage` | Float   | Completion percentage (0-100) for easier display                                    |
| `deliveryState`        | String  | Current enrollment state: `delivered`, `group_buying`, `pre_ordering`, or `expired` |
| `endedAt`              | Int     | Unix timestamp when course access expires (null for lifetime access)                |
| `createdAt`            | Int!    | Unix timestamp when the student enrolled                                            |
| `updatedAt`            | Int!    | Unix timestamp of last update                                                       |

### User Object in Progress [#user-object-in-progress]

Each progress record includes user information:

| Field   | Type    | Description              |
| ------- | ------- | ------------------------ |
| `id`    | String! | User's unique identifier |
| `name`  | String  | User's full name         |
| `email` | String  | User's email address     |

### Course Object in Progress [#course-object-in-progress]

Each progress record includes basic course information:

| Field  | Type    | Description                |
| ------ | ------- | -------------------------- |
| `id`   | String! | Course's unique identifier |
| `name` | String! | Course name                |

## Detailed Query Structure [#detailed-query-structure]

Below is a comprehensive view of fields available in the studentCourseProgress query:

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    filter: {
      completionPercentage: { gte: 50 }
      deliveryState: { eq: "delivered" }
    }
    page: 1
    perPage: 20
  ) {
    # Student progress data
    nodes {
      id                          # Enrollment record ID (String!)

      # User information
      user {
        id                        # User ID (String!)
        name                      # Full name (String)
        email                     # Email address (String)
      }

      # Course information
      course {
        id                        # Course ID (String!)
        name                      # Course name (String!)
      }

      # Progress metrics
      completionRate              # Decimal format 0.0-1.0 (Float)
      completionPercentage        # Percentage format 0-100 (Float)

      # Enrollment status
      deliveryState               # delivered, group_buying, pre_ordering, expired (String)
      endedAt                     # Access expiration timestamp (Int)

      # Timestamps
      createdAt                   # Enrollment date (Int!)
      updatedAt                   # Last updated (Int!)
    }

    # Pagination metadata
    currentPage                   # Current page number (Int!)
    hasNextPage                   # Whether there are more pages (Boolean!)
    hasPreviousPage               # Whether there are previous pages (Boolean!)
    nodesCount                    # Number of items in current page (Int!)
    totalPages                    # Total number of pages (Int!)
  }
}
```

## Filtering [#filtering]

The `studentCourseProgress` query accepts a `filter` parameter of type `StudentCourseProgressFilter`. This allows you to narrow down results based on various criteria.

| Filter Field           | Type           | Description                             |
| ---------------------- | -------------- | --------------------------------------- |
| `userId`               | StringOperator | Filter by specific user ID(s)           |
| `completionPercentage` | IntOperator    | Filter by completion percentage (0-100) |
| `deliveryState`        | StringOperator | Filter by enrollment state              |
| `endedAt`              | IntOperator    | Filter by access expiration date        |
| `createdAt`            | IntOperator    | Filter by enrollment date               |
| `updatedAt`            | IntOperator    | Filter by last update date              |

### IntOperator [#intoperator]

The `IntOperator` used for numeric filters has these operations:

| Operation | Description              |
| --------- | ------------------------ |
| `eq`      | Equal to                 |
| `neq`     | Not equal to             |
| `gt`      | Greater than             |
| `gte`     | Greater than or equal to |
| `lt`      | Less than                |
| `lte`     | Less than or equal to    |

### StringOperator [#stringoperator]

The `StringOperator` used for string filters has these operations:

| Operation  | Description                                                          |
| ---------- | -------------------------------------------------------------------- |
| `eq`       | Equal to                                                             |
| `neq`      | Not equal to                                                         |
| `in`       | In a list of values (batch query, max 100 items)                     |
| `nin`      | Not in a list of values                                              |
| `like`     | Match text values against a pattern using wildcards (case-sensitive) |
| `contains` | Contains text (case-insensitive)                                     |

## Filter Examples [#filter-examples]

### Find High-Performing Students [#find-high-performing-students]

Query students with completion rate above 80%:

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    filter: {
      completionPercentage: { gt: 80 }
      deliveryState: { eq: "delivered" }
    }
  ) {
    nodes {
      user {
        id
        name
        email
      }
      completionPercentage
      updatedAt
    }
    nodesCount
  }
}
```

### Find Students Needing Attention [#find-students-needing-attention]

Query students with low completion rate (below 30%):

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    filter: {
      completionPercentage: { lt: 30 }
      deliveryState: { eq: "delivered" }
    }
  ) {
    nodes {
      user {
        id
        name
        email
      }
      completionPercentage
      updatedAt
    }
  }
}
```

### Find Students with Expiring Access [#find-students-with-expiring-access]

Query students whose access will expire within 30 days:

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    filter: {
      endedAt: {
        gte: 1704067200    # Current timestamp
        lte: 1706745600    # 30 days from now
      }
      deliveryState: { eq: "delivered" }
    }
  ) {
    nodes {
      user {
        id
        name
        email
      }
      completionPercentage
      endedAt
    }
  }
}
```

### Query Multiple Students [#query-multiple-students]

Query progress for specific students using batch query:

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    filter: {
      userId: {
        in: ["user-1-uuid", "user-2-uuid", "user-3-uuid"]
      }
    }
  ) {
    nodes {
      user {
        id
        name
      }
      completionPercentage
      deliveryState
    }
  }
}
```

### Query by Completion Range [#query-by-completion-range]

Find students with moderate progress (50%-80%):

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    filter: {
      completionPercentage: {
        gte: 50
        lte: 80
      }
    }
  ) {
    nodes {
      user {
        id
        name
      }
      completionPercentage
    }
  }
}
```

### Exclude Expired Enrollments [#exclude-expired-enrollments]

Query only active students (not expired):

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    filter: {
      deliveryState: { neq: "expired" }
    }
  ) {
    nodes {
      user {
        id
        name
      }
      completionPercentage
      deliveryState
    }
  }
}
```

### Find Recently Active Students [#find-recently-active-students]

Query students who have been active in the last 7 days:

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    filter: {
      updatedAt: { gte: 1703980800 }  # 7 days ago timestamp
    }
  ) {
    nodes {
      user {
        id
        name
      }
      completionPercentage
      updatedAt
    }
  }
}
```

### Combined Filters [#combined-filters]

Query high-performing active students who recently updated their progress:

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    filter: {
      completionPercentage: { gte: 70 }
      deliveryState: { eq: "delivered" }
      updatedAt: { gte: 1701388800 }  # Last 30 days
    }
  ) {
    nodes {
      user {
        id
        name
        email
      }
      completionPercentage
      updatedAt
    }
    nodesCount
  }
}
```

## Delivery States [#delivery-states]

The `deliveryState` field indicates the current status of a student's course enrollment:

| State          | Description                                   |
| -------------- | --------------------------------------------- |
| `delivered`    | Normal access - student can access the course |
| `group_buying` | Currently in group buying phase               |
| `pre_ordering` | Course is in pre-order status                 |
| `expired`      | Course access has expired                     |

## Use Cases [#use-cases]

### Track Course Engagement [#track-course-engagement]

Monitor overall course engagement by viewing completion rates across all students:

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    page: 1
    perPage: 50
  ) {
    nodes {
      user { name }
      completionPercentage
    }
    nodesCount
  }
}
```

### Identify Students for Re-engagement [#identify-students-for-re-engagement]

Find students who haven't made progress recently:

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    filter: {
      completionPercentage: { lt: 50 }
      updatedAt: { lt: 1698796800 }  # 90 days ago
      deliveryState: { eq: "delivered" }
    }
  ) {
    nodes {
      user {
        id
        name
        email
      }
      completionPercentage
      updatedAt
    }
  }
}
```

### Monitor Course Completion [#monitor-course-completion]

Track students who have completed or nearly completed the course:

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    filter: {
      completionPercentage: { gte: 90 }
    }
  ) {
    nodes {
      user {
        id
        name
        email
      }
      completionPercentage
      createdAt
      updatedAt
    }
    nodesCount
  }
}
```

## Pagination [#pagination]

Results are paginated to ensure optimal performance. Use the `page` and `perPage` parameters to navigate through results:

```graphql
query {
  studentCourseProgress(
    courseId: "course-123-uuid"
    page: 2
    perPage: 25
  ) {
    nodes {
      user { name }
      completionPercentage
    }
    currentPage      # 2
    totalPages       # Total number of pages
    hasNextPage      # true if more pages available
    hasPreviousPage  # true if previous pages exist
    nodesCount       # Number of students in current page
  }
}
```

## Sorting [#sorting]

Results are automatically sorted by:

1. Completion rate (descending) - highest completion first
2. Updated at (descending) - most recently active first

This ensures that the most engaged students appear at the top of the results.

## Best Practices [#best-practices]

1. **Always specify courseId**: This is a required parameter that ensures you're querying the correct course.

2. **Use completion percentage for filtering**: The `completionPercentage` field (0-100) is more intuitive than `completionRate` (0.0-1.0).

3. **Batch queries have limits**: When using the `userId: { in: [...] }` filter, limit the array to 100 items maximum.

4. **Filter by delivery state**: Consider filtering out expired enrollments for most use cases by using `deliveryState: { eq: "delivered" }`.

5. **Combine filters for targeted queries**: Use multiple filter criteria to narrow down results to specific student cohorts.

6. **Monitor access expiration**: Use `endedAt` filters to identify students who need renewal reminders.

## Error Handling [#error-handling]

Common error scenarios:

* **Course not found**: If the specified `courseId` doesn't exist or doesn't belong to your school, an empty result set will be returned.
* **Invalid filter values**: Ensure numeric filters use appropriate operators and values.
* **Batch size exceeded**: Keep `userId` batch queries under 100 items to avoid errors.


---

# Subscriptions Query (https://docs.loopwise.com/api/queries/subscriptions)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Subscriptions API allows you to retrieve information about user subscriptions in your school. Each subscription represents a user's access to a membership plan, including billing period details and cancellation status.

## Available Queries [#available-queries]

### `subscriptions` [#subscriptions]

Returns a paginated list of subscriptions for the authenticated school.

**Parameters:**

| Parameter | Type                    | Description                                     |
| --------- | ----------------------- | ----------------------------------------------- |
| `filter`  | AdminSubscriptionFilter | Filter criteria (see [Filtering](#filtering))   |
| `page`    | Int                     | Page number for pagination                      |
| `perPage` | Int                     | Number of items per page (default: 20, max: 50) |
| `limit`   | Int                     | Alternative to perPage                          |

**Returns:**

* AdminSubscriptionPage object with:
  * `nodes`: Array of AdminSubscription objects
  * `currentPage`: Current page number
  * `hasNextPage`: Whether there are more pages
  * `hasPreviousPage`: Whether there are previous pages
  * `nodesCount`: Total number of items matching the query
  * `totalPages`: Total number of pages

**Example:**

```graphql
query {
  subscriptions(
    page: 1,
    perPage: 10
  ) {
    nodes {
      id
      state
      startAt
      endAt
      currentPeriodStart
      currentPeriodEnd
      planId
      isCanceling
      isCancellable
      nextChargeDate
      createdAt
      updatedAt
      plan {
        id
        name
      }
      user {
        id
        name
        email
      }
    }
    currentPage
    hasNextPage
    hasPreviousPage
    nodesCount
    totalPages
  }
}
```

## Subscription Object [#subscription-object]

The AdminSubscription object contains the following fields:

| Field                | Type            | Description                                                                                                                    |
| -------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `id`                 | String!         | Unique identifier                                                                                                              |
| `state`              | String!         | Current state of the subscription (e.g., active, canceled, past\_due)                                                          |
| `startAt`            | Int             | Unix Timestamp. When the subscription starts                                                                                   |
| `endAt`              | Int             | Unix Timestamp. When the subscription ends. For cancelled subscriptions, this represents the final termination date            |
| `currentPeriodStart` | Int             | Unix Timestamp. Start of the current billing period                                                                            |
| `currentPeriodEnd`   | Int             | Unix Timestamp. End of the current billing period. For active subscriptions, this represents when the next payment will be due |
| `planId`             | String!         | The unique identifier of the associated membership plan                                                                        |
| `plan`               | MembershipPlan! | The membership plan associated with this subscription                                                                          |
| `isCanceling`        | Boolean!        | Whether the subscription is scheduled for cancellation in the next billing cycle                                               |
| `isCancellable`      | Boolean!        | Whether the subscription can be cancelled                                                                                      |
| `nextChargeDate`     | Int             | Timestamp of the next scheduled charge. Null for non-recurring or inactive subscriptions                                       |
| `user`               | User!           | The user who owns this subscription                                                                                            |
| `createdAt`          | Int!            | Unix Timestamp. When the subscription was created                                                                              |
| `updatedAt`          | Int!            | Unix Timestamp. When the subscription was last updated                                                                         |
| `cancelReason`       | String          | The reason for cancellation if the subscription has been cancelled                                                             |
| `cancelType`         | String          | The type of cancellation (e.g., immediate, at\_period\_end)                                                                    |

## Filtering [#filtering]

The `subscriptions` query accepts a `filter` parameter of type `AdminSubscriptionFilter`. This allows you to narrow down results based on various criteria.

### Available Filters [#available-filters]

| Filter Field | Type           | Description                                                      |
| ------------ | -------------- | ---------------------------------------------------------------- |
| `id`         | StringOperator | Filter by subscription ID                                        |
| `state`      | StringOperator | Filter by subscription state (e.g., active, canceled, past\_due) |
| `planId`     | StringOperator | Filter by membership plan ID                                     |
| `userEmail`  | StringOperator | Filter by user email address                                     |

### StringOperator [#stringoperator]

The `StringOperator` used in filters has these operations:

| Operation  | Description                                                          |
| ---------- | -------------------------------------------------------------------- |
| `eq`       | Equal to                                                             |
| `neq`      | Not equal to                                                         |
| `in`       | In a list of values                                                  |
| `nin`      | Not in a list of values                                              |
| `like`     | Match text values against a pattern using wildcards (case-sensitive) |
| `contains` | Contains substring (case-insensitive)                                |

### Filter Examples [#filter-examples]

**Find active subscriptions:**

```graphql
query {
  subscriptions(
    filter: {
      state: { eq: "active" }
    }
  ) {
    nodes {
      id
      state
      startAt
      endAt
      user {
        id
        name
        email
      }
    }
    nodesCount
  }
}
```

**Find canceled subscriptions:**

```graphql
query {
  subscriptions(
    filter: {
      state: { eq: "canceled" }
    }
  ) {
    nodes {
      id
      state
      cancelReason
      cancelType
      endAt
      user {
        id
        email
      }
    }
    nodesCount
  }
}
```

**Find subscriptions by plan:**

```graphql
query {
  subscriptions(
    filter: {
      planId: { eq: "plan-123" }
    }
  ) {
    nodes {
      id
      state
      startAt
      endAt
      plan {
        id
        name
      }
    }
    nodesCount
  }
}
```

**Find subscriptions by user email:**

```graphql
query {
  subscriptions(
    filter: {
      userEmail: { contains: "alice" }
    }
  ) {
    nodes {
      id
      state
      user {
        id
        name
        email
      }
    }
    nodesCount
  }
}
```

**Find active subscriptions for a specific plan:**

```graphql
query {
  subscriptions(
    filter: {
      state: { eq: "active" },
      planId: { eq: "plan-123" }
    }
  ) {
    nodes {
      id
      state
      currentPeriodStart
      currentPeriodEnd
      nextChargeDate
    }
    nodesCount
  }
}
```

**Find subscriptions with multiple states:**

```graphql
query {
  subscriptions(
    filter: {
      state: { in: ["active", "past_due"] }
    }
  ) {
    nodes {
      id
      state
      user {
        id
        email
      }
    }
    nodesCount
  }
}
```


---

# Users Query (https://docs.loopwise.com/api/queries/users)



> **Note:** The Loopwise Admin API is currently under development and not yet available for public use. This documentation is provided for preview purposes only.

## Overview [#overview]

The Users API allows you to retrieve information about users in your school. You can list all users, get details for a specific user, and access related data.

## Available Queries [#available-queries]

### `users` [#users]

Returns a paginated list of users for the school.

**Parameters:**

| Parameter | Type          | Description                                                                                                                                                                                                                                              |
| --------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `role`    | AdminUserRole | Which user pool to return: `student` (default) or `teaching_assistant`. Admin roles (owner / manager) are intentionally not selectable — use [`meetingHosts`](/docs/api/queries/consulting#meetinghosts) for the owner+TA pool that `hostUserId` accepts |
| `filter`  | UserFilter    | Filter criteria (see [Filtering](#filtering))                                                                                                                                                                                                            |
| `page`    | Int           | Page number for pagination                                                                                                                                                                                                                               |
| `perPage` | Int           | Number of items per page (default: 20, max: 50)                                                                                                                                                                                                          |
| `limit`   | Int           | Alternative to perPage                                                                                                                                                                                                                                   |

**Returns:**

* UserPage object with:
  * `nodes`: Array of User objects
  * `currentPage`: Current page number
  * `hasNextPage`: Whether there are more pages
  * `hasPreviousPage`: Whether there are previous pages
  * `nodesCount`: Total number of items in the current page
  * `totalPages`: Total number of pages

**Example:**

```graphql
query {
  users(
    page: 1
    perPage: 10
  ) {
    nodes {
      id
      name
      email
      phoneNumber
    }
    currentPage
    hasNextPage
    totalPages
  }
}
```

## User Object [#user-object]

The User object contains the following fields based on the schema:

| Field         | Type        | Description                                                                                                                        |
| ------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `id`          | String!     | Unique identifier (UUID)                                                                                                           |
| `name`        | String      | Full name of the user                                                                                                              |
| `email`       | String      | Email address of the user                                                                                                          |
| `phoneNumber` | String      | Phone number of the user                                                                                                           |
| `identities`  | \[Identity] | Third-party authentication identities (see [Identities](#identities-fields))                                                       |
| `tags`        | \[String!]! | Admin-assigned tags on this user, scoped to the current school. See [`updateStudent`](/docs/api/mutations/students) to manage tags |

## Detailed Query Structure [#detailed-query-structure]

Below is a comprehensive view of fields available in the users query based on the schema:

```graphql
query {
  users(
    filter: {
      name: { eq: "Smith" }
    }
    page: 1
    perPage: 20
  ) {
    # User metadata
    nodes {
      id                          # Unique identifier (String!)
      name                        # Full name (String!)
      email                       # Email address (String!)
      phoneNumber                 # Phone number (String)
      tags                        # Admin-assigned tags, scoped to this school ([String!]!)

      # Third-party authentication identities
      identities(provider: "google_oauth2") {
        id
        provider
        uid
        name
      }

      # subscriptions of user
      subscriptions(
        filter: {
          state: { eq: "active" }
        }
      ) {
        nodes {
          id
          planId
          state
        }
      }
    }

    # Pagination metadata
    currentPage                   # Current page number (Int!)
    hasNextPage                   # Whether there are more pages (Boolean!)
    hasPreviousPage               # Whether there are previous pages (Boolean!)
    nodesCount                    # Number of items in current page (Int!)
    totalPages                    # Total number of pages (Int!)
  }
}
```

## Filtering [#filtering]

The `users` query accepts a `filter` parameter of type `UserFilter`. This allows you to narrow down results based on various criteria.

| Filter Field | Type           | Description          |
| ------------ | -------------- | -------------------- |
| `name`       | StringOperator | Filter by user name  |
| `email`      | StringOperator | Filter by user email |

### StringOperator [#stringoperator]

The `StringOperator` used in filters has these operations:

| Operation | Description                                                          |
| --------- | -------------------------------------------------------------------- |
| `eq`      | Equal to                                                             |
| `neq`     | Not equal to                                                         |
| `in`      | In a list of values                                                  |
| `nin`     | Not in a list of values                                              |
| `like`    | Match text values against a pattern using wildcards (case-sensitive) |

### Filter Examples [#filter-examples]

**Find users with a specific name pattern:**

```graphql
query {
  users(
    filter: {
      name: { eq: "Smith" }
    }
  ) {
    nodes {
      id
      name
      email
    }
  }
}
```

**Find users with a specific email pattern:**

```graphql
query {
  users(
    filter: {
      email: { eq: "smith@example.com" }
    }
  ) {
    nodes {
      id
      name
      email
    }
  }
}
```

## Identities Fields [#identities-fields]

The User object can include identity information through the `identities` field. This returns a list of the user's third-party authentication identities (e.g., Google, LINE, Facebook).

**Parameters:**

| Parameter  | Type   | Description                                                              |
| ---------- | ------ | ------------------------------------------------------------------------ |
| `provider` | String | Optional. Filter by provider (e.g., `google_oauth2`, `line`, `facebook`) |

**Identity Object:**

| Field      | Type    | Description                                                         |
| ---------- | ------- | ------------------------------------------------------------------- |
| `id`       | String! | Unique identifier for the identity                                  |
| `provider` | String! | Authentication provider (e.g., `google_oauth2`, `line`, `facebook`) |
| `uid`      | String! | User identifier from the provider                                   |
| `name`     | String  | Display name from the provider                                      |

**Example with identity data:**

```graphql
query {
  users(page: 1, perPage: 20) {
    nodes {
      id
      name
      email
      identities {
        id
        provider
        uid
        name
      }
    }
    currentPage
    totalPages
  }
}
```

## Subscriptions Fields [#subscriptions-fields]

The User object can include subscription information through the `subscriptions` field. This returns a paginated list of the user's subscriptions.

| Field       | Type    | Description                            |
| ----------- | ------- | -------------------------------------- |
| `id`        | String! | Unique identifier for the subscription |
| `planId`    | String! | Identifier of the subscription plan    |
| `state`     | String! | Current state of the subscription      |
| `createdAt` | Int!    | When the subscription was created      |

### StringOperator [#stringoperator-1]

The `StringOperator` used in filters has these operations:

| Operation | Description                                                          |
| --------- | -------------------------------------------------------------------- |
| `eq`      | Equal to                                                             |
| `neq`     | Not equal to                                                         |
| `in`      | In a list of values                                                  |
| `nin`     | Not in a list of values                                              |
| `like`    | Match text values against a pattern using wildcards (case-sensitive) |

### Subscription Filter Parameters [#subscription-filter-parameters]

| Parameter | Type           | Description                    |
| --------- | -------------- | ------------------------------ |
| `id`      | StringOperator | Filter by subscription ID      |
| `planId`  | StringOperator | Filter by subscription plan ID |
| `state`   | StringOperator | Filter by subscription state   |

**Example with subscription data:**

```graphql
query {
  users(page: 1, perPage: 20) {
    nodes {
      id
      name
      subscriptions(
        filter: {
          planId: {
            eq: "abc123-983dsf8"
          }
        }
      ) {
        nodes {
          id
          planId
          state
          createdAt
        }
      }
    }
    currentPage
    totalPages
  }
}
```
