Sign-in and purchases
Biometrics, OAuth and Sign in with Apple, in-app purchases and store reviews.
Biometrics
Section titled “Biometrics”cx.BiometricAvailability reports whether Face ID, Touch ID, a device fingerprint or Windows Hello (core.BiometricWindowsHello) is enrolled without showing a prompt. Android does not say which kind is enrolled, so there it reports a fingerprint when one is enrolled and otherwise face when the device has face hardware; Windows does not distinguish which factor is configured and reports core.BiometricWindowsHello when Windows Hello is ready. cx.AuthenticateBiometric asks the system to confirm the user with a reason, which must not be empty, and reports success, failure, cancellation or unavailability. On macOS, iOS, Android and HarmonyOS it never falls back to a device passcode; on Windows it shows a Windows Hello prompt parented to the requesting window and accepts whichever Windows Hello method the user configured (face, fingerprint, or Windows Hello PIN).
cx.BiometricAvailability(func(kind core.BiometricKind) { if kind != core.BiometricNone { cx.AuthenticateBiometric("Confirm deleting this account", func(result core.BiometricResult) { if result == core.BiometricSuccess { deleteAccount() } }) }})Face ID apps declare NSFaceIDUsageDescription under apple.info; Android apps list USE_BIOMETRIC under android.permissions.
Signing in
Section titled “Signing in”cx.AuthSession signs the user in with an OAuth provider in the system’s authentication session rather than a web view: ASWebAuthenticationSession on macOS, iOS and watchOS, a Custom Tab or browser on Android, the default browser on Windows, Linux and a Mac without a scheme, and a popup on the web. On the web, the redirect page also sends its callback over a same-origin BroadcastChannel, so a sign-in completes when the provider’s Cross-Origin-Opener-Policy cuts the popup off from the page. Such a popup reads as closed to the page, so closing a popup after it showed the provider’s page ends the session cancelled only after 5 minutes; give the session a cancel button. The app keeps the protocol: it makes the PKCE verifier and the state, builds the authorization URL for the redirect it is given, and checks the callback before trading its code. Cancelling is not failing: errors.Is(err, core.AuthCancelled) tells the user closing the session, or the returned cancel ending it.
verifier, challenge, state := newPKCE() // the app's owncx.AuthSession(func(redirect string) string { q := url.Values{"client_id": {clientID(redirect)}, "redirect_uri": {redirect}, "response_type": {"code"}, "scope": {"openid email"}, "state": {state}, "code_challenge": {challenge}, "code_challenge_method": {"S256"}} return "https://accounts.example.com/authorize?" + q.Encode()}, core.AuthSessionOptions{Scheme: "com.example.app", Path: "/oauth2redirect", Timeout: 5 * time.Minute}, func(callback string, err error) { if errors.Is(err, core.AuthCancelled) { return } if err != nil { showError(err) return } u, _ := url.Parse(callback) if u.Query().Get("state") == state { exchangeCode(u.Query().Get("code"), verifier) }})The redirect is com.example.app:/oauth2redirect where a scheme is set (Windows, Linux and Android need it in nsgo.yaml‘s url_schemes so the OS hands the callback to the running app; macOS’s, iOS’s and watchOS’s system session catches it without that declaration), and http://127.0.0.1:<port>/oauth2redirect on the desktops’ loopback, so register both with the provider, often as clients of their own. Leave Scheme empty for loopback alone, or set it to https with Host for the app’s associated domain, which iOS 17.4, macOS 14.4 and watchOS 10.4 catch. watchOS requires a scheme or associated HTTPS domain; it has no loopback fallback, and NSGo’s existing watchOS 26 minimum still applies. A closed browser tab tells a loopback session nothing, so give it a Timeout or a cancel button. Ephemeral asks macOS, iOS and watchOS not to share the browser’s cookies, and requests a private Custom Tab on Android where the browser supports one; do not assume cookie isolation on Android. tvOS and mini programs answer core.AuthUnavailable for now.
Android consumes a matching callback before ordinary OnOpenLinks, and returning without a callback ends the session cancelled. Its callback must use an app-owned private scheme; an empty scheme, HTTPS callback or undeclared scheme returns core.AuthUnavailable, as does an Android runtime built before sign-in sessions.
A browser session consumes only its matching callback link; unrelated and late links still reach OnOpenLinks. Starting another browser session for the same callback URI cancels the earlier one; distinct URIs can wait in different windows.
Use the exact redirect passed to the authorization URL function. Web and desktop loopback redirects encode Unicode paths and resolve dot segments before the function receives them; a loopback Path is decoded text, so a literal % is escaped too.
Mini programs use cx.SignInMiniProgram(core.MiniProgramSignInOptions{}, done) instead. The callback receives a core.MiniProgramCredential with its Platform (MiniProgramWeChat, MiniProgramQQ, MiniProgramDouyin or MiniProgramAlipay) and a nonempty, short-lived Code. Send it to your server for the host’s code exchange; keep the app secret there. This is wx.login/qq.login/tt.login, or Alipay’s basic auth_base authorization, without requesting profile information. It does not open a URL or run an OAuth URL builder.
cx.Env().CanSignInMiniProgram() reports the host API’s availability. Other targets answer core.MiniProgramSignInUnavailable; code without core.AccessMiniProgramSignIn gets AccessDenied. Douyin asks silently by default: an unsigned host returns MiniProgramSignInNotSignedIn, and MiniProgramSignInOptions{Prompt: true} permits its host-account login window. Closing that window returns MiniProgramSignInCancelled. An anonymous device code never counts as a signed-in user. Tests set nsgotest.Environment(core.Environment{MiniProgramSignIn: true}) and app.MiniProgramSignIn; app.MiniProgramSignIns records requests.
An app whose web views should be signed in as the user already is elsewhere, such as in their own browser, writes the cookies of that sign-in with cx.SetWebCookies, HttpOnly ones included, which page scripts cannot set, then loads the pages: done runs once the store holds them. The store is the persistent one every web view of the app shares, so cookies with an Expires outlive the app; Incognito views do not see them, except on Android, which keeps one store per app. On Linux, libsoup refuses cookies whose domain is on the Public Suffix List (including its private section), failing the call before any cookie is written. The web, tvOS and watchOS answer Unavailable.
cx.SetWebCookies([]core.WebCookie{ {Name: "SID", Value: sid, Domain: ".example.com", Expires: expires, Secure: true, HTTPOnly: true},}, func(err error) { if err == nil { page.Set(core.WebSrc("https://www.example.com/")) }})To remove one cookie, write it again with the same name, domain and path and Expires in the past; a zero expiry makes a session cookie. Wait for the callback before loading a page that should observe the removal.
The other way round, cx.WebCookies lists the store’s cookies, HttpOnly ones and their domain, path, expiry and flags included, which document.cookie cannot read, whether or not a page of the site is showing: a core.WebCookieFilter picks those a request to a URL would send, or those of a Domain and every host under it, and the zero filter all of them. An app calling the site from Go with the user’s sign-in, or showing where the user is signed in, reads them this way. cx.ClearWebsiteData signs the user out of every site: it removes the store’s cookies, local and session storage, IndexedDB, service workers and caches, and done runs once they are gone. Android’s CookieManager (and HarmonyOS prior to API 23) answers only the names and values a URL would send, so there only a URL filter lists, filling Domain with its host and leaving the other fields empty, and a Domain filter or the zero one answers Unavailable; clearing on Android leaves the HTTP cache. The web, tvOS and watchOS answer Unavailable to both.
cx.WebCookies(core.WebCookieFilter{Domain: "example.com"}, func(cookies []core.WebCookie, err error) { signedIn.Set(err == nil && slices.ContainsFunc(cookies, func(c core.WebCookie) bool { return c.Name == "SID" }))})Sign in with Apple
Section titled “Sign in with Apple”cx.SignInWithApple shows the system’s Sign in with Apple sheet from the app’s own button on macOS, iOS and tvOS, where cx.Env().CanSignInWithApple() is true. It answers once with the credential, or with an error: core.AppleSignInCancelled when the user closes the sheet, which is not a failure, else AppleSignInFailed or, on other platforms, AppleSignInUnavailable. Apple gives the email and the name only on the user’s first sign-in to the app, so keep them then. Nonce goes into the request as its SHA-256 in lowercase hex, which the identity token’s nonce claim holds: the server hashes the nonce it gave the app and compares. cx.AppleCredentialState tells whether the user has since revoked it. In headless tests, app.AppleSignIn receives a nsgotest.AppleSignInRequest and supplies the credential or error.
nonce := rand.Text() // also sent to the server, which checks the token's claim against its SHA-256cx.SignInWithApple(core.AppleSignInOptions{FullName: true, Email: true, Nonce: nonce}, func(c core.AppleCredential, err error) { switch { case errors.Is(err, core.AppleSignInCancelled): case err != nil: showError(err) default: signInOnServer(c.IdentityToken, c.AuthorizationCode, nonce, c.GivenName, c.FamilyName, c.Email) }})cx.AppleCredentialState(savedUser, func(s core.AppleCredentialState, err error) { if err == nil && s == core.AppleCredentialRevoked { signOut() }})The app must be signed with the Sign in with Apple entitlement, which build adds when nsgo.yaml asks for it; without it the sheet fails:
apple: sign_in_with_apple: true # com.apple.developer.applesignin, in iOS and tvOS packages and Mac App Store buildsXcode registers the capability for device builds from nsgo dev; a provisioning profile in sign.profile or sign.macos_profile must come from an App ID with Sign in with Apple turned on. macOS grants it only with a profile, so a disk image or a nsgo dev run on a Mac cannot sign in, nor can the simulator, whose builds claim no developer entitlement.
In-app purchases
Section titled “In-app purchases”cx.Products, cx.Purchase and the calls beside them sell through the App Store on macOS, iOS and tvOS, where cx.Env().CanPurchase() is true, in a build whose nsgo.yaml asks for StoreKit:
apple: purchases: true # StoreKit's library, in macOS, iOS and tvOS packages; no entitlement is neededShow the prices the store gives, DisplayPrice, never prices of the app’s own: the store prices each storefront itself. A purchase answers once, with the transaction or an error: core.PurchaseCancelled when the user closes the sheet, core.PurchasePending while it waits for approval, as Ask to Buy does, and otherwise core.PurchaseFailed, with the store’s words, or PurchasesUnavailable elsewhere. Send the transaction’s Signed, the store’s JWS, to the app’s server to verify, deliver what it bought, then finish it; the store hands an unfinished transaction to the app again at every launch.
cx.ManageSubscriptions opens Apple’s subscription management UI (the system sheet on iOS, the App Store subscriptions page on macOS and tvOS). cx.RequestRefund starts a refund request for a transaction on iOS and macOS and answers core.RefundSuccess or core.RefundCancelled (tvOS answers core.PurchaseFailed).
cx.OnPurchaseUpdate(func(t core.Transaction) { // renewals, approved purchases, other devices', refunds, and unfinished ones at launch verifyAndDeliver(t.Signed, func() { cx.FinishTransaction(t.ID, nil) })})cx.Products([]string{"com.example.pro.monthly"}, func(products []core.Product, err error) { if err == nil && len(products) > 0 { price.Set(products[0].DisplayPrice) }})cx.Purchase("com.example.pro.monthly", core.PurchaseOptions{AccountToken: userUUID}, func(t core.Transaction, err error) { switch { case errors.Is(err, core.PurchaseCancelled): case errors.Is(err, core.PurchasePending): showWaiting() // its transaction comes through OnPurchaseUpdate case err != nil: showError(err) default: verifyAndDeliver(t.Signed, func() { cx.FinishTransaction(t.ID, nil) }) }})FinishTransaction returns PurchaseNotFound for an already finished transaction, including one returned by CurrentEntitlements; a finished non-consumable remains owned.
Register OnPurchaseUpdate as the app starts: updates that come before any handler wait for the first. cx.CurrentEntitlements answers what the user owns now, to unlock it at launch, and a Restore Purchases button calls cx.SyncPurchases, which may ask the user to sign in. AccountToken is a UUID of the app’s own that the transaction and the App Store’s server notifications carry. macOS sells only in a Mac App Store build, and an App Clip sells nothing; Android, watchOS, Windows, Linux, the web and mini programs answer PurchasesUnavailable for now. Test purchases with nsgotest, whose Products, PurchaseAnswer, ManageSubscriptionsError, RefundStatus, RefundError, UpdatePurchase and UnfinishedTransactions stand in for the store. app.PurchaseRequests records store operations as nsgotest.PurchaseRequest values.
Store reviews
Section titled “Store reviews”cx.RequestReview() asks for an in-app rating prompt from the App Store on macOS and iOS, or Google Play on Android. cx.Env().CanRequestReview() reports whether the service is available. The store decides whether and when to show the prompt and reports no result. Use a development build to test the Apple prompt. TestFlight builds suppress it.
Standalone Android packages include the Play Review SDK, its dialog activity and Play Store visibility query; building them needs no Android SDK or JDK. A device with no enabled Play Store reports the service as unavailable. Test a released package using Internal App Sharing.
When embedding NSGo, add com.google.android.play:review:2.0.2 to the Gradle host. In the host’s manifest, add <package android:name="com.android.vending" /> under <queries> so the app can see the Play Store. If the host shrinks its code, preserve the Play Review and Tasks APIs with the rules below, as NSGo loads them by name.
-keep class com.google.android.play.core.review.ReviewManagerFactory { *; }-keep interface com.google.android.play.core.review.ReviewManager { *; }-keep class com.google.android.play.core.review.ReviewInfo { *; }-keep class com.google.android.gms.tasks.Task { *; }-keep interface com.google.android.gms.tasks.OnCompleteListener { *; }In tests, set CanRequestReview in nsgotest.Environment and check nsgotest.App.ReviewRequests.