PlanGate
Type to search every docs page
↑ ↓ to move↵ to openesc to close
DocsSign in

Sign users in

Every call to your model carries a session: the token of one user of your app. <app> is your app's short name, shown in the panel.

Your app either signs its users in itself (the first two ways, which can be combined) or lets PlanGate do it (the third):

All three work on the web, desktop, Android and iOS.

Use the account already on the phone

  1. In the panel, choose My app signs them in when you launch your app (or later in Settings → Sign-in, with Change).
  2. Fill in what your app uses:
    • Google: your OAuth web client ID. On Android it is the one you give Credential Manager as serverClientId; on iOS, give the same one to Google Sign-In as serverClientID.
    • Sign in with Apple: your app's bundle ID.
  3. In your app, send the ID token the system gave you to POST /apps/<app>/sign-in, as below. The answer is the session.

Filling in both lets the same app run on Android and iOS: a user who signs in with the same verified email on both is one user, with one plan.

Android: Google with Credential Manager

val option = GetGoogleIdOption.Builder()
    .setServerClientId(WEB_CLIENT_ID)
    .setFilterByAuthorizedAccounts(false)
    .build()
val result = CredentialManager.create(context)
    .getCredential(context, GetCredentialRequest(listOf(option)))
val idToken = GoogleIdTokenCredential.createFrom(result.credential.data).idToken

val body = JSONObject().put("token", idToken).toString()
    .toRequestBody("application/json".toMediaType())
val request = Request.Builder().url("https://api.plangate.dev/apps/my-agent/sign-in").post(body).build()
val session = JSONObject(http.newCall(request).execute().body!!.string())
val accessToken = session.getString("access_token")

iOS: Sign in with Apple

// In ASAuthorizationControllerDelegate, or SignInWithAppleButton's onCompletion
guard let credential = authorization.credential as? ASAuthorizationAppleIDCredential,
      let idToken = credential.identityToken.flatMap({ String(data: $0, encoding: .utf8) }) else { return }

var request = URLRequest(url: URL(string: "https://api.plangate.dev/apps/my-agent/sign-in")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONEncoder().encode(["token": idToken])
let (data, _) = try await URLSession.shared.data(for: request)

struct Session: Decodable { let access_token: String; let refresh_token: String; let expires_in: Int }
let session = try JSONDecoder().decode(Session.self, from: data)

Apple gives an identity token only when the user signs in: keep the session's refresh_token in the Keychain (see Keep the session).

React Native and the web

The same call with fetch. expo-apple-authentication gives the token as identityToken, @react-native-google-signin/google-signin as idToken, Google Identity Services on the web as credential.

const res = await fetch("https://api.plangate.dev/apps/my-agent/sign-in", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ token: idToken }),
})
const session = await res.json() // access_token, refresh_token, expires_in

Use the accounts your app already has

For Firebase Auth, Supabase, Auth0, Clerk, or a backend of yours that signs its own tokens.

  1. In the panel, choose My app signs them in (at launch, or Settings → Sign-in), and under Another provider enter the tokens' issuer (iss), their audience (aud), and either the address of the provider's keys (JWKS) or, for a backend of yours, its public key (PEM, RSA or EC P-256). Values for common providers:

    Provider Issuer Audience Keys (JWKS)
    Firebase Auth https://securetoken.google.com/<project-id> <project-id> https://www.googleapis.com/service_accounts/v1/jwk/[email protected]
    Supabase https://<ref>.supabase.co/auth/v1 authenticated https://<ref>.supabase.co/auth/v1/.well-known/jwks.json (asymmetric signing keys only)
    Auth0 https://<your Auth0 domain>/ (your custom domain if you use one, trailing slash) your client ID (ID tokens) or API identifier (access tokens) https://<your Auth0 domain>/.well-known/jwks.json
    Clerk your Frontend API URL none by default: add an aud claim with a JWT template (getToken({ template })) <Frontend API URL>/.well-known/jwks.json

    Firebase's own docs point to X.509 certificates: use the key set above instead.

  2. Send the token your sign-in gives the user to POST /apps/<app>/sign-in, exactly as in the examples above.

Anonymous users (Firebase anonymous sign-in, Supabase is_anonymous) are refused. What a token must contain is in the API reference.

Server key

Your backend signs users in with sessions or cookies of its own, and makes no JWT? It can name the user to PlanGate with the app's server key instead, as you would call Stripe with its secret key.

  1. In the panel, choose My app signs them in, then Create a server key. Copy it: it is shown once (it starts with pgsk_). Replace the key makes a new one, and the old one stops working at once.
  2. From your backend only, never from an app or a web page, call POST /apps/<app>/server-sign-in with the key as bearer token and your user's id. The answer is the user's session, as on /sign-in:
curl https://api.plangate.dev/apps/my-agent/server-sign-in \
  -H "Authorization: Bearer $PLANGATE_SERVER_KEY" \
  -H "Content-Type: application/json" \
  -d '{"user_id": "42", "email": "[email protected]", "name": "Ada"}'

user_id is the user's id in your app: the same id is always the same PlanGate user, created on first sign-in. email and name are optional; send email only once your app verified it, since a user who already has that email in the app (signed in before with PlanGate or a token) is the same user.

  1. Either call the models from your backend with the access_token, or hand the session to your app, which keeps it as below.

Use Sign in with PlanGate

  1. In the panel, choose PlanGate signs them in (at launch, or Settings → Sign-in).

  2. Open this address, in the system's browser:

    https://account.plangate.dev/connect?app=<app>&return=<return url>&state=<random>
    
  3. After sign-in, read access_token, refresh_token, expires_in and state from the return URL, and check that state is the one you sent.

The return URL depends on the platform:

  • A web app: an address under your app's Return link (panel, Settings → Payments), such as https://myagent.example/signed-in. The session comes in the fragment (#access_token=…): read it from location.hash, then clear it with history.replaceState.
  • A desktop app or a command-line tool: a loopback address your app listens on (http://127.0.0.1:<port>/…). The session comes in the query.
  • An Android or iOS app: your app's own URL scheme (myagent://signed-in), opened in Custom Tabs or ASWebAuthenticationSession, never in a WebView. The session comes in the query.

Any other address is refused.

Keep the session

The access token lasts an hour. Store the session where the platform keeps secrets (Keychain, EncryptedSharedPreferences, expo-secure-store), and renew it shortly before it expires, or when a call answers 401 unauthorized.

The simplest way is to sign in again with a fresh ID token. On Android, Credential Manager gives one silently for an account that already signed in, so nothing has to be stored.

Otherwise, refresh: POST /auth/refresh with {"refresh_token": "…"} answers a new session. Keep the new refresh token, since each one works once. Never refresh twice at the same time: the second call finds the token used and signs the user out.

Next: Call the model.

❌🕸️