Перейти к содержанию
CADCAMFUN
Документы

Документация

Биллинг

Информация о подписке, интеграция оформления заказа/портала Stripe, пробное обслуживание и прием подписанного веб-перехватчика.

Автоматически переведено с английского. Смотреть оригинал на английском

Песочница

Отправьте эти запросы на свою работающую сайдкар. Значения остаются в этом браузере.

Не подключено
Как это работает

Сайдкар прослушивает порт обратной связи, выбранный при запуске, и печатает его в своем ready линия; используйте этот URL-адрес и CADCAMFUN_TOKEN с этого началось. Запросы идут прямо с этой страницы на этот адрес.

Sidecar отправляет заголовки CORS только источникам Tauri и http://localhost или http://127.0.0.1 в любом порту. Из размещенных документов браузер блокирует ответ, поэтому запускайте документы локально (bun run dev в packages/web), чтобы использовать игровую площадку, или скопируйте запрос как завиток. Чтобы поэкспериментировать, не затрагивая реальные данные, запустите сайдкар с помощью CADCAMFUN_DATA_DIR указал на одноразовый каталог — см. пошаговое руководство по API.

Операции

15 endpoint в billing группа, созданная на основе собственной сайдкара документ OpenAPI. Защищенные операции занимают Authorization: Bearer $CADCAMFUN_TOKEN; видеть аутентификация. Поведение и ограничения находятся в руководство по подсистеме.

получать /api/subscription/info billing.info
получать /api/subscriptions billing.current
почта /api/subscriptions billing.subscribe
почта /api/subscriptions/portal billing.portal
получать /api/better-auth-stripe/subscription billing.baGet
почта /api/better-auth-stripe/subscription billing.baCheckout
помещать /api/better-auth-stripe/subscription billing.baUpdate
удалить /api/better-auth-stripe/subscription billing.baCancel
почта /api/better-auth-stripe/billing-portal billing.baPortal
почта /api/better-auth-stripe/feature-access billing.baFeature
почта /api/better-auth-stripe/sync billing.baSync
получать /api/cron/update-expired-trials billing.cronGet
почта /api/cron/update-expired-trials billing.cronPost
получать /api/health/stripe billing.stripeHealth
почта /api/webhooks/stripe billing.stripeWebhook
Платежные операции в 3D Перетащите на орбиту · прокрутите, чтобы увеличить · перетащите вправо, чтобы панорамировать
Один блок на операцию (15), сгруппированный в каждом разделе ресурсов на этой странице и окрашенный в зависимости от метода: зеленый GET, оранжевый POST, синий PUT, фиолетовый PATCH, красный DELETE. Создается из документа OpenAPI во время сборки.

/api/subscription/info

получать /api/subscription/info # billing.info

Требует Authorization: Bearer <token>.

Параметры
ИмяВТипНеобходимый
userId запрос нить | null необязательный
Ответы
200 объект application/json
{
  id: string
  plan: string
  status: string
  currentPeriodEnd: string | null
  cancelAtPeriodEnd: boolean | null
  stripeCustomerId: string | null
  stripeSubscriptionId: string | null
}
400 BillingBadRequestEncoded application/json
BillingBadRequestEncoded
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
403 BillingForbiddenEncoded application/json
BillingForbiddenEncoded
404 BillingNotFoundEncoded application/json
BillingNotFoundEncoded
500 BillingFailureEncoded application/json
BillingFailureEncoded
Пример ответа пойман · 400
ПОЛУЧИТЬ /api/подписку/информацию
{
  "_tag": "BillingBadRequest",
  "error": "User ID is required"
}
Пример SDK
billing.info
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// BillingInfoInput
const result = await client.billing.info({})
curl
ПОЛУЧИТЬ /api/подписку/информацию
curl --request GET "${CADCAMFUN_URL}/api/subscription/info" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}"
Попробуйте это

/api/subscriptions

получать /api/subscriptions # billing.current

Требует Authorization: Bearer <token>.

