Developers

Developers

Apps And Devices

Phone and desktop apps, kiosks, scanners and points of sale can send screens and events with an app key, and show up on the same people’s paths as your website.

App keys come with any upgraded token plan. See Pricing.

Get An App Key

An app key goes inside your app. In Stattery, open the site, then Site Settings in the left menu and the Integrations tab. In API Keys, type a name (say “iPhone app”), choose App key (apps and devices) and press Make key. Copy it straight away: it starts stt_pk_ and is shown once.

Anyone can pull a key out of an app, so an app key can do very little: send screens and plain events, nothing else. It can’t send orders, payments, refunds or quotes, it reads nothing, and it can’t sign email links. For those, use a secret key on your server.

No website needed. An app key’s hits are taken without a web page’s address, so a kiosk, a scanner or a desktop app counts like a browser. The usual bot, flood and ban checks still apply.

Screens And Events

Send each screen to https://c.stattery.com/h, the same address and JSON the website tag uses, with the key in a header.

FieldWhat it is
sRequired. Your site as added to Stattery. The app’s visits show under it.
vRequired. A visitor id that stays the same for this install: make a random one on first launch and keep it.
kRequired. A session id: a new random one each time the app opens.
t"pv" for a screen.
uThe screen, written like a path: /screens/cart.
tiOptional. The screen’s title, shown in the path.
src, plat, verOptional. Where it came from (below). An app key says app unless you say kiosk or device.

Send events (a signup, a scan, a button) to https://c.stattery.com/e with { "s", "en", "ep", "v" }, the same as a server event. Both answer 204; a wrong or revoked key answers 401 { "error": "bad_key" }, so your app can tell.

Swift (iPhone And iPad)

import Foundation

enum Stattery {
    static let key = "stt_pk_your_app_key", site = "example.com"
    static let install: String = {
        if let v = UserDefaults.standard.string(forKey: "stt_v") { return v }
        let v = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
        UserDefaults.standard.set(v, forKey: "stt_v"); return v
    }()
    static let session = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
    static let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""

    static func send(_ path: String, _ body: [String: Any]) {
        var r = URLRequest(url: URL(string: "https://c.stattery.com" + path)!)
        r.httpMethod = "POST"
        r.setValue("Bearer " + key, forHTTPHeaderField: "Authorization")
        r.setValue("application/json", forHTTPHeaderField: "Content-Type")
        r.httpBody = try? JSONSerialization.data(withJSONObject: body)
        URLSession.shared.dataTask(with: r).resume()
    }
    static func screen(_ name: String, title: String = "") {
        send("/h", ["s": site, "v": install, "k": session, "t": "pv", "u": "/screens/" + name, "ti": title,
                    "src": "app", "plat": "ios", "ver": version])
    }
    static func event(_ name: String, _ props: [String: Any] = [:]) {
        send("/e", ["s": site, "v": install, "en": name, "ep": props, "src": "app", "plat": "ios", "ver": version])
    }
}

// Stattery.screen("cart", title: "Cart")
// Stattery.event("Signup", ["plan": "pro"])

Kotlin (Android)

// Android, with OkHttp 4. Call from a background thread or a coroutine.
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody

object Stattery {
    private const val KEY = "stt_pk_your_app_key"; private const val SITE = "example.com"
    private val http = okhttp3.OkHttpClient()
    private val session = java.util.UUID.randomUUID().toString().replace("-", "")
    private lateinit var install: String; private lateinit var version: String

    fun init(ctx: android.content.Context) {
        val prefs = ctx.getSharedPreferences("stattery", 0)
        install = prefs.getString("v", null) ?: java.util.UUID.randomUUID().toString().replace("-", "").also { prefs.edit().putString("v", it).apply() }
        version = ctx.packageManager.getPackageInfo(ctx.packageName, 0).versionName ?: ""
    }
    private fun send(path: String, body: org.json.JSONObject) {
        val req = okhttp3.Request.Builder().url("https://c.stattery.com$path")
            .header("Authorization", "Bearer $KEY")
            .post(body.toString().toRequestBody("application/json".toMediaType())).build()
        http.newCall(req).execute().close()
    }
    fun screen(name: String, title: String = "") = send("/h", org.json.JSONObject(mapOf(
        "s" to SITE, "v" to install, "k" to session, "t" to "pv", "u" to "/screens/$name", "ti" to title,
        "src" to "app", "plat" to "android", "ver" to version)))
    fun event(name: String, props: Map<String, Any> = emptyMap()) = send("/e", org.json.JSONObject(mapOf(
        "s" to SITE, "v" to install, "en" to name, "ep" to org.json.JSONObject(props),
        "src" to "app", "plat" to "android", "ver" to version)))
}

JavaScript

// Electron, React Native, a kiosk page or any JavaScript app.
const KEY = 'stt_pk_your_app_key', SITE = 'example.com';
const rand = () => crypto.randomUUID().replace(/-/g, '');
let install = localStorage.getItem('stt_v');
if (!install) { install = rand(); localStorage.setItem('stt_v', install); }
const session = rand();
const base = { src: 'kiosk', plat: 'windows', ver: '2.4.0' };
const send = (path, body) => fetch('https://c.stattery.com' + path, {
  method: 'POST', headers: { 'Authorization': `Bearer ${KEY}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ s: SITE, v: install, ...base, ...body }),
});
export const screen = (name, title = '') => send('/h', { k: session, t: 'pv', u: '/screens/' + name, ti: title });
export const event = (name, props = {}) => send('/e', { en: name, ep: props });

curl

# A screen
curl https://c.stattery.com/h -H "Authorization: Bearer stt_pk_your_app_key" -H "Content-Type: application/json" \
  -d '{ "s": "example.com", "v": "install-id", "k": "session-id", "t": "pv", "u": "/screens/cart", "ti": "Cart",
        "src": "app", "plat": "ios", "ver": "3.1.0" }'

# An event
curl https://c.stattery.com/e -H "Authorization: Bearer stt_pk_your_app_key" -H "Content-Type: application/json" \
  -d '{ "s": "example.com", "v": "install-id", "en": "Signup", "ep": { "plan": "pro" }, "src": "app", "plat": "ios" }'

Sources

Every hit and event can say where it came from. Nothing sent means a website, as before.

FieldValues
srcweb, app, kiosk, device, api, email, webhook, pos, other
platios, android, windows, mac, linux, web, other. Anything else becomes other.
verYour app’s version, up to 30 characters.

In Stattery, People shows a small icon after the name of anyone who came from somewhere other than a website; hover over it for the platform and version. The live feed and the visit’s path show it too, and the visitor’s details say From. Once anyone has come from an app, a kiosk or a server, a From filter appears beside Companies, to show one source at a time.

Good To Know

  • Send a screen when it opens, not on a timer. Stattery works out time on screen from the next one.
  • To tie the install to a person once they sign in, send an event from your server with the same v and their email’s hash (gh), using a secret key.
  • A user agent that looks like a script (for example python-requests) is still counted as a bot.
  • An order sent with an app key is dropped or refused, however it is sent.
  • Revoke a key in the same list; it stops working within a minute.