# Go SDK

> Use appsdk in a Go app for the install flow, session tokens, the app proxy, webhook signatures and the content API; keep installations in your own database and test with appsdktest.

`go.biticaret.com.tr/appsdk` lets you write an app's side of the platform contracts in Go: it verifies the signature on everything the platform sends, installs the app over OAuth, calls a store's app API and keeps installations. It depends only on the standard library. The contracts themselves are described in [App API](api.md), [Webhooks](webhooks.md) and [App proxy and admin page](storefront-and-admin.md); this page shows how to use them from Go.

## Install

```sh
go get go.biticaret.com.tr/appsdk
```

The module is being published. Until it is, the way in is the CLI's Go template: `biticaret app init my-app` generates a working app ([CLI](../cli.md)). The examples below use the same API as the code in that template.

Installations can be kept in PostgreSQL with a separate module: `go.biticaret.com.tr/appsdk/store/postgres`.

## The OAuth install flow

The steps of the flow are on the [App API](api.md#install-an-app) page. The SDK has a counterpart for each:

```go
verifier := appsdk.Verifier{Secrets: []string{clientSecret}}
platform := appsdk.Platform{StoreDomain: "mybiticaret.com.tr"}
oauth := appsdk.OAuth{ClientID: clientID, ClientSecret: clientSecret, Scopes: scopes, RedirectURI: appURL + "/oauth/callback"}

// application_url: the signed link the admin's Install and Open buttons open.
store, storeID, err := verifier.VerifyAppURL(r.URL.Query())
storeURL, err := platform.StoreURL(store)
state := rand.Text() // crypto/rand
http.SetCookie(w, &http.Cookie{Name: "oauth_state", Value: state, Path: "/oauth/callback", MaxAge: 600, HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode})
http.Redirect(w, r, oauth.AuthorizeURL(storeURL, state), http.StatusFound)

// Callback, a request of its own: verify the signed query, check state
// against the cookie, take the store from the signed query, exchange the code.
q := r.URL.Query()
err = verifier.VerifyQuery(q)
c, err := r.Cookie("oauth_state")
if err != nil || subtle.ConstantTimeCompare([]byte(c.Value), []byte(q.Get("state"))) != 1 {
	// 400: start the install again
}
storeURL, err := platform.StoreURL(q.Get("store"))
tok, err := oauth.Exchange(r.Context(), storeURL, q.Get("code"))
_, err = installs.Install(r.Context(), tok, q.Get("store"))
```

Generating `state`, binding it to the browser (in a cookie, as above) and comparing it in the callback is the app's job: without it, someone else's install could land in the merchant's session. The callback takes the store from its own signed `store`, never from the earlier request. `appsdktest/content_app_test.go` runs the whole flow. `Platform` makes sure the app only sends its secret and tokens to a real store host: `StoreURL` rejects any other address.

## Installations and InstallationStore

The app keeps an `Installation` record for each store that installed it: the store id, the store's host, scopes, timestamps and the sealed access token. The records live in the app's own storage; the SDK gives you only the `InstallationStore` interface and `Installations`, which applies the rules on top.

- **Stores.** `appsdk.NewMemoryStore()` for tests and apps without a database (its records go with the process). For PostgreSQL, `postgres.New(pool)`; run `postgres.Schema`, which creates the table, as your app's first migration, before your own tables that reference `store_id`. You can also implement the interface for your own store; every store should pass the `appsdktest.Storage` scenarios.
- **Sealed token.** The access token is sealed with AES-256-GCM, bound to the store id, before it reaches the store; the store sees only opaque bytes. Keys come from the `ENCRYPTION_KEYS` environment variable; each entry is `id:<64 hex characters>`, read with `appsdk.ParseEncryptionKey`. The first key seals new tokens and every key opens them; a key id listed twice is refused. To rotate, list the new key first, run `ResealAll(ctx)` once (or `Reseal(ctx, storeID)` per store), which seals every token again under the new key without touching the rest of the record, and drop the old key only after it has finished without an error.
- **Stores are found by id.** `Active(ctx, storeID)` returns the installed store; it gives `ErrNoInstallation` when there is no record and `ErrUninstalled` for an uninstalled store. Everything the platform sends (session token, proxy request, webhook) carries the store id; find the record by that id, not by a host.
- **Uninstall and delete.** On the `app/uninstalled` webhook, call `Uninstall(ctx, storeID, wh.TriggeredAt)`: the record stays, and a reinstall keeps `InstalledAt`. Only an installation saved no later than the event's time is marked, so a late retry of an old `app/uninstalled` leaves a store installed again since; the returned `bool` says whether the store is now uninstalled, so skip your own uninstall work when it is `false`. On the `store/redact` webhook, `Delete` removes the record, and with it your rows that reference it `ON DELETE CASCADE`. `UninstalledWebhook` and `StoreRedactWebhook` are both routes ready to mount (see Webhooks).

```go
var keys []appsdk.EncryptionKey
for _, s := range strings.Split(os.Getenv("ENCRYPTION_KEYS"), ",") {
	k, err := appsdk.ParseEncryptionKey(s)
	if err != nil {
		log.Fatal(err)
	}
	keys = append(keys, k)
}
installs, err := appsdk.NewInstallations(postgres.New(pool), keys...)

rec, err := installs.Active(ctx, storeID)
token, err := installs.Token(rec) // the opened token, for API calls
client := &appsdk.Client{StoreURL: storeURL, Token: token}
```

Where you read a record and then write it, do it in your own transaction and lock the row first:

```go
err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
	st := postgres.New(tx)
	if _, err := st.Lock(ctx, storeID); err != nil && !errors.Is(err, appsdk.ErrNoInstallation) {
		return err
	}
	_, err := installs.With(st).Install(ctx, tok, store)
	return err
})
```

`Lock` holds the row until the transaction ends (`FOR NO KEY UPDATE`): two installs or uninstalls for the same store at once can't overwrite each other, while foreign key checks aren't blocked. Because every code exchange revokes the previous token at once, code that calls the API should read the token from the saved record each time.

## Session tokens

Your page in the admin sends a session token from App Bridge ([App proxy and admin page](storefront-and-admin.md)). On the server, verify it as a token from the admin, then find the store by the token's `store_id`:

```go
// adminOrigin comes from your configuration, such as "https://admin.biticaret.com.tr".
tok, err := verifier.VerifyAdminSessionToken(appsdk.BearerToken(r), clientID, adminOrigin)
rec, err := installs.ForSession(r.Context(), tok)
```

Checkout UI extensions get tokens signed with the same secret and `aud`, but their `iss` is the store and their `sub` a buyer. `VerifyAdminSessionToken` refuses them: it requires `iss` to be `adminOrigin`, a staff member's `sub` and a `store_id`. `ForSession` takes only the `AdminSessionToken` it returns, so a token checked another way doesn't compile. A backend for a checkout extension uses `VerifyCheckoutSessionToken(token, clientID)` (`iss` must equal `dest`; `sub` is the customer, empty for a guest) and `ForCheckoutSession`; an admin token fails there. Both return `ErrBadSessionToken` or `ErrExpiredSessionToken`: answer 401.

`ForSession` returns `ErrBadSessionToken` for a token without a store id (answer 401), and `ErrNoInstallation` or `ErrUninstalled` for a store that doesn't have the app installed (answer 403). `appsdk.EmbeddedPage` serves the admin page shell: the design system, App Bridge and your app's `static` folder, with a policy that lets only the admin frame it.

## App proxy

Requests from the storefront to `/apps/<subpath>` reach your app with a signed query:

```go
pr, err := verifier.VerifyProxy(r.URL.Query())
rec, err := installs.ForProxy(r.Context(), pr)
```

`ProxyRequest` carries the store's host, `StoreID` and the signed-in customer's id (0 for a visitor). `ForProxy` finds the store by the signed `store_id`; for a store that doesn't have the app installed it returns `ErrNoInstallation` or `ErrUninstalled` (answer 404). Signature errors are `ErrNoSignature`, `ErrBadSignature` and `ErrStaleSignature` (401); a signed query without a valid `store_id` gives `ErrBadProxyQuery`.

## Webhooks

Topics, headers and retries are on the [Webhooks](webhooks.md) page. An endpoint dedicated to one topic checks the signature and the topic together with `VerifyWebhookTopic`; a signature made for another topic is not accepted at this address. `VerifyWebhook` refuses a delivery without `X-Biticaret-Signature` (`ErrWebhookSignature`). The signature must be within `appsdk.SignatureTolerance` (5 minutes); while a secret rotates, `Secrets` takes more than one.

```go
mux.Handle("POST /webhooks/app-uninstalled", installs.UninstalledWebhook(secrets...))
mux.Handle("POST /privacy/store-redact", installs.StoreRedactWebhook(secrets...))
mux.Handle("POST /webhooks/orders-paid", appsdk.WebhookHandler{
	Topic:   appsdk.TopicOrdersPaid,
	Secrets: secrets,
	Handle: func(ctx context.Context, storeID int64, wh appsdk.Webhook) error {
		return orders.Record(ctx, storeID, wh.Body)
	},
})
```

`WebhookHandler` checks the signature and topic with `VerifyWebhookTopic`, reads the body's `store_id` and runs `Handle`. It answers 401 for a signature or topic that doesn't verify, 400 for a body without `store_id`, 200 when `Handle` returns nil or `ErrNoInstallation`, and 500 for any other error; `OnError` hears every answer other than 200, for your log. To verify by hand, call `VerifyWebhookTopic` yourself. `Webhook` gives the body, topic, event id and store host. The same event can arrive more than once, so your handler must be safe to run again; any response other than 200 causes a retry. Constants exist for the privacy topics every app answers (`TopicCustomersDataRequest`, `TopicCustomersRedact`, `TopicStoreRedact`).

## The content API client

`Client` calls a store's app API with the installation's token. Paged lists take a `pageInfo` cursor and return the next one; `appsdk.Retryable(err)` tells whether an error may succeed later.

```go
c := &appsdk.Client{StoreURL: storeURL, Token: token}

products, next, err := c.ListProducts(ctx, "", 100)
p, err := c.GetProduct(ctx, productID)
variants, err := c.ProductVariants(ctx, p)
_, err = c.SetMetafield(ctx, appsdk.Metafield{
	OwnerType: appsdk.OwnerProduct, OwnerID: p.ID,
	Namespace: appsdk.AppNamespace("my-app", "seo"), Key: "title",
	Type: "single_line_text", Value: json.RawMessage(`"Hello"`),
})
```

There are methods for products, variants, collections, inventory, discounts, metafields, the payment app endpoints and more; the scopes each call needs are on the [App API](api.md) page.

## Testing with appsdktest

`go.biticaret.com.tr/appsdk/appsdktest` is a fake platform with one store: it answers the OAuth endpoints and the app API, sends your app signed requests the way the platform does, and records every call the app makes.

```go
p := appsdktest.New(t)
p.RedirectURI = app.URL + "/oauth/callback"
// Configure the app with p.ClientID, p.ClientSecret, p.AppSDK() and p.Transport().

res, err := http.Get(p.AppURLLink(app.URL + "/app")) // starts the install
res, err = p.SendWebhook(app.URL, appsdk.TopicOrdersPaid, map[string]any{"id": 1})
p.Uninstall() // the store uninstalls the app
```

`p.CallbackURL(state)` makes a signed OAuth callback and `p.SessionToken(staffID)` a session token. `appsdktest/content_app_test.go` in the SDK is a whole content app tested this way: install, an admin page call with a session token, `app/uninstalled` and `store/redact`. Ready-made checks exist too: `appsdktest.Storage{Store: s}.Run(t)` for every `InstallationStore`; `appsdktest.SessionStore` for apps with session tokens and `appsdktest.ProxyStore` for apps with an app proxy. Both check that the app finds the store by id and not by host, and refuses an uninstalled store.