Ответы
200 объект application/json
{
  plan: string
  status: string
  periodEnd: string | null
  cancelAtPeriodEnd: boolean
  isOnTrial?: boolean | null
  trialEnd?: string | null
}
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
500 InternalErrorEncoded application/json
InternalErrorEncoded
Пример ответа пойман · 200
ПОЛУЧИТЬ /api/подписки
{
  "plan": "FREE",
  "status": "active",
  "periodEnd": null,
  "cancelAtPeriodEnd": false
}
Пример SDK
billing.current
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// no input
const result = await client.billing.current()
curl
ПОЛУЧИТЬ /api/подписки
curl --request GET "${CADCAMFUN_URL}/api/subscriptions" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}"
Попробуйте это
почта /api/subscriptions # billing.subscribe

Требует Authorization: Bearer <token>.

Тело запроса · обязательно · приложение/json
{
  priceId?: string | null
  startTrial?: boolean | null
}
Ответы
200 объект application/json
{
  url?: string | null
  success?: boolean | null
  message?: string | null
  redirectUrl?: string | null
}
400 BadRequestEncoded application/json
BadRequestEncoded
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
404 NotFoundEncoded application/json
NotFoundEncoded
500 InternalErrorEncoded application/json
InternalErrorEncoded
Пример SDK
billing.subscribe
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// BillingSubscribeInput
const result = await client.billing.subscribe({
  priceId: "",
  startTrial: false
})
curl
POST/api/подписки
curl --request POST "${CADCAMFUN_URL}/api/subscriptions" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}" \
  --header "Content-Type: application/json" \
  --data-binary @request.json
Попробуйте это

/api/subscriptions/portal

почта /api/subscriptions/portal # billing.portal

Требует Authorization: Bearer <token>.

Тело запроса · обязательно · приложение/json
{
  returnUrl?: string | null
}
Ответы
200 объект application/json
{
  url: string
}
400 BadRequestEncoded application/json
BadRequestEncoded
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
404 NotFoundEncoded application/json
NotFoundEncoded
500 InternalErrorEncoded application/json
InternalErrorEncoded
Пример SDK
billing.portal
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// BillingPortalInput
const result = await client.billing.portal({
  returnUrl: ""
})
curl
POST/api/подписки/портал
curl --request POST "${CADCAMFUN_URL}/api/subscriptions/portal" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}" \
  --header "Content-Type: application/json" \
  --data-binary @request.json
Попробуйте это

/api/better-auth-stripe/subscription

получать /api/better-auth-stripe/subscription # billing.baGet

Требует Authorization: Bearer <token>.

Ответы
200 объект application/json
{
  id?: string | null
  plan: string
  status: string
  currentPeriodEnd: string | null
  cancelAtPeriodEnd: boolean
  stripeCustomerId?: string | null
  stripeSubscriptionId?: string | null
  source: "better-auth"
}
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
500 BillingFailureEncoded application/json
BillingFailureEncoded
Пример ответа пойман · 200
ПОЛУЧИТЬ /api/better-auth-stripe/subscription
{
  "id": "c942817d-0162-4291-84ff-77321d387acc",
  "plan": "FREE",
  "status": "active",
  "currentPeriodEnd": null,
  "cancelAtPeriodEnd": false,
  "stripeCustomerId": null,
  "stripeSubscriptionId": null,
  "source": "better-auth"
}
Пример SDK
billing.baGet
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// no input
const result = await client.billing.baGet()
curl
ПОЛУЧИТЬ /api/better-auth-stripe/subscription
curl --request GET "${CADCAMFUN_URL}/api/better-auth-stripe/subscription" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}"
Попробуйте это
почта /api/better-auth-stripe/subscription # billing.baCheckout

Требует Authorization: Bearer <token>.

