### Quick Start Example Source: https://docs.starti.app/ A basic HTML structure demonstrating how to load the starti.app SDK, initialize it, and check if the application is running within the native app environment. ```APIDOC ## Quick Start Example ### Description This example shows how to set up a basic HTML page with the starti.app SDK, initialize it, and check if it's running within the native app. It also demonstrates how to get the device platform (iOS or Android). ### Code ```html
You are using the native app!
Download our app for the best experience.
``` ### Notes - The `startiapp` object is globally available after loading the script. - The `ready` event is fired when the SDK is fully loaded and ready to be used. - `startiapp.initialize()` must be called to set up the SDK. - `startiapp.isRunningInApp()` returns a boolean indicating if the code is executing within the native app container. ``` -------------------------------- ### Quick Start: Initialize starti.app SDK and Check Environment Source: https://docs.starti.app/ This example demonstrates how to load the starti.app SDK, initialize it upon the 'ready' event, and check if the application is running within the native starti.app environment. It also shows how to retrieve the device platform (iOS or Android). ```javascriptYou are using the native app!
Download our app for the best experience.
``` -------------------------------- ### Complete Working Example: Register User and Listen for Notifications Source: https://docs.starti.app/getting-started/push-notifications A comprehensive example demonstrating the initialization of the SDK, requesting notification permissions, registering the user, and setting up listeners for foreground notifications and token refreshes. ```APIDOC ## Complete Working Example ### Description This example shows a complete workflow for setting up push notifications, including initialization, permission requests, user registration, and handling foreground notifications and token refreshes. ### Initialization and Permission Request ```javascript async function main() { if (!startiapp.isRunningInApp()) return; await startiapp.initialize(); // Request permission const granted = await startiapp.PushNotification.requestAccess(); if (!granted) { console.log("User denied notifications."); showOptInBanner(); return; } // Register the user — this handles FCM token management automatically const userId = getCurrentUserId(); // your own function if (userId) { await startiapp.User.registerId(userId); } // Optionally, load and display topics const topics = await startiapp.PushNotification.getTopics(); renderTopicList(topics); } main(); ``` ### Example with Token Registration and Event Listeners ```javascript async function main() { if (!startiapp.isRunningInApp()) return; await startiapp.initialize(); // Request permission const granted = await startiapp.PushNotification.requestAccess(); if (!granted) { console.log("User denied notifications."); showOptInBanner(); return; } // Get and send the FCM token to your server const token = await startiapp.PushNotification.getToken(); await registerTokenOnServer(token); // Listen for foreground notifications startiapp.PushNotification.addEventListener( "notificationReceived", function (event) { showNotificationBanner(event.detail.title, event.detail.body); }, ); // Handle token refresh startiapp.PushNotification.addEventListener("tokenRefreshed", function (event) { registerTokenOnServer(event.detail); }); // Optionally, load and display topics const topics = await startiapp.PushNotification.getTopics(); renderTopicList(topics); } async function registerTokenOnServer(token) { await fetch("/api/push/register", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fcmToken: token }), }); } main(); ``` ``` -------------------------------- ### Vue 3 Example: Initialize and Get Platform Source: https://docs.starti.app/explanation/typescript-support A Vue 3 component using the Composition API with `Platform: {{ platform || "web" }}
``` -------------------------------- ### Complete Share and Download Example with starti.app SDK Source: https://docs.starti.app/how-to/share-content A comprehensive example demonstrating how to initialize the starti.app SDK and attach event listeners to buttons for sharing text and downloading files. This showcases practical implementation of the sharing and download functionalities. ```javascript await startiapp.initialize(); // Share button document.getElementById("share-btn").addEventListener("click", async () => { await startiapp.Share.shareText("Join me on this app!"); }); // Download button document.getElementById("download-btn").addEventListener("click", async () => { await startiapp.Share.downloadFile( "https://api.example.com/export/data.csv", "export.csv", ); }); ``` -------------------------------- ### React Example: Initialize and Get Platform Source: https://docs.starti.app/explanation/typescript-support A React functional component that initializes the starti.app SDK and retrieves the platform information. It handles potential errors if not running within the starti.app container. ```typescript import { useEffect, useState } from "react"; function DeviceInfo() { const [platform, setPlatform] = useStatePlatform: {platform || "web"}
; } ``` -------------------------------- ### Complete Example Source: https://docs.starti.app/how-to/share-content Demonstrates initializing the SDK and using share/download functionality with event listeners. ```APIDOC ## Complete Example ### Description This example shows how to initialize the starti.app SDK and attach event listeners to buttons to trigger sharing text or downloading files. ### Method `initialize`, `shareText`, `downloadFile` ### Endpoint N/A (Client-side SDK usage) ### Parameters None ### Request Example ```javascript await startiapp.initialize(); // Share button event listener document.getElementById("share-btn").addEventListener("click", async () => { await startiapp.Share.shareText("Join me on this app!"); }); // Download button event listener document.getElementById("download-btn").addEventListener("click", async () => { await startiapp.Share.downloadFile( "https://api.example.com/export/data.csv", "export.csv", ); }); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Authentication Example Source: https://docs.starti.app/rest-api Example of how to authenticate requests to the starti.app API using an API key. ```APIDOC ## Authentication Example ### Description All requests to the starti.app API must include an API key in the `x-api-key` header and set `Content-Type` to `application/json`. ### Method POST ### Endpoint `https://api.starti.app/v1/...` ### Request Example ```bash curl -X POST \ -H "Content-Type: application/json" \ -H "x-api-key: YOUR_API_KEY" \ https://api.starti.app/v1/... ``` ``` -------------------------------- ### Svelte Example: Initialize and Get Platform Source: https://docs.starti.app/explanation/typescript-support A Svelte component that initializes the starti.app SDK on mount and retrieves the platform information. It displays the platform or 'web' if the SDK is not initialized. ```typescriptPlatform: {platform || "web"}
``` -------------------------------- ### Install starti.app SDK Types (npm) Source: https://docs.starti.app/explanation/typescript-support Installs the starti.app npm package as a development dependency to provide TypeScript type definitions for the SDK. The actual SDK is loaded from a CDN at runtime. ```bash npm install --save-dev starti.app ``` -------------------------------- ### Complete Google Sign-In Implementation Source: https://docs.starti.app/how-to/sign-in-with-google A full example demonstrating initialization, triggering the sign-in flow, and sending the authorization data to a backend server for token exchange. ```javascript await startiapp.initialize(); async function loginWithGoogle() { const result = await startiapp.Auth.signIn("google"); if (!result.isSuccess) { alert("Login failed: " + result.errorMessage); return; } const response = await fetch("/api/auth/google", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ authorizationCode: result.authorizationCode, codeVerifier: result.codeVerifier, redirectUri: result.redirectUri, }), }); const session = await response.json(); console.log("Logged in as:", session.email); } ``` -------------------------------- ### Complete In-App Purchase Workflow Source: https://docs.starti.app/how-to/setup-in-app-purchases A full implementation example showing initialization, displaying product pricing, and handling the purchase click event with backend validation. ```javascript await startiapp.initialize(); const productId = "com.example.premium"; const product = await startiapp.InAppPurchase.getProduct(productId, "nonconsumable"); if (product.success) { document.getElementById("price").textContent = product.value.localizedPrice; } document.getElementById("buy-btn").addEventListener("click", async () => { const result = await startiapp.InAppPurchase.purchaseProduct(productId, "nonconsumable"); if (result.success) { await fetch("/api/validate-purchase", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ transactionId: result.value.transactionIdentifier, productId, }), }); } }); ``` -------------------------------- ### Full NFC Scan Flow with Capability Checks Source: https://docs.starti.app/reference/nfc-scanner A comprehensive example demonstrating the complete NFC scanning workflow. It includes checks for hardware support and enablement, sets up an event listener for tag scans, and starts the scanner. This pattern ensures NFC is ready before attempting to read tags. ```javascript async function startNfcScan() { // Check hardware support const supported = await startiapp.NfcScanner.isNfcSupported(); if (!supported) { alert("NFC is not supported on this device"); return; } // Check if NFC is turned on const enabled = await startiapp.NfcScanner.isNfcEnabled(); if (!enabled) { alert("Please enable NFC in your device settings"); return; } // Listen for tags startiapp.NfcScanner.addEventListener("nfcTagScanned", (event) => { const records = event.detail; for (const record of records) { console.log(`Scanned: ${record.message} (${record.mimeType})`); } }); // Start scanning await startiapp.NfcScanner.startNfcScanner(); console.log("NFC scanner is active, hold a tag near the device"); } ``` -------------------------------- ### POST startListeningForUdpPackets Source: https://docs.starti.app/reference/network Starts listening for incoming UDP packets on a specified port. ```APIDOC ## POST startListeningForUdpPackets ### Description Starts listening for incoming UDP packets on the specified port. Received packets fire the `udpPacketReceived` event. ### Method POST ### Endpoint startiapp.Network.startListeningForUdpPackets(port) ### Parameters #### Request Body - **port** (number) - Required - The UDP port to listen on. ### Request Example { "port": 9000 } ``` -------------------------------- ### Full MitID Authentication Workflow Source: https://docs.starti.app/how-to/sign-in-with-mitid A complete example showing initialization, sign-in, backend token exchange, and accessing additional claims. ```javascript await startiapp.initialize(); async function loginWithMitID() { const result = await startiapp.Auth.signIn("signaturgruppenmitid", { scope: "openid mitid ssn", }); if (!result.isSuccess) { alert("Login failed: " + result.errorMessage); return; } const response = await fetch("/api/auth/mitid", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ authorizationCode: result.authorizationCode, codeVerifier: result.codeVerifier, redirectUri: result.redirectUri, }), }); const session = await response.json(); console.log("Logged in:", session.name); console.log("CPR:", result.additionalClaims["dk.cpr"]); } ``` -------------------------------- ### Complete Apple Sign-In and Backend Sync Source: https://docs.starti.app/how-to/sign-in-with-apple A full implementation example showing initialization, authentication, and sending the identity payload to a backend API for verification. ```javascript await startiapp.initialize(); async function loginWithApple() { const result = await startiapp.Auth.signIn("apple"); if (!result.isSuccess) { alert("Login failed: " + result.errorMessage); return; } await fetch("/api/auth/apple", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userId: result.identity.userId, email: result.identity.email, name: result.identity.name, idToken: result.identity.idToken, authorizationCode: result.authorizationCode, }), }); } ``` -------------------------------- ### API Authentication Example (cURL) Source: https://docs.starti.app/rest-api Demonstrates how to authenticate API requests using an API key in the request headers. Requires an API key obtained from the starti.app manager and sets the Content-Type to application/json. ```shell curl -X POST \ -H "Content-Type: application/json" \ -H "x-api-key: YOUR_API_KEY" \ https://api.starti.app/v1/... ``` -------------------------------- ### JavaScript Example for Image Capture Source: https://docs.starti.app/reference/camera Provides a JavaScript function to programmatically create and trigger a file input element for capturing an image. It returns a Promise that resolves with the captured file. This example also shows how to display the captured image using a URL. ```javascript function captureImage() { return new Promise((resolve) => { const input = document.createElement("input"); input.type = "file"; input.accept = "image/*"; input.capture = "environment"; input.addEventListener("change", () => { const file = input.files?.[0]; if (file) { resolve(file); } }); input.click(); }); } // Usage const imageFile = await captureImage(); console.log("Captured:", imageFile.name, imageFile.size); // Display the captured image const url = URL.createObjectURL(imageFile); document.getElementById("preview").src = url; ``` -------------------------------- ### Initialize and Use starti.app SDK in TypeScript Source: https://docs.starti.app/explanation/typescript-support Demonstrates how to use the global `startiapp` object in TypeScript after installing the SDK package. It shows event handling, initialization, and accessing module properties and methods with type safety. ```typescript // No import needed — the types are globally available after installing the package. // The global `startiapp` object is typed as `StartiappClass`. startiapp.addEventListener("ready", async () => { startiapp.initialize(); const platform = startiapp.App.platform; // type: string const deviceId = await startiapp.App.deviceId(); // type: string const volume = await startiapp.Media.getVolume(); // type: number }); ``` -------------------------------- ### GET /InAppPurchase/getProduct Source: https://docs.starti.app/how-to/setup-in-app-purchases Fetches localized product details such as name, price, and description for a specific product ID. ```APIDOC ## GET /InAppPurchase/getProduct ### Description Retrieves product information from the store provider to display to the user before purchase. ### Method GET (SDK Method) ### Parameters #### Path Parameters - **productId** (string) - Required - The unique identifier for the product defined in App Store Connect or Google Play Console. - **type** (string) - Required - The product type: "consumable" or "nonconsumable". ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **value** (object) - Contains product details including name, localizedPrice, currencyCode, and description. #### Response Example { "success": true, "value": { "name": "Premium Upgrade", "localizedPrice": "$4.99", "currencyCode": "USD", "description": "Unlock all premium features." } } ``` -------------------------------- ### Implement Biometric-Secured OAuth Login Flow Source: https://docs.starti.app/how-to/biometric-oauth-login This example demonstrates how to initialize the StartiApp SDK, check for biometric availability, and implement a login flow that attempts biometric session retrieval before falling back to OAuth authentication. It also includes logic for storing session tokens securely and handling user logout. ```javascript await startiapp.initialize(); const biometricType = await startiapp.Biometrics.getAuthenticationType(); const hasBiometrics = biometricType !== "none"; async function login() { if (hasBiometrics) { const hasSession = await startiapp.Biometrics.hasSecuredContent(); if (hasSession) { const token = await startiapp.Biometrics.getSecuredContent("Log in", "Verify your identity"); if (token) { const response = await fetch("/api/auth/session", { headers: { Authorization: `Bearer ${token}` } }); if (response.ok) { const user = await response.json(); console.log("Welcome back,", user.name); return; } await startiapp.Biometrics.removeSecuredContent(); } } } const result = await startiapp.Auth.signIn("signaturgruppenmitid"); if (!result.isSuccess) { alert("Login failed: " + result.errorMessage); return; } const response = await fetch("/api/auth/mitid", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ authorizationCode: result.authorizationCode, codeVerifier: result.codeVerifier, redirectUri: result.redirectUri }) }); const session = await response.json(); console.log("Logged in:", session.name); if (hasBiometrics) { await startiapp.Biometrics.setSecuredContent(session.token); } } async function logout() { await startiapp.Biometrics.removeSecuredContent(); await startiapp.Auth.signOut(); console.log("Logged out"); } ``` -------------------------------- ### Manage AppStorage Settings with JavaScript Source: https://docs.starti.app/getting-started/storage-and-data This JavaScript code demonstrates how to manage application settings using startiapp.Storage.app. It includes functions to initialize storage, load settings (with defaults and error handling for corrupt data), save settings, and clear all stored data. The example also shows how to handle running in a browser environment where AppStorage falls back to localStorage. ```javascript const SETTINGS_KEY = "app-settings"; const defaultSettings = { theme: "light", fontSize: 14, notifications: true, }; async function main() { if (!startiapp.isRunningInApp()) { console.log("Running in browser -- AppStorage will use localStorage fallback."); } try { await startiapp.initialize(); } catch (e) { // Continue anyway -- AppStorage falls back to localStorage } // Load saved settings or use defaults const settings = await loadSettings(); console.log("Current settings:", settings); // Update a setting settings.theme = "dark"; await saveSettings(settings); console.log("Settings saved."); // Verify the save const reloaded = await loadSettings(); console.log("Reloaded settings:", reloaded); } async function loadSettings() { const raw = await startiapp.Storage.app.getItem(SETTINGS_KEY); if (raw) { try { const parsed = JSON.parse(raw); return Object.assign({}, defaultSettings, parsed); } catch (e) { console.warn("Corrupt settings data -- using defaults."); } } return Object.assign({}, defaultSettings); } async function saveSettings(settings) { await startiapp.Storage.app.setItem(SETTINGS_KEY, JSON.stringify(settings)); } // Wire up a "Reset all data" button const resetBtn = document.getElementById("reset-btn"); if (resetBtn) { resetBtn.addEventListener("click", async function () { if (confirm("This will clear all app data. Continue?")) { await startiapp.Storage.app.clear(); console.log("All AppStorage data cleared."); window.location.reload(); } }); } main(); ``` -------------------------------- ### Share a File using starti.app SDK Source: https://docs.starti.app/how-to/share-content Share a file by providing its URL and a filename. This action triggers the native share sheet on the user's device, allowing them to choose how to share the content. Ensure the starti.app SDK is installed and initialized before use. ```javascript await startiapp.Share.shareFile("https://example.com/report.pdf", "report.pdf"); ``` -------------------------------- ### AppStorage CRUD Operations Source: https://docs.starti.app/reference/storage Demonstrates basic CRUD operations including getting, setting, removing items, and clearing storage using the AppStorage interface. ```javascript const value = await startiapp.Storage.app.getItem("my-key"); if (value !== null) { console.log("Found:", value); } await startiapp.Storage.app.setItem("user-name", "John"); await startiapp.Storage.app.setItem("settings", JSON.stringify({ theme: "dark" })); await startiapp.Storage.app.removeItem("user-name"); await startiapp.Storage.app.clear(); ``` -------------------------------- ### Download a File using starti.app SDK Source: https://docs.starti.app/how-to/share-content Download a file directly to the device's download folder without displaying the share sheet. This is useful for saving reports, invoices, or other documents. Requires the starti.app SDK to be installed and initialized. ```javascript await startiapp.Share.downloadFile("https://example.com/invoice.pdf", "invoice-2024.pdf"); ``` -------------------------------- ### Read Device Information (JavaScript) Source: https://docs.starti.app/getting-started/setup-and-the-basics Provides examples for reading device information using the Starti App SDK. The `platform` property is synchronous, returning 'ios', 'android', or 'web'. Device ID, brand ID, and app version are asynchronous and require `await` for retrieval, with `deviceId()` and `brandId()` caching results after the first call. ```javascript const platform = startiapp.App.platform; console.log("Platform:", platform); // "ios" or "android" or "web" const deviceId = await startiapp.App.deviceId(); console.log("Device ID:", deviceId); const brandId = await startiapp.App.brandId(); console.log("Brand ID:", brandId); const version = await startiapp.App.version(); console.log("App version:", version); ``` -------------------------------- ### Sign In with MitID - Starti App Auth Source: https://docs.starti.app/reference/auth Initiates the sign-in flow using MitID, a Danish digital identity provider. This example demonstrates requesting specific scopes, such as 'openid', 'mitid', and 'ssn', to obtain additional claims like the Social Security Number (SSN). Dependencies include the `startiapp.Auth` module. ```javascript // Sign in with MitID and request SSN const result = await startiapp.Auth.signIn("signaturgruppenmitid", { scope: "openid mitid ssn ssn.details_name", }); if (result.isSuccess) { console.log("Claims:", result.additionalClaims); } ``` -------------------------------- ### Get Available App Icons - JavaScript Source: https://docs.starti.app/reference/app Fetches a list of all alternate app icons that are available for the application. This list is determined at build time and reflects the icons bundled with the app. ```javascript const icons = await startiapp.App.getAvailableIcons(); console.log(icons); // ["default", "dark-icon", "holiday-icon"] ``` -------------------------------- ### Get Product Information - JavaScript Source: https://docs.starti.app/reference/in-app-purchase Retrieves metadata for a product, such as its name, description, and localized price, without initiating a purchase. This is useful for displaying product details to the user before they decide to buy. It returns a promise with product information or an error. ```javascript const result = await startiapp.InAppPurchase.getProduct( "com.example.premium", "nonconsumable" ); if (result.success) { console.log(`${result.value.name} - ${result.value.localizedPrice}`); } else { console.error("Failed to load product:", result.errorMessage); } ``` -------------------------------- ### Biometric and OAuth Login Flow Source: https://docs.starti.app/how-to/biometric-oauth-login This example demonstrates a complete login process that prioritizes biometric authentication for returning users and falls back to a full OAuth flow for new users or when biometrics are unavailable. It also includes handling session expiration and secure storage of tokens. ```APIDOC ## Biometric and OAuth Login Flow ### Description This code snippet illustrates a comprehensive authentication strategy. It first attempts to use biometric authentication to retrieve a stored session token. If successful, it validates the token with the server. If biometrics are not available, or the stored token is invalid/expired, it initiates a full OAuth sign-in process. Upon successful OAuth login, it stores the new session token for future biometric access. ### Method N/A (Client-side JavaScript) ### Endpoint N/A (Client-side JavaScript) ### Parameters N/A ### Request Example ```javascript await startiapp.initialize(); const biometricType = await startiapp.Biometrics.getAuthenticationType(); const hasBiometrics = biometricType !== "none"; async function login() { // Try biometric resume first if (hasBiometrics) { const hasSession = await startiapp.Biometrics.hasSecuredContent(); if (hasSession) { const token = await startiapp.Biometrics.getSecuredContent( "Log in", "Verify your identity" ); if (token) { const response = await fetch("/api/auth/session", { headers: { Authorization: `Bearer ${token}` }, }); if (response.ok) { const user = await response.json(); console.log("Welcome back,", user.name); return; } // Token expired — clear and continue to full login await startiapp.Biometrics.removeSecuredContent(); } } } // Full OAuth login const result = await startiapp.Auth.signIn("signaturgruppenmitid"); if (!result.isSuccess) { alert("Login failed: " + result.errorMessage); return; } const response = await fetch("/api/auth/mitid", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ authorizationCode: result.authorizationCode, codeVerifier: result.codeVerifier, redirectUri: result.redirectUri, }), }); const session = await response.json(); console.log("Logged in:", session.name); // Store for biometric resume next time if (hasBiometrics) { await startiapp.Biometrics.setSecuredContent(session.token); } } ``` ### Response #### Success Response (200) User session data upon successful login. #### Response Example ```json { "name": "John Doe", "token": "Open this page inside the starti.app native container to see device info.