# Apps

> Connect members' STX accounts to your app, act for them, and call app routes with an app token.

Source: https://docs.stxapp.io/sdks/go/apps/

> **Availability.** Available on US demo now. Live access is coming soon in the US and Ontario. See [Environments](https://docs.stxapp.io/environments/).

The `github.com/stxapp/stx-go/oauth` package runs the OAuth flows for an app registered with STX: it creates the PKCE verifier and `state`, exchanges the code, refreshes and rotates tokens, and revokes them. How the flow works, what each scope allows and how to handle tokens safely are covered in [OAuth](/oauth/) and [Build an app](/apps/); this page shows the SDK calls. Where the exchange does not offer OAuth yet, the calls return an error matching `stx.ErrNotAvailable`; see [What you can do](/sdks/go/capabilities/).

## Start from where you are

Pick the guide that matches your app; each runs end to end with this package.

| Your situation | Guide | With this package | Example |
| --- | --- | --- | --- |
| You have an app with its own accounts | [Connect your STX account](/oauth/connect-your-stx-account/) | `Begin` and `Complete` to link, a `TokenStore` keyed on your user id, `MemberClient` to act, `Unlink` (this page) | [connect-account](https://github.com/stxapp/stx-go/tree/main/examples/connect-account) |
| You're building a new app with no login yet | [Sign in with your STX account](/oauth/sign-in-with-your-stx-account/) | `oauth.NewSignIn`: `Start`, `Finish` (verified ID token), `UserInfo` ([Sign in with STX](/sdks/go/sign-in-with-stx/)) | [sign-in-with-stx](https://github.com/stxapp/stx-go/tree/main/examples/sign-in-with-stx) |
| You use a login service like Auth0 or Clerk | [Login services](/oauth/sign-in-with-your-stx-account/login-vendor/) | Keep your login and link STX accounts as in the first row, or act for members with the STX tokens the service passes on ([Sign in with STX](/sdks/go/sign-in-with-stx#with-a-login-service)) | [login-service](https://github.com/stxapp/stx-go/tree/main/examples/login-service) |

Create one `*oauth.Client` per registered app, on your server:

```go
app, err := oauth.New(oauth.Config{
	BaseURL:      "demo.stxapp.io",
	ClientID:     "stxapp_client_9f2c41d7",
	ClientSecret: os.Getenv("STX_OAUTH_CLIENT_SECRET"),
	RedirectURL:  "https://sideline.example.com/stx/callback",
	Scopes:       []string{oauth.ScopeBalanceRead, oauth.ScopePortfolioRead, oauth.ScopeOrdersWrite},
})
if err != nil {
	log.Fatal(err)
}
```

`oauth.Discover` does the same after reading the exchange's discovery document, so a scope the exchange does not offer is reported as `stx.ErrNotAvailable`. `oauth.ConfigFromEnv` reads the settings from `STX_HOST`, `STX_OAUTH_CLIENT_ID`, `STX_OAUTH_CLIENT_SECRET`, `STX_OAUTH_REDIRECT_URI` and `STX_OAUTH_SCOPE`.

## Connect a member's account

`Begin` on your connect route sends the member to STX; `Complete` on your callback checks `state`, exchanges the code and stores the tokens. The pending store holds the verifier between the two, and the token store keeps each member's tokens under your own key for them.

```go
pending := &oauth.MemoryPendingStore{}
tokens := oauth.NewFileTokenStore("/var/lib/sideline/stx-tokens.json")

http.HandleFunc("/stx/connect", func(w http.ResponseWriter, r *http.Request) {
	auth, err := app.Begin(r.Context(), pending, oauth.BeginParams{Data: map[string]string{"user": "u_1842"}})
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	http.Redirect(w, r, auth.URL, http.StatusFound)
})

http.HandleFunc("/stx/callback", func(w http.ResponseWriter, r *http.Request) {
	done, err := app.Complete(r.Context(), pending, r.URL.Query(), oauth.RedeemOptions{
		Store:         tokens,
		MemberKeyFunc: func(data map[string]string) string { return data["user"] },
	})
	switch {
	case errors.Is(err, oauth.ErrAccessDenied):
		fmt.Fprint(w, "Not connected.")
	case errors.Is(err, oauth.ErrAccountPending):
		fmt.Fprint(w, "Your STX account is still being verified.")
	case err != nil:
		http.Error(w, err.Error(), http.StatusBadRequest)
	default:
		fmt.Fprintf(w, "Connected with %v.", done.Scopes)
	}
})
```

`done.Scopes` are the scopes the member granted, which can be fewer than you asked for. `MemoryPendingStore` and `MemoryTokenStore` suit one process; for several, implement `oauth.PendingStore` and `oauth.TokenStore` on your database, and give the token store an `oauth.Locker` so concurrent refreshes happen once.

## Act for a member

`MemberClient` returns an ordinary `*stx.Client` that acts for one connected member. Every call carries their access token, refreshed before it expires and once on a 401, with the rotated refresh token stored each time. WebSocket connections send the token too.

```go
member, err := app.MemberClient(tokens, "u_1842", nil)
if err != nil {
	log.Fatal(err)
}
balance, err := member.Account.Balance(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(balance.AvailableBalance) // 746.8600
```

A call the grant does not cover returns an error matching `stx.ErrInsufficientScope`, with the scopes it needs in `APIError.RequiredScopes`. When the member revokes access at STX, the next refresh deletes their stored tokens and returns an error matching `oauth.ErrGrantRevoked`: send them through `Begin` again. A write from an address the app's IP allow-list lacks returns `stx.ErrIPNotAllowed`.

### When STX has new terms for the member

A call can return an error matching `stx.ErrTermsRequired` when the member has new STX terms to accept. Send them to `APIError.TermsURL`, with a way back to your app:

```go
_, err := member.Orders.Place(ctx, stx.OrderRequest{
	MarketID: marketID, Action: stx.Buy, OrderType: stx.Limit,
	Price: stx.MustDecimal("0.01"), Quantity: stx.MustDecimal("1"),
})
var apiErr *stx.APIError
if errors.Is(err, stx.ErrTermsRequired) && errors.As(err, &apiErr) {
	fmt.Println(oauth.TermsURLWithReturn(apiErr.TermsURL, "https://sideline.example.com/account"))
}
```

`oauth.SessionOptions.OnTermsRequired` tells you the same after a token refresh, before any call fails.

## Disconnect

```go
confirmed, err := app.Unlink(ctx, tokens, "u_1842")
if err != nil {
	log.Fatal(err)
}
fmt.Println("revoked at STX:", confirmed)
```

`Unlink` revokes the grant at STX and deletes the member's tokens from your store; the local tokens are deleted even when STX cannot be reached.

## Act as your app

An app token (the client credentials grant) calls the routes that belong to your app rather than a member: the market and event catalogs, the market data channels, and [creating markets](/sdks/go/create-markets/). `AppClient` returns an `*stx.Client` that fetches the token and renews it before it expires:

```go
appClient, err := app.AppClient([]string{oauth.ScopeMarketData, oauth.ScopeEvents})
if err != nil {
	log.Fatal(err)
}
page, err := appClient.Markets.List(ctx, &stx.MarketsQuery{Status: []string{"open"}, Limit: 5})
if err != nil {
	log.Fatal(err)
}
for _, m := range page.Items {
	fmt.Println(m.Symbol, m.LastTradedPrice)
}
// STXNHL-26OCT101600EDMSJ-GAMEEDM 0.5800
```

`app.AppToken(scopes...)` is the same token as an `stx.Auth` for `stx.WithAuth`, and `app.ClientCredentials` returns the raw token. A public client (no secret) cannot get an app token. Which scopes an app can hold is listed under [App scopes](/oauth/scopes/#app-scopes).

## Register a client

Where the exchange offers dynamic client registration, `oauth.Register` registers a client without a trip to the STX Apps console. The registration does nothing until a member consents:

```go
reg, err := oauth.Register(ctx, "demo.stxapp.io", oauth.ClientRegistrationRequest{
	ClientName:   "Sideline",
	RedirectURIs: []string{"https://sideline.example.com/stx/callback"},
}, nil)
if err != nil {
	log.Fatal(err)
}
fmt.Println(reg.ClientID)
```

## Errors

Errors from the OAuth endpoints are `*oauth.Error` values with the RFC `Code` (such as `invalid_grant`), `Description`, and STX's narrower `Reason`. They match the package's sentinels: `oauth.ErrAccessDenied` (the member said no), `oauth.ErrAccountPending` (their STX account is still being verified), `oauth.ErrTermsNotAccepted`, `oauth.ErrGrantRevoked`, `oauth.ErrInvalidState` and `oauth.ErrNotConnected` (no tokens stored for that member). See [Discovery and errors](/oauth/discovery-and-errors/).