Тело запроса · обязательно · приложение/json
{
  plan?: string | null
  successUrl?: string | null
  cancelUrl?: string | null
  trialDays?: number | "Infinity" | "-Infinity" | "NaN" | null
}
Ответы
200 объект application/json
{
  url: string
  source: "better-auth"
}
400 BillingBadRequestEncoded application/json
BillingBadRequestEncoded
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
500 BillingFailureEncoded application/json
BillingFailureEncoded
Пример SDK
billing.baCheckout
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// BillingBaCheckoutInput
const result = await client.billing.baCheckout({
  plan: "",
  successUrl: "",
  cancelUrl: "",
  trialDays: 0
})
curl
POST/api/better-auth-stripe/подписка
curl --request POST "${CADCAMFUN_URL}/api/better-auth-stripe/subscription" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}" \
  --header "Content-Type: application/json" \
  --data-binary @request.json
Попробуйте это
помещать /api/better-auth-stripe/subscription # billing.baUpdate

Требует Authorization: Bearer <token>.

Тело запроса · обязательно · приложение/json
{
  newPlan?: string | null
}
Ответы
200 объект application/json
{
  success: true
  message: string
  source: "better-auth"
}
400 BillingBadRequestEncoded application/json
BillingBadRequestEncoded
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
500 BillingFailureEncoded application/json
BillingFailureEncoded
Пример SDK
billing.baUpdate
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// BillingBaUpdateInput
const result = await client.billing.baUpdate({
  newPlan: ""
})
curl
PUT /api/better-auth-stripe/подписка
curl --request PUT "${CADCAMFUN_URL}/api/better-auth-stripe/subscription" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}" \
  --header "Content-Type: application/json" \
  --data-binary @request.json
Попробуйте это
удалить /api/better-auth-stripe/subscription # billing.baCancel

Требует Authorization: Bearer <token>.

Ответы
200 объект application/json
{
  success: true
  message: string
  source: "better-auth"
}
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
500 BillingFailureEncoded application/json
BillingFailureEncoded
Пример SDK
billing.baCancel
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// no input
const result = await client.billing.baCancel()
curl
УДАЛИТЬ /api/better-auth-stripe/subscription
curl --request DELETE "${CADCAMFUN_URL}/api/better-auth-stripe/subscription" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}"
Попробуйте это

/api/better-auth-stripe/billing-portal

почта /api/better-auth-stripe/billing-portal # billing.baPortal

Требует Authorization: Bearer <token>.

Тело запроса · обязательно · приложение/json
{
  returnUrl?: string | null
}
Ответы
200 объект application/json
{
  url: string
  source: "better-auth"
}
400 BillingBadRequestEncoded application/json
BillingBadRequestEncoded
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
500 BillingFailureEncoded application/json
BillingFailureEncoded
Пример SDK
billing.baPortal
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// BillingBaPortalInput
const result = await client.billing.baPortal({
  returnUrl: ""
})
curl
POST /api/better-auth-stripe/биллинг-портал
curl --request POST "${CADCAMFUN_URL}/api/better-auth-stripe/billing-portal" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}" \
  --header "Content-Type: application/json" \
  --data-binary @request.json
Попробуйте это

/api/better-auth-stripe/feature-access

почта /api/better-auth-stripe/feature-access # billing.baFeature

Требует Authorization: Bearer <token>.

Тело запроса · обязательно · приложение/json
{
  feature?: string | null
  features?: unknown | null
}
Ответы
200 объект application/json
{
  feature?: string | null
  hasAccess?: boolean | null
  source: "better-auth"
  features?: Array<{
    feature: string
    hasAccess: boolean
    error?: string | null
  }> | null
}
400 BillingBadRequestEncoded application/json
BillingBadRequestEncoded
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
500 BillingFailureEncoded application/json
BillingFailureEncoded
Пример SDK
billing.baFeature
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// BillingBaFeatureInput
const result = await client.billing.baFeature({
  feature: "",
  features: null
})
curl
POST /api/better-auth-stripe/feature-access
curl --request POST "${CADCAMFUN_URL}/api/better-auth-stripe/feature-access" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}" \
  --header "Content-Type: application/json" \
  --data-binary @request.json
Попробуйте это

