# App API

> Install and authenticate an app, sign and verify requests, and call the /api/v1 resources with their scopes; billing, pagination, errors and rate limits.

An app installs on a store using the OAuth 2.0 authorization code flow, receives an access token, and calls the store's `/api/v1` endpoints with it. This page covers installation, request signing, resources and scopes, billing, pagination, errors and rate limits. If you are building in Go, the [Go template](https://github.com/biticaret/app-template-go) already implements all of this.

## Install an app

1. **Start.** The store owner initiates installation from the admin. The platform opens the app's `application_url` with a signed query: `store` (the store's hostname), `store_id` (the store's numeric ID) and `signature`.
2. **Request authorization.** The app generates a random `state`, stores it (in a cookie, for example), and redirects the browser to the store:

   ```
   https://<store>/oauth/authorize?client_id=…&scope=…&redirect_uri=…&state=…
   ```

   `state` is owned by the app. `redirect_uri` must match one of the configured `auth.redirect_urls` values verbatim.
3. **Consent.** The consent screen lists the scopes the app requests, and the store owner approves them. If the app is already installed with all requested scopes, this screen is skipped.
4. **Callback.** The platform redirects to `redirect_uri` with `code`, `store`, `state` and `signature`. Verify the signature first, then verify that `state` matches the stored value.
5. **Token exchange.** The app exchanges the authorization code for an access token:

   ```http
   POST /oauth/access_token HTTP/1.1
   Host: <store>
   Content-Type: application/x-www-form-urlencoded

   client_id=…&client_secret=…&code=…
   ```

   ```json
   { "access_token": "bt_app_…", "scope": "…", "store_id": 1000000000001 }
   ```

   Authorization codes are single-use and expire after 60 seconds. Error responses: `401 invalid_client`, `400 invalid_grant`, `400 invalid_request`.

**The token** remains valid until the app is uninstalled. Each code exchange issues a new token and immediately revokes the installation's previous one: persist the token from every exchange and read the latest stored token on each request.

**Key your records by `store_id`.** A store's domain can change; its numeric ID never does.

**Open the app.** Clicking **Aç** (Open) in the admin opens `application_url` with the same signed query parameters as step 1. The signed query proves that the platform generated the link, not who is presenting it: it stays valid for 5 minutes and can leak. Do not establish an authenticated session solely on that query. If you do not yet have a session for the store, run OAuth from step 2—because the app is already installed, the platform redirects straight back.

## Verify signatures

Everything the platform sends to your app is signed with the app's client secret.

- **Signed redirects** (steps 1 and 4) carry the signature in the `signature` query parameter formatted as `t=<unix seconds>,v1=<hex>`. `v1 = hex(HMAC-SHA256(client_secret, t + "." + query))`, where `query` consists of all other query parameters sorted by name and URL-encoded. Verify the signature before trusting `store`, `store_id` or `code`.
- **Requests with a body** include the `x-biticaret-signature: t=…,v1=…` header, where `v1 = hex(HMAC-SHA256(client_secret, t + "." + raw body))`. Webhooks use a different signing format: see [Webhooks](webhooks.md#verify-the-signature).
- Verify signatures against the raw request bytes before parsing, using a constant-time comparison. Reject any `t` more than 5 minutes from the current time.
- **Rotating the secret.** You can rotate the client secret in the partner portal. The previous secret remains valid for the grace period you choose (1 hour, 24 hours or 7 days). During that window, `x-biticaret-signature` includes one `v1=` per active secret, and code exchange accepts either secret.

## Make a call

```http
GET /api/v1/shop HTTP/1.1
Host: <store>
Authorization: Bearer bt_app_…
```

Requests must target the store that issued the token. Responses are wrapped in `{ "data": … }`. IDs are JSON numbers, monetary amounts are in kuruş (fields ending in `_cents`), and timestamps are RFC 3339. Send request bodies with `Content-Type: application/json`.

## Resources

Every resource path below is under `/api/v1`. Every write scope implies the corresponding read scope for the same resource (`write_orders` includes reading orders). For what each scope grants, see [Scopes](../reference/scopes.md). For the full code-generated list of routes—including which routes are paginated—see [App API routes](../reference/api-routes.md).

| Path | Scope |
| :--- | :--- |
| `GET /shop` | None |
| `GET /products`, `GET /products/{id}`, `GET /products/{id}/variants` | `read_products` |
| `POST /products`, `PUT /products/{id}`, `PUT /variants/{id}/cost` | `write_products` |
| `GET /collections`, `GET /collections/{id}` | `read_products` |
| `PUT /variants/{id}/inventory` | `write_inventory` |
| `GET /locations` | `read_locations` |
| `GET /inventory_levels`, `GET /inventory_levels/history` | `read_inventory` |
| `PUT /inventory_levels`, `POST /inventory_levels/adjust`, `POST /inventory_levels/move` | `write_inventory` |
| `GET /orders`, `GET /orders/{id}`, `GET /orders/{id}/refunds` | `read_orders` |
| `PUT /orders/{id}`, `POST /orders/{id}/cancel`, `POST /orders/{id}/refunds` | `write_orders` |
| `POST /orders/{id}/fulfillments`, `PUT /orders/{id}/fulfillments/{fulfillmentID}`, `POST /orders/{id}/fulfillments/{fulfillmentID}/cancel`, `POST /orders/{id}/fulfillments/{fulfillmentID}/events` | `write_fulfillments` |
| `POST /orders/{id}/capture` | `write_payments` |
| `GET /customers`, `GET /customers/{id}` | `read_customers` |
| `GET /customer_segments`, `GET /customer_segments/{id}`, `GET /customer_segments/{id}/customers` | `read_customers` |
| `PUT /customers/{id}` | `write_customers` |
| `GET /marketing/audience` | `read_marketing_audience` |
| `POST /customers/{id}/marketing_consent` | `write_marketing_consent` |
| `GET`, `POST /discount_codes`; `GET`, `PUT`, `DELETE /discount_codes/{id}` | `write_discounts` |
| `GET /gift_cards`, `GET /gift_cards/{id}` | `read_gift_cards` |
| `POST /gift_cards`, `PUT /gift_cards/{id}`, `POST /gift_cards/{id}/disable` | `write_gift_cards` |
| `GET /draft_orders`, `GET /draft_orders/{id}` | `read_draft_orders` |
| `POST /draft_orders`; `PUT`, `DELETE /draft_orders/{id}`; `POST /draft_orders/{id}/complete`, `POST /draft_orders/{id}/send_invoice` | `write_draft_orders` |
| `GET /companies`, `GET /companies/{id}` | `read_companies` |
| `POST /companies`; `PUT`, `DELETE /companies/{id}`; `POST /companies/{id}/locations`; `PUT`, `DELETE /companies/{id}/locations/{locationID}`; `POST /companies/{id}/contacts`; `PUT`, `DELETE /companies/{id}/contacts/{customerID}` | `write_companies` |
| `POST /channels`; `GET /channels/{id}/products`; `PUT`, `DELETE /channels/{id}/products/{productID}`; `POST /channels/{id}/orders` | `write_channels` |
| `GET /metaobject_definitions`, `GET /metaobject_definitions/{id}`, `GET /metaobjects`, `GET /metaobjects/{id}` | `read_metaobjects` |
| `POST /metaobject_definitions`; `PUT`, `DELETE /metaobject_definitions/{id}`; `POST /metaobjects`; `PUT`, `DELETE /metaobjects/{id}` | `write_metaobjects` |
| `GET /translations` | `read_translations` |
| `PUT /translations` | `write_translations` |
| `GET`, `PUT /pixels/{pixelID}/settings` | `write_pixels` |
| `POST /sms`, `POST /sms/{id}/status` | `write_sms` |
| `GET`, `PUT`, `DELETE /metafields` | None (see [Metafields](#metafields)) |
| `GET /webhook_deliveries`, `POST /webhook_deliveries/{id}/replay` | None |
| `GET /function_runs` | None |
| `GET /billing/plans`; `GET`, `POST /billing/subscriptions`; `GET /billing/subscriptions/{id}`; `POST /billing/subscriptions/{id}/cancel`; `POST /billing/subscriptions/{id}/usage_records`; `GET`, `POST /billing/credits` | None |

`POST /emails` (`write_emails`) is restricted to biticaret's own first-party apps. Payment app session endpoints are not covered here: for now, payment apps are first-party only, and third-party payment apps cannot yet be published.

### Customer data levels

An app whose scopes or features access customer data must declare a level and a reason in the `[customer_data]` block of its configuration ([Configuration](configuration.md#biticaret-app-toml)):

| Level | Access granted |
| :--- | :--- |
| 0 | No customer data. |
| 1 | Customer data without names or contact details. |
| 2 | Customer data including names and contact details. |

The level is reviewed and approved per app version. The sections below specify which level each endpoint and field requires. Calling an endpoint or requesting fields above the approved level returns `403 customer_data_not_approved`.

### Shop

`GET /shop` requires no scope. It returns `id`, `name`, `domain`, `url`, `primary_url` (the storefront URL on the store's primary domain: the primary custom domain once active, otherwise `url`), `email`, `phone`, `locale`, `currency`, `logo_url`, `logo_width`, `plan` (`handle`, `name`) and `partner_development` (`true` on development stores).

### Products

Products (`/products`) include their options, variants and images. Each product embeds up to its first 250 variants in position order. `variants_count` gives the total; if there are more, `variants_truncated` is `true` and `GET /products/{id}/variants` paginates through all variants (`products/*` webhooks follow the same structure). A product can have at most 2,048 variants.

- `PUT /products/{id}` updates only the fields you send. If you include `variants`, it replaces the variant list, while any variant carrying an `id` retains omitted fields.
- Setting `inventory_quantity` on a new variant requires `write_inventory`; on an existing variant it is rejected (adjust stock through `/inventory_levels`).
- Each variant also includes `image_id` and `compare_at_price_lawful`. That flag is `true` when `compare_at_price` is higher than the sale price and does not exceed the lowest price recorded in the 10 days before the current price took effect—so the store may lawfully display it struck through as a previous price.
- `PUT /variants/{id}/cost` with `{"cost_cents": …}` updates only the variant's cost.
- `cost_cents` is populated only when the app holds `read_product_costs`.

### Customers

Customers (`/customers`) return `id`, `email`, `first_name`, `last_name`, `phone`, `note` (the merchant's private note on the customer), `accepts_marketing`, `email_marketing_consent`, `sms_marketing_consent`, `tags`, `orders_count`, `total_spent_cents`, `default_address`, `created_at` and `updated_at`.

- Name, email, phone, address and `note` require customer data level 2; at level 1 these fields are omitted/empty.
- `PUT /customers/{id}` updates only `tags`. `note` can be read (at level 2) but cannot be modified by an app.
- Customer segments (`/customer_segments`) are the store's saved customer filters: `id`, `name`, `rules`, `created_at`, `updated_at`. `GET /customer_segments/{id}/customers` paginates through customers currently matching the segment in the same format as `/customers`.

### Discounts

A discount (`/discount_codes`) is either code-based or automatic. `method` is `code` or `automatic` and can only be set on creation. An automatic discount has an empty `code`: it applies to every eligible checkout without requiring the buyer to enter anything, and appears in the cart under its `title`.

- `discount_type` is `percentage`, `fixed_amount`, `free_shipping` or `buy_x_get_y`.
- For `buy_x_get_y`, `value` is the percentage discount on the Y items in basis points (`10000` means free), `applies_to` specifies the Y side, and `buy_x_get_y` (`{buy_quantity, buys, get_quantity, uses_per_order}`) defines the X side and quantities. A `null` `uses_per_order` means no per-order limit.
- `combines_with` (`{product, order, shipping}`) specifies which discount classes this discount can combine with. When discounts conflict, the buyer automatically receives the combination that saves them the most.
- `min_quantity` sets the minimum item quantity required.
- When `buyer_eligibility` is `segments`, `customer_segment_ids` lists eligible segments; when `customers`, `customer_ids` lists eligible customers; when `locations`, `company_location_ids` lists eligible B2B company locations. For `segments` and `customers`, only signed-in customers qualify—guest buyers belong to no segment and cannot match chosen customer IDs.
- Below customer data level 1, `company_location_ids`, `customer_segment_ids` and `customer_ids` return `null`, and sending them in write requests is rejected.

### Marketing consent

Marketing consent is stored centrally on the store. Marketing apps read their audience from the store and write every opt-out back here, so a customer who unsubscribes in one place is unsubscribed everywhere. Both endpoints require customer data level 2; below level 2 they return `403 customer_data_not_approved`.

`GET /marketing/audience?channel=email` paginates through customers reachable by the store's email campaigns: customers who granted consent, have not requested erasure, and whose address is not suppressed (due to a hard bounce or complaint). Each entry returns `id`, `email`, `first_name`, `locale`, `consent_updated_at` and `source`. `channel=sms` returns customers with SMS consent for a Turkish mobile number and no erasure request, returning `phone` (in E.164 format) instead of `email`.

With `read_customers`, each customer record also includes `email_marketing_consent` and `sms_marketing_consent`, carrying `state` (`subscribed`, `unsubscribed` or `not_subscribed`), `consent_updated_at`, `source` and—for active SMS consent—`phone`.

`POST /customers/{id}/marketing_consent` updates a customer's marketing consent:

```json
{ "channel": "email", "state": "unsubscribed" }
```

- `"state": "unsubscribed"` always withdraws consent.
- `"state": "subscribed"` requires proof: `collected_at` (RFC 3339 timestamp when the customer consented) and `consent_text` (the exact text they agreed to, up to 2,000 characters). Include `ip` and `user_agent` when available. Consent requests without proof return `422 invalid_request`.
- If `collected_at` precedes the customer's most recent consent change, the call returns `409 consent_superseded`. If the customer has requested erasure, it returns `409 erasure_requested`.
- The recorded source is `app:<app>`. An SMS provider app records opt-outs performed in IYS with `"source": "iys"`.
- `channel=sms` requires the same proof and records consent against the customer's phone number. If the number is not a valid Turkish mobile number, the call returns `422 no_mobile_number` without changing anything. If SMS consent is already granted (for any number), granting it again is a no-op.
- When withdrawing SMS consent, you may pass `phone`: the opt-out is applied only if that number matches the customer's currently consented SMS number; otherwise nothing is written and `changed` is `false`. Numbers are normalised to E.164 just as when granting consent. Passing `phone` for `email`, when granting consent, or with a non-Turkish mobile number returns `422`.
- SMS consent and email consent are completely independent.
- The response returns the customer's current consent state, and `changed` indicates whether this request altered it. Repeating a request with the same `Idempotency-Key` header returns the original response.

Every consent change emits the `customers/marketing_consent_update` webhook ([Webhooks](webhooks.md#customers-marketing-consent-update)).

### Metafields

Metafields require no separate scope. Every app can always read and write its own namespaces; accessing another app's or custom namespaces on a resource requires that resource's scope.

### Orders and fulfillments

Orders (`/orders`) include their line items, fulfillments, refunds, discount codes and sales channel. Tax breakdown is in `tax_lines`—one entry per VAT rate (`rate_bps`, `base_cents`, `tax_cents`) as recorded on the order—and shipping lines carry their own `tax_cents`. Below customer data level 2, `note` (along with `note_attributes` and addresses) is omitted when reading orders, and `PUT /orders/{id}` ignores `note`, keeping the existing note unchanged.

Fulfillments require `write_fulfillments`:

- `POST /orders/{id}/fulfillments` accepts `line_items` (`line_item_id`, `quantity`; omit or leave empty to fulfill all remaining unfulfilled items), tracking details and `notify_customer`.
- `PUT /orders/{id}/fulfillments/{fulfillmentID}` updates tracking details and `notify_customer` on an existing fulfillment.
- A shipping app cancels a fulfillment with `POST /orders/{id}/fulfillments/{fulfillmentID}/cancel` (returning the items to unfulfilled status) and reports shipment progress with `POST /orders/{id}/fulfillments/{fulfillmentID}/events`: `{"status": "in_transit" | "delivered" | "failed", "message": "…"}`.
- Sending the same status twice is a no-op, and posting an event to a cancelled fulfillment returns `409`. Each new status is recorded in the order timeline under the app's name.

### Inventory

`POST /inventory_levels/adjust` accepts `variant_id`, `location_id`, a signed `amount`, `deny_negative` (returns `409 insufficient_stock` if stock would drop below zero), `reason` (`app` by default; or `received`, `damaged`, `lost`, `correction`) and an optional `note` of up to 200 characters. Repeating the call with the same `Idempotency-Key` header returns the original result.

`GET /inventory_levels/history` returns every stock change, newest first. Filter by `variant_id`, `location_id` and `created_at_min` (RFC 3339); omitting all filters returns the entire store's history. Each entry includes `variant_id`, `location_id`, `delta`, `available_after`, `reason` (`manual`, `order`, `order_cancel`, `restock_refund`, `checkout_release`, `move`, `app`, `import`, `correction`, `received`, `damaged`, `lost`), `order_id` (the order's numeric ID, or `null`), `actor_type` (`staff`, `app` or `system`; actor names are not exposed) and `created_at`. The history contains no customer data, and staff notes are visible only in the admin.

### Metaobjects

Metaobjects (`/metaobject_definitions`, `/metaobjects`) store custom data types and their entries.

- Create or replace a definition with `{"metaobject_definition": {type, name, description, display_name_key, fields, web_pages, url_handle, access}}`. `type` can only be set on creation, and `PUT` replaces the entire `fields` list. A definition can have at most 40 fields.
- Create or update an entry with `{"metaobject": {type, handle, status, fields}}`, where `status` is `draft` or `active`. `PUT` updates only the fields you send.
- `GET /metaobjects?type=…` lists entries of one type, newest first. It paginates like other list endpoints, and `type` is required.
- **App-owned types.** A type named `$app:<name>` belongs exclusively to the app that created it: other apps cannot see it (`404`) or modify it. `access.admin` (`merchant_read` or `merchant_read_write`) controls whether merchants can only view entries in the admin or also edit them. `access.storefront` (`none` or `public_read`) controls storefront visibility. New types default to `merchant_read` and `none`.

### Translations

`GET` and `PUT /translations` accept these `resource_type` values: `product`, `product_option`, `product_option_value`, `product_variant`, `collection`, `page`, `blog`, `article`, `menu`, `metaobject` and `legal_template`. Theme strings are translated only in the admin. Any other `resource_type` returns `422` along with the accepted values.

### Gift cards

`POST /gift_cards/{id}/disable` reads no payload: call it with an empty body or `{}`. If a body is sent, it must be valid `application/json`, or the call returns `400 invalid_json`.

### SMS

`POST /sms` (`write_sms`) with `{"order_id": …, "body": "…"}` sends a transactional SMS to the order's recipient. The platform reads the phone number from the order and routes the message to the store's SMS provider app. It responds with `202` and `{id, status, encoding, segments, …}`; neither the phone number nor the body is echoed back.

- If the store has no SMS provider configured, the call returns `409 no_sms_provider`. If the order has no mobile number, it returns `422 no_phone`.
- Sending an `Idempotency-Key` header prevents duplicate sends when retrying.
- The SMS provider app (`sms_provider = true`) reports the outcome of an SMS received via `sms/send` by calling `POST /sms/{id}/status`: `{"status": "sent" | "delivered" | "failed", "provider_message_id": "…", "error": "…"}`. Calling this for another app's SMS returns `404`, and status transitions only move forward.

### Company tax IDs

A sole proprietorship's 11-digit tax number is returned unmasked only if the app holds `read_company_tax_ids`.

## Billing

Apps bill stores directly for their own charges. Billing endpoints require no scope, and each app sees only its own charges. Amounts are in kuruş excluding VAT; biticaret's invoice adds VAT. These endpoints are for public apps only: private apps receive `403 billing_not_available`.

1. `POST /billing/subscriptions` accepts `name`, `price_cents` (monthly price), `return_url`, and optionally `trial_days` and `test`. For usage-based billing, add `capped_amount_cents` (monthly cap) and `usage_terms`. You must provide at least one of a monthly price or usage terms. A `test` charge is never billed.
2. Redirect the merchant's browser to the returned `confirmation_url`. The merchant approves or declines in the admin, and the browser returns to `return_url?charge_id=<id>`.
3. Status updates arrive via the `app_subscriptions/update` webhook: `pending`, `active`, `declined`, `cancelled`, `frozen` (the store's invoice is overdue or the app is suspended; returns to `active` once resolved), `expired` (the merchant did not respond within 2 days) and `scheduled` (a plan queued to start when an annual plan's term ends, at `starts_at`).
4. `POST /billing/subscriptions/{id}/usage_records` with `{description, price_cents, idempotency_key}` records a usage charge. Monthly usage cannot exceed `capped_amount_cents`. `balance_used_cents` tracks usage recorded so far in the current billing month.

**Plans.** If an app defines pricing plans in the partner portal (managed pricing), the merchant selects a plan on the app's plan page, and `GET /billing/plans` returns the pricing mode and available plans. Plans are either monthly (`interval` `monthly`, billed at month end) or annual (`annual`, billed at the start of each plan year) and may include a usage component. Charges created from a plan have `plan` populated; self-created charges are always monthly. Calling `POST /billing/subscriptions` on a managed-pricing app returns `409 managed_pricing`.

**Credits.** `GET` and `POST /billing/credits` read and issue store credits granted by the app.

## Pagination

List endpoints accept `limit` (1 to 100, default 25) and return items newest first. Responses include the next-page cursor in both the `Link` header and the JSON body:

```http
Link: <…?limit=25&page_info=…>; rel="next"
```

```json
{ "data": [], "page_info": { "next": "…", "previous": null } }
```

Pass the `page_info` value back verbatim to fetch the next page. Treat the cursor as an opaque string.

## Errors

Error responses return an HTTP status code and the following JSON body:

```json
{ "error": { "code": "…", "message": "…" } }
```

`code` is stable and intended for programmatic handling; `message` is human-readable and may change.

| Status | Code | Meaning |
| :--- | :--- | :--- |
| `400` | `invalid_json` | The body is not valid JSON of the expected shape, or lacked `application/json`. |
| `401` | `invalid_token` | The access token is missing, unknown, revoked or belongs to another store. |
| `403` | `missing_scope` | The token lacks the scope required by this endpoint. |
| `403` | `customer_data_not_approved` | The endpoint or field requires a higher customer data level than approved. |
| `404` | `not_found` | No matching resource exists in this store for this app. |
| `409` | `conflict` and route-specific codes | The request conflicts with the resource's current state (such as `inventory_changed`, `insufficient_stock`, `consent_superseded`). |
| `422` | `invalid_request` | The JSON is well-formed, but validation failed. |
| `422` | `idempotency_key_reused` | The same `Idempotency-Key` was reused with a different request payload. |
| `423` | `store_suspended` | The store is suspended: all calls are rejected except results for open payment sessions. |
| `429` | `rate_limited` | The rate limit has been reached; wait for `Retry-After` seconds. |
| `503` | `store_moving` | The store is migrating to another server for a few minutes. Reads succeed; retry writes and code exchanges after `Retry-After`. |
| `5xx` | `internal_error` | An internal platform error occurred; retrying the same request may succeed later. |

`400`, `409` and `422` reject the request itself: retrying the exact same payload will fail the same way.

## Rate limit

Each app installation has a leaky-bucket quota with a capacity of 40 requests, draining at 2 requests per second. This limit currently applies to all store plans. Every response for a valid token reports current bucket usage:

```http
x-biticaret-api-call-limit: 14/40
```

When the bucket is full, requests receive `429 rate_limited` with a `Retry-After` header in seconds.
