Документация
Биллинг
Информация о подписке, интеграция оформления заказа/портала 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 |
/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
{
"_tag": "BillingBadRequest",
"error": "User ID is required"
} Пример SDK
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
curl --request GET "${CADCAMFUN_URL}/api/subscription/info" \
--header "Authorization: Bearer ${CADCAMFUN_TOKEN}" Попробуйте это
/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
{
"plan": "FREE",
"status": "active",
"periodEnd": null,
"cancelAtPeriodEnd": false
} Пример SDK
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
curl --request GET "${CADCAMFUN_URL}/api/subscriptions" \
--header "Authorization: Bearer ${CADCAMFUN_TOKEN}" Попробуйте это
billing.subscribe Требует Authorization: Bearer <token>.
{ 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
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
curl --request POST "${CADCAMFUN_URL}/api/subscriptions" \
--header "Authorization: Bearer ${CADCAMFUN_TOKEN}" \
--header "Content-Type: application/json" \
--data-binary @request.json Попробуйте это
/api/subscriptions/portal
billing.portal Требует Authorization: Bearer <token>.
{ 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
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
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
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
{
"id": "c942817d-0162-4291-84ff-77321d387acc",
"plan": "FREE",
"status": "active",
"currentPeriodEnd": null,
"cancelAtPeriodEnd": false,
"stripeCustomerId": null,
"stripeSubscriptionId": null,
"source": "better-auth"
} Пример SDK
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
curl --request GET "${CADCAMFUN_URL}/api/better-auth-stripe/subscription" \
--header "Authorization: Bearer ${CADCAMFUN_TOKEN}" Попробуйте это
billing.baCheckout Требует Authorization: Bearer <token>.
{ 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
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
curl --request POST "${CADCAMFUN_URL}/api/better-auth-stripe/subscription" \
--header "Authorization: Bearer ${CADCAMFUN_TOKEN}" \
--header "Content-Type: application/json" \
--data-binary @request.json Попробуйте это
billing.baUpdate Требует Authorization: Bearer <token>.
{ 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
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
curl --request PUT "${CADCAMFUN_URL}/api/better-auth-stripe/subscription" \
--header "Authorization: Bearer ${CADCAMFUN_TOKEN}" \
--header "Content-Type: application/json" \
--data-binary @request.json Попробуйте это
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
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
curl --request DELETE "${CADCAMFUN_URL}/api/better-auth-stripe/subscription" \
--header "Authorization: Bearer ${CADCAMFUN_TOKEN}" Попробуйте это
/api/better-auth-stripe/billing-portal
billing.baPortal Требует Authorization: Bearer <token>.
{ 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
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
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
billing.baFeature Требует Authorization: Bearer <token>.
{ 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
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
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
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
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
curl --request POST "${CADCAMFUN_URL}/api/better-auth-stripe/sync" \
--header "Authorization: Bearer ${CADCAMFUN_TOKEN}" Попробуйте это
/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
{
"success": true,
"updatedCount": 0,
"message": "Successfully updated 0 expired trials",
"timestamp": "2026-10-15T04:52:23.475Z"
} Пример SDK
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
curl --request GET "${CADCAMFUN_URL}/api/cron/update-expired-trials" \
--header "Authorization: Bearer ${CADCAMFUN_TOKEN}" Попробуйте это
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
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
curl --request POST "${CADCAMFUN_URL}/api/cron/update-expired-trials" \
--header "Authorization: Bearer ${CADCAMFUN_TOKEN}" Попробуйте это
/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
{
"_tag": "StripeUnhealthy",
"status": "unhealthy",
"message": "Stripe is not configured on this installation",
"timestamp": "2026-10-15T04:52:23.476Z",
"service": "stripe"
} Пример SDK
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
curl --request GET "${CADCAMFUN_URL}/api/health/stripe" \
--header "Authorization: Bearer ${CADCAMFUN_TOKEN}" Попробуйте это
/api/webhooks/stripe
billing.stripeWebhook Требует Authorization: Bearer <token>.
string 200 объект application/json
{ received: true }
400 BadRequestEncoded application/json
BadRequestEncoded
401 UnauthorizedEncoded application/json
UnauthorizedEncoded
взять пример
// 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
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 }
InternalErrorEncoded{ _tag: "InternalError" message: string }
NotFoundEncoded{ _tag: "NotFound" message: string }
StripeUnhealthyEncoded{ _tag: "StripeUnhealthy" status: "unhealthy" message: string timestamp: string service: "stripe" }
Звонок в эту группу
Идентификаторы операций имеют вид billing.<name>. Сгенерированный Promise SDK (@cadcamfun/api/sdk) выставляет большинство из них как client.<namespace>.<method>(input), где input представляет собой один плоский объект параметров пути и полей тела; В примере SDK каждой карты показаны точный метод доступа и тип ввода. Многочастные загрузки, двоичные ответы или ответы JavaScript, а также необработанные веб-перехватчики не генерируются; эти карты показывают fetch вместо этого.
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 строка. |