/api/better-auth-stripe/sync

почта /api/better-auth-stripe/sync # billing.baSync

Требует Authorization: Bearer <token>.

Ответы
200 объект application/json
{
  success: true
  message: string
  subscription: {
    id?: string | null
    plan: string
    status: string
    currentPeriodEnd: string | null
    cancelAtPeriodEnd: boolean
    stripeCustomerId?: string | null
    stripeSubscriptionId?: string | null
    source: "better-auth"
  } | null
  source: "better-auth"
}
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
500 BillingFailureEncoded application/json
BillingFailureEncoded
Пример SDK
billing.baSync
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// no input
const result = await client.billing.baSync()
curl
POST /api/better-auth-stripe/sync
curl --request POST "${CADCAMFUN_URL}/api/better-auth-stripe/sync" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}"
Попробуйте это

/api/cron/update-expired-trials

получать /api/cron/update-expired-trials # billing.cronGet

Требует Authorization: Bearer <token>.

Параметры
ИмяВТипНеобходимый
секрет запрос нить | null необязательный
Ответы
200 объект application/json
{
  success: true
  updatedCount: number | "Infinity" | "-Infinity" | "NaN"
  message: string
  timestamp: string
}
401 CronUnauthorizedEncoded | НеавторизованныйКодированный application/json
CronUnauthorizedEncoded | UnauthorizedEncoded
500 CronFailureEncoded application/json
CronFailureEncoded
Пример ответа пойман · 200
ПОЛУЧИТЕ /api/cron/update-expired-trials
{
  "success": true,
  "updatedCount": 0,
  "message": "Successfully updated 0 expired trials",
  "timestamp": "2026-10-15T04:52:23.475Z"
}
Пример SDK
billing.cronGet
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// BillingCronGetInput
const result = await client.billing.cronGet({})
curl
ПОЛУЧИТЕ /api/cron/update-expired-trials
curl --request GET "${CADCAMFUN_URL}/api/cron/update-expired-trials" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}"
Попробуйте это
почта /api/cron/update-expired-trials # billing.cronPost

Требует Authorization: Bearer <token>.

Параметры
ИмяВТипНеобходимый
секрет запрос нить | null необязательный
Ответы
200 объект application/json
{
  success: true
  updatedCount: number | "Infinity" | "-Infinity" | "NaN"
  message: string
  timestamp: string
}
401 CronUnauthorizedEncoded | НеавторизованныйКодированный application/json
CronUnauthorizedEncoded | UnauthorizedEncoded
500 CronFailureEncoded application/json
CronFailureEncoded
Пример SDK
billing.cronPost
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// BillingCronPostInput
const result = await client.billing.cronPost({})
curl
POST /api/cron/update-expired-trials
curl --request POST "${CADCAMFUN_URL}/api/cron/update-expired-trials" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}"
Попробуйте это

/api/health/stripe

получать /api/health/stripe # billing.stripeHealth

Требует Authorization: Bearer <token>.

Ответы
200 объект application/json
{
  status: "healthy"
  message: string
  timestamp: string
  service: "stripe"
}
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
503 StripeUnhealthyEncoded application/json
StripeUnhealthyEncoded
Пример ответа пойман · 503
ПОЛУЧИТЬ /api/health/stripe
{
  "_tag": "StripeUnhealthy",
  "status": "unhealthy",
  "message": "Stripe is not configured on this installation",
  "timestamp": "2026-10-15T04:52:23.476Z",
  "service": "stripe"
}
Пример SDK
billing.stripeHealth
import { CadCam } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

// no input
const result = await client.billing.stripeHealth()
curl
ПОЛУЧИТЬ /api/health/stripe
curl --request GET "${CADCAMFUN_URL}/api/health/stripe" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}"
Попробуйте это

/api/webhooks/stripe

почта /api/webhooks/stripe # billing.stripeWebhook

Требует Authorization: Bearer <token>.

Тело запроса · обязательно · приложение/поток октетов
string
Ответы
200 объект application/json
{
  received: true
}
400 BadRequestEncoded application/json
BadRequestEncoded
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
взять пример
billing.stripeWebhook
// Not generated in the Promise SDK (multipart, binary or raw body): call it with fetch.
const response = await fetch(`${process.env.CADCAMFUN_URL}/api/webhooks/stripe`, {
  method: "POST",
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})
curl
POST/api/webhooks/полоса
curl --request POST "${CADCAMFUN_URL}/api/webhooks/stripe" \
  --header "Authorization: Bearer ${CADCAMFUN_TOKEN}" \
  --header "Content-Type: application/octet-stream" \
  --data-binary @request-body
Попробуйте это

Эта операция принимает application/octet-stream; используйте пример скручивания или выборки.

Схемы

Именованные схемы, доступные из параметров, тел и ответов этой группы. А ? отмечает необязательное поле; | null отмечает поле, которое может иметь нулевое значение.

BadRequestEncoded
{
  _tag: "BadRequest"
  message: string
}
BillingBadRequestEncoded
{
  _tag: "BillingBadRequest"
  error: string
}
BillingFailureEncoded
{
  _tag: "BillingFailure"
  error: string
}
BillingForbiddenEncoded
{
  _tag: "BillingForbidden"
  error: string
}
BillingNotFoundEncoded
{
  _tag: "BillingNotFound"
  error: string
}
CronFailureEncoded
{
  _tag: "CronFailure"
  success: false
  error: string
  timestamp: string
}
CronUnauthorizedEncoded
{
  _tag: "CronUnauthorized"
  error: string
}
InternalErrorEncoded
{
  _tag: "InternalError"
  message: string
}
NotFoundEncoded
{
  _tag: "NotFound"
  message: string
}
StripeUnhealthyEncoded
{
  _tag: "StripeUnhealthy"
  status: "unhealthy"
  message: string
  timestamp: string
  service: "stripe"
}
UnauthorizedEncoded
{
  _tag: "Unauthorized"
  message: string
}

Звонок в эту группу

Идентификаторы операций имеют вид billing.<name>. Сгенерированный Promise SDK (@cadcamfun/api/sdk) выставляет большинство из них как client.<namespace>.<method>(input), где input представляет собой один плоский объект параметров пути и полей тела; В примере SDK каждой карты показаны точный метод доступа и тип ввода. Многочастные загрузки, двоичные ответы или ответы JavaScript, а также необработанные веб-перехватчики не генерируются; эти карты показывают fetch вместо этого.

Ошибки Promise SDK
import { CadCam, ClientError } from "@cadcamfun/api/sdk"

const client = CadCam.make({
  baseUrl: process.env.CADCAMFUN_URL!,
  headers: { authorization: `Bearer ${process.env.CADCAMFUN_TOKEN}` },
})

try {
  await client.projects.list()
} catch (error) {
  if (error instanceof ClientError) {
    // Transport | UnexpectedStatus | UnsupportedContentType | MalformedResponse | SseEventTooLarge
  } else {
    // a declared error body: switch on error._tag
  }
}

Поиск неисправностей

СимптомВероятная причинаИсправить
401 на каждый вызовТокен от предыдущего запуска или отсутствует Bearer префиксОтправлять Authorization: Bearer <token> с жетоном, с которого была запущена сайдкар.
400 до того как что-либо произойдётТело или параметр не соответствует схемеСравните полезную нагрузку со схемой запроса на карте.
403 или 404 у записи, которую видно в другом местеДействующий счет отличаетсяОтправить право x-session-tokenили используйте локальный профиль, которому принадлежит запись.
409Конфликтующее состояние, например повторяющееся имя или устаревший заголовок ветки.Перечитайте ресурс и повторите попытку с текущими данными.
Попробуйте, написано «заблокировано CORS».Документы подаются из источника без обратной связи.Запустите документы локально или скопируйте запрос как curl.
В соединении отказаноСайдкар перезапустилась в новом портуПрочтите порт из нового ready строка.