In-app purchases
Sell subscriptions and one-time products on the App Store and Google Play. Blaink checks every purchase with the store, keeps it under the right customer, and answers what that customer may use now — to your iOS, macOS, Android and React Native apps, to your server, and to your team in the console.
How a purchase moves
Every purchase travels the same line, on the App Store and on Google Play. Whatever happens along it, your app and your server ask one question — what may this customer use now? — and get the same answer.
- 01
Bought
Your customer taps Buy. Apple’s or Google’s own sheet takes the payment, with the Blaink customer attached to the purchase.
The store
- 02
Reported
The SDK sends the store’s signed proof of purchase to Blaink, and holds the transaction open until Blaink answers.
The SDK, in your app
- 03
Verified
Blaink checks the proof with Apple or Google, then records the purchase under the customer — never twice, however often it is reported.
Blaink
- 04
Entitled
The product’s entitlements turn on. The SDK answers your app with them, and only then finishes or acknowledges the transaction.
Your app
- 05
Kept current
Renewals, billing problems, refunds and expirations arrive from the stores’ own notifications, change the entitlements, and go to your webhooks.
Blaink, for your server
After it lands, the store keeps moving it. Each of these reaches Blaink from the store's own notifications, without your app being opened. Blaink also asks the store about subscriptions that are due to renew, every few hours, so a renewal whose notification went missing still lands — once the store is connected (Connect the stores):
renewalbilling_issuebilling_recoveryexpirationrefundproduct_changed
The full list is under From your server.
Concepts
The words the console, the SDKs and this guide use, each with the rule that most often catches a team out.
What you sell
- Product
One thing a store sells, listed once per store under the ID App Store Connect or the Play Console gives it:
pro_monthlyon the App Store andpro_monthlyon Google Play are two products. Its kind is an auto-renewable subscription, a non-renewing subscription (for a number of access days, or for life), a non-consumable, or a consumable, which unlocks nothing and only counts as revenue. A project has one catalogue for all its apps, so what a customer bought in one app unlocks the same entitlements in every app of the project they are logged in to.Stop selling takes a product out of what apps are offered and keeps every buyer’s access, renewals and restores included. Remove deletes it from the catalogue: its purchases stay recorded as revenue but unlock nothing until it is listed again. To retire a product, stop selling it.
- Entitlement
What a purchase unlocks, by a name you choose —
pro,no_ads— listed on each product that grants it. Your app checks entitlements, never product IDs, so you can change what you sell without an app release. Every kind of product but a consumable needs at least one.An entitlement is active while a subscription’s period, or its grace period, runs; for life for a non-consumable; and for its access days for a non-renewing subscription. A refund, a withdrawn Family Sharing copy or an upgrade to another product ends it. A payment the store is still retrying with no grace period is not access: the entitlement reads inactive, with
hasBillingIssueset.- Offering and package
An offering is the set of choices your app shows together — monthly beside annual — as up to 20 ordered packages, with optional metadata of up to 4 KB of JSON for your own screen. The metadata reaches every app, so put nothing secret in it. A package holds at most one product per store, so one package sells the same plan on both stores; an app is sent only the packages with a product on its own store. On Google Play a package can also name a base plan, so two packages can sell the monthly and annual plans of one Play subscription.
There is no current offering until an operator chooses Make current on the Offerings page: adding the first offering doesn’t make it current, and until then every app reads no current offering. A change reaches apps the next time they read offerings, with no release.
- Paywall
The screen that sells one offering, designed in the console and drawn natively by the SDK. Each offering has at most one. You edit a draft; publishing freezes it as a numbered version that never changes, and apps are served only the latest published version. See Paywalls.
A version is served only for the offering it was published against. Remove an offering and add it again under the same ID, and its paywall is served nothing until you publish it again.
- Virtual currency
Coins, gems or credits. A product grants an amount of each per paid charge — a consumable’s coins, or every paid renewal of a subscription, never a free period — and a refund takes it back, a prorated refund its share rounded up, so a balance can go below zero. Your backend spends and credits it over the server API, each change with an
Idempotency-Key; an operator adjusts it on the customer’s page.The SDKs have no currency calls in these versions: your app reads balances from your backend. Sandbox purchases credit nothing until you switch on Sandbox purchases on the Virtual currencies page.
Who buys it
- Customer
Whom Blaink records a purchase under. Until your app calls
logIn, it is the device’s own anonymous customer; after it, the account named by your own ID for the person, made the first time that ID logs in. A first login from an anonymous device brings everything the device held — purchases, grants, attributes, balances — to the account, and where both hold something the account keeps its own. Logging out leaves everything with the account. See Customers and accounts.A purchase leaves an account only when another account buys or restores it, and then only as the project’s Shared purchases setting says. Opening the app never moves one. The console’s Customers page lists only customers who own a purchase, hold a grant or are blocked.
- Grant
Access given by hand: an entitlement for life or until a date, with a reason, given with Give access on a customer’s page or by your backend. One per customer per entitlement; a new grant replaces the old. It is weighed with what the stores sold, so it never shortens paid access, and revoking it never touches a store purchase. Apps read it with the store
promotional.A grant follows a first login to the account, unless the account already holds that entitlement as a grant. It stays behind when an operator moves a customer’s purchases to someone else.
- Audience and custom attributes
An audience is a saved rule, not a list: what customers bought (status, entitlement, product, store, trial, country), what their devices did (platform, language, last seen, an analytics event), and custom attributes your app or backend set. Who is in it is worked out each time it is read. A custom attribute is a key of up to 40 characters, starting with a letter, and a text value of up to 500; a customer holds at most 50.
Today only experiments use these audiences. Push campaigns choose their recipients with the push composer’s own audiences, which don’t read these rules.
- Experiment
A test of offerings against each other: 2 to 4 variants, each showing a different offering, with shares that add up to 100, and optionally an audience. While it runs, each new customer is put in a variant the first time their app reads offerings or the current offering’s paywall, and sees that variant’s offering as current from then on. Results are worked out every six hours.
Only customers first seen after it starts take part; everyone else keeps the project’s current offering. One experiment runs per project at a time, starting it freezes its variants, and stopping it is final.
Where it runs
- Environment
Every purchase is production or sandbox, as the store itself reports it. Purchases in a development build with a sandbox Apple Account, in TestFlight, in a build under App Review, and by Google Play licence testers are sandbox. Sandbox purchases unlock entitlements like real ones, so testers see the product work — each entitlement’s
isSandboxsays which it is — and stay out of revenue.The Overview, Charts and Transactions show production unless you switch them to sandbox; they never add the two together. The Customers page’s statuses mix both, and paywall views aren’t split. Webhooks, automations, Retention messages and the Shared purchases setting are set per environment.
- Observer mode
For an app where another purchases SDK finishes transactions: Blaink records every purchase and finishes or acknowledges none. Start it with
start(completion: .observer)on iOS,start(context, BlainkPurchases.Completion.OBSERVER)on Android, orstart({ observer: true })in React Native.In observer mode nothing is acknowledged on Google Play, not even what Blaink’s own
purchasesold, and Google refunds a purchase nobody acknowledges within three days. So sell through the other SDK until you switch over, then start Blaink the usual way (Test and go live).
Connect the stores
Before the first sale: tell Blaink your apps, what you sell, and how to ask each store about a purchase. An app manager or owner does this once per app, on the console’s Purchases page and in each store’s own console.
Register your apps
Add each app on the console’s Platforms page: the iOS app with its bundle ID, the Android app with its package name. Each store panel on the Purchases page lists the project’s apps of its kind, and says “This project has no iOS platform yet” until there is one. A device buys from its platform’s store; a web app has none.
List what you sell
On the Purchases page, under Products, choose Add product once per product per store: the store; the Product ID exactly as App Store Connect or the Play Console names it, which can’t change once listed; the kind; the entitlements it unlocks, separated by commas; for a non-renewing subscription its access days (left empty, it is sold for life); and for a Google Play subscription an optional default base plan. If the project has virtual currencies, the product dialog also takes how much of each a purchase grants.
Then, on the Offerings page, choose Add offering: an ID, which can’t change once added; the name apps are sent; and its packages in order, each an ID with a product per store and, on Google Play, a base plan. Finally choose Make current: until you do, apps read no current offering.
Copy Play base plan IDs from the Play Console. Blaink checks only their format, and a mistyped one shows as a package with no price that can’t be bought (productNotFound). Already have your products in App Store Connect? Import them on the App Store products page once step 5 is done.
App Store: add the In-App Purchase key
In App Store Connect, under Users and Access → Integrations → In-App Purchase, generate a key and download its .p8 file; Apple lets you download it once. On the Purchases page, under App Store keys, choose Add key on the app’s row and give the Issuer ID, the Key ID (filled in from the file’s name), the .p8 file, and the app’s numeric Apple ID. The Apple ID is optional, but Retention messages need it.
With the key, Blaink asks Apple for a subscription’s state as soon as an app reports it, and asks again every six hours about each subscription due to renew. Without it, purchases still verify — Blaink checks Apple’s signature and your bundle ID — but renewals, refunds and billing problems reach Blaink only through Apple’s notifications.
App Store: point the notifications at Blaink
Copy the row’s App Store Server Notifications URL, which ends in /api/v1/purchases/app-store/<platform ID>/notifications. In the app’s App Store Server Notifications settings in App Store Connect, enter it as both the Production Server URL and the Sandbox Server URL, with Version 2 notifications. One URL serves both environments: Blaink reads which one a notification is from Apple’s signed payload, and the row shows the last notification received in each.
With the key saved, choose Ask Apple to test the production URL, then the sandbox one, and refresh the page. If the time beside each environment doesn’t move, the URL in App Store Connect is wrong.
Apple takes one URL per environment. If another service needs Apple’s notifications too, point them at Blaink and forward them from the Webhooks page: see the migration section.
App Store: add an App Store Connect API key Optional
A second, different key, for two jobs. Catalogue: importing products on the App Store products page (up to 2,000 at a time; kinds come over, prices, offers and localisations don’t) and scheduling subscription prices on the App Store prices page. Reports: Apple’s daily sales reports, which replace Blaink’s estimated upgrade credits with Apple’s figures.
In App Store Connect, under Users and Access → Integrations → App Store Connect API, create a team key: one covers every app of your Apple developer account. For the catalogue it needs Admin or App Manager access; a Developer key can import, and Apple refuses its price changes. For reports it needs Admin or Finance access, or Sales with access to reports, and you also give the Vendor number shown in Payments and Financial Reports.
On the Purchases page, under App Store Connect, choose Add a key, tick what it is for, and choose Check and save: Blaink tries the key with Apple before keeping it. Change edits its uses later. Remove stops Blaink using it; revoke it in App Store Connect yourself.
Google Play: add a service account
Google Play signs nothing an app sends, so Blaink looks every purchase up with Google, as a service account of yours.
Add it before anyone can buy
With no service account, Blaink refuses every Android purchase with purchase_store_not_configured, and the Android SDK still acknowledges the purchase, or consumes it if it was bought as a consumable. The customer is charged, the app is told Refused, and Blaink records nothing. Once you add the account, each app’s next launch reports the subscriptions and non-consumables Google Play still holds for that device; a consumed consumable, or a subscription that has lapsed meanwhile, is never recorded.
Google Play: send real-time notifications to Blaink
Once the account is saved, its row shows the Real-time Developer Notifications push URL. Google delivers its notifications through Pub/Sub, which you set up in Google’s consoles:
google-play-developer-notifications@system.gserviceaccount.com the Pub/Sub Publisher role on it.Google Play has no forwarding: if another service needs its notifications too, give it a second subscription to the same topic.
If a step is skipped
| Skipped | What happens |
|---|---|
| A product in the catalogue | Its purchases are recorded as revenue and unlock nothing, and no package can sell it. |
| Make current | Every app reads no current offering, and a paywall asked for without naming an offering answers purchase_paywall_not_found. |
| The In-App Purchase key | Purchases still verify. Renewals, refunds and billing problems reach Blaink only through Apple’s notifications, and Retention messages can’t be set up. |
| The App Store notification URL | Your webhooks and the billing-issue and win-back automations hear no App Store event as it happens. With the key, Blaink re-asks Apple every six hours about each subscription due to renew, so entitlements catch up within hours; without it, only when the app next opens. |
| The App Store Connect API key | Products are added by hand, subscription prices are changed in App Store Connect, and upgrade credits stay Blaink’s estimates. |
| The Google Play service account | Every Android purchase is refused with purchase_store_not_configured and still acknowledged: charged, and not recorded (step 6). |
| The Pub/Sub push subscription | Your webhooks and the billing-issue and win-back automations hear no Google Play event. Blaink re-asks Google every six hours about each subscription due to renew, and reads refunded purchases of the last 30 days, so entitlements catch up within hours. |
Add it to your app
The same steps on every platform, in the same order: install, start, show what's for sale, sell it, then read what the customer may use. Signed in, your own platform's keys are filled into every sample.
StoreKit 2 sells; Blaink checks each transaction with Apple, records it under the customer, and answers what they may use — their entitlements, the same ones your Android app and your server read. Set up the App Store side first: Connect your stores.
Install
BlainksPurchases is a second product of the package that gives you Blainks: add both to your app target. For the ready-made paywall, add BlainksPaywalls too; it brings BlainksPurchases with it. In Xcode, choose File → Add Package Dependencies, enter https://git.blainks.com/blainks/blainks-ios.git and tick the libraries. Then add the In-App Purchase capability to the target.
// swift-tools-version: 5.10
import PackageDescription
let package = Package(
name: "MyApp",
platforms: [.iOS(.v15), .macOS(.v12)],
dependencies: [
.package(url: "https://git.blainks.com/blainks/blainks-ios.git", from: "2.4.0")
],
targets: [
.target(
name: "MyApp",
dependencies: [
.product(name: "Blainks", package: "blainks-ios"),
.product(name: "BlainksPurchases", package: "blainks-ios"),
// The ready-made paywall, drawn in SwiftUI; brings BlainksPurchases with it
.product(name: "BlainksPaywalls", package: "blainks-ios")
]
)
]
)The libraries link on iOS 13, but their API needs iOS 15 or macOS 12 (Mac Catalyst 15). With a lower deployment target, wrap each call in if #available(iOS 15.0, *), as the next step does. A Mac app uses the SDK key of an iOS platform whose bundle ID is the Mac app's.
Start it
Call start() once at launch, after Blaink's setup (on macOS, in applicationDidFinishLaunching(_:)). It reports what the customer holds now — so a purchase made before Blaink, or offline, is recorded — and listens for the transactions StoreKit hands over while the app runs: a renewal, an Ask to Buy approval, a purchase made with the same Apple Account on another device.
import Blainks
import BlainksPurchases
import UIKit
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
Blaink.shared.setup(sdkKey: "YOUR_SDK_KEY") // first, as in the core SDK guide
if #available(iOS 15.0, *) { // needed only below an iOS 15 deployment target
BlainkPurchases.shared.start()
}
return true
}
}- Only the first call counts. Later calls are ignored, a different
completion:included. - On a first launch, Blaink's sign-in may still be under way. Every purchases call waits for it up to 30 seconds, then throws
PurchasesError.unavailablewith nothing sent or bought; calling again is safe. Ifstart's own report gives up the same way, it is made again on the next launch. From the second launch the device's Blaink user is known, and nothing waits.
Another purchases library still running? Start in observer mode instead: Blaink records every transaction and finishes none. That includes what purchase buys, so keep buying through the other library until you switch. Moving from another provider: Migrate.
import BlainksPurchases
// In place of start(): Blaink records every transaction and finishes none, so your
// existing purchases code (or library) must still finish each one
BlainkPurchases.shared.start(completion: .observer)Read offerings
An offering is a set of packages your operators arrange in the console, so what your paywall sells changes without an app release. offerings() reads them from Blaink each time — nothing is cached — with what the App Store says about each package's product.
import BlainksPurchases
/// One row of your own paywall.
struct PaywallRow {
let package: Package
let price: String? // nil: the App Store didn't describe it; show the row without a price
let introOffer: StoreProduct.IntroductoryOffer? // only when this Apple Account may have it
}
func currentPaywallRows() async throws -> (headline: String?, rows: [PaywallRow]) {
let offerings = try await BlainkPurchases.shared.offerings() // read from Blaink each time
guard let current = offerings.current else { return (nil, []) } // none is current yet
var headline: String?
if case let .string(text)? = current.metadata["headline"] { headline = text }
let rows = current.packages.map { package in // the console's order, App Store packages only
PaywallRow(
package: package,
price: package.storeProduct?.priceString,
introOffer: package.storeProduct?.isEligibleForIntroOffer == true
? package.storeProduct?.introductoryOffer : nil
)
}
return (headline, rows)
}currentis nil until an operator makes an offering current. While an experiment runs, it can differ between customers.offerings["sale"]reads any offering by its identifier.packagesare in the console's order, and only those with an App Store product.current.package("annual")finds one by identifier.storeProductis nil when the App Store didn't describe the product: hide the price, not the package, as buying it may still work.priceStringis the App Store's price, formatted for the customer.- For a subscription,
subscriptionPeriodandintroductoryOfferdescribe it, andisEligibleForIntroOffersays whether this Apple Account may have the introductory offer, as the App Store answers. metadatais the JSON your operators gave the offering, asMetadataValuecases. Every app receives it, so it holds nothing secret.
Show a paywall
BlainkPaywallView, from BlainksPaywalls, draws in SwiftUI a paywall your operators designed and published in the console (Paywalls): its packages with App Store prices, a purchase button and Restore. It buys and restores through BlainkPurchases, so what it buys reaches customerInfoUpdates too.
In a SwiftUI sheet
import BlainksPaywalls
import BlainksPurchases
import SwiftUI
struct UpgradeButton: View {
@State private var showsPaywall = false
@State private var isPro = false
var body: some View {
Button("Upgrade") { showsPaywall = true }
.disabled(isPro)
.sheet(isPresented: $showsPaywall) {
BlainkPaywallView(
offering: nil, // nil: the current offering's paywall
variables: ["user_name": "Ada"], // fills {{custom.user_name}}
onPurchaseCompleted: { info in
isPro = info.isActive("pro")
showsPaywall = false
},
onRestoreCompleted: { info in
// It says "nothing to restore" itself: act only on what was found
if info.isActive("pro") {
isPro = true
showsPaywall = false
}
},
onClose: { showsPaywall = false },
onFailure: { error in
// It didn't load (it shows its own message and a Close button), or a
// purchase or restore failed (it says so and stays open)
print("Paywall:", error)
}
)
}
}
}BlainkPaywallView(offering:)loads that offering's paywall;nil, the default, is the current offering's.BlainkPaywallView(paywall:)draws one you loaded withpaywall(offering:).variablesfills{{custom.<name>}}in its texts; the paywall's own defaults cover the rest.- Its callbacks run on the main actor. It keeps the ones it was first created with.
onPurchaseCompletedfollows a purchase Blaink recorded. A cancelled purchase calls nothing; a pending one shows "Your purchase is waiting for approval." and calls nothing either.onRestoreCompletedfollows every restore, even one that found nothing — the paywall then says so itself, so show no message of your own.onClosefollows its close button. A close button appears only if the published design has one; the screen shown when loading failed always has one.onFailurefollows a paywall that couldn't load (it shows "This offer isn't available right now.") or a purchase or restore that failed (it says so and stays open).- Without
onPurchaseCompletedoronClose, the view dismisses itself after a purchase or a close; withoutonRestoreCompleted, after a restore that unlocked something. - It is served in the device's first preferred language, not the language set with Blaink's localisation. Its own labels exist in English, Turkish, German, Spanish, French and Russian; other languages get English ones.
Fall back to your own paywall
To show your own when there's none to show, load it first: paywall(offering:) throws before anything is on screen.
import BlainksPaywalls
import BlainksPurchases
import SwiftUI
struct OnboardingPaywall: View {
@State private var paywall: Paywall?
@State private var showsOwnPaywall = false
var body: some View {
Group {
if let paywall {
BlainkPaywallView(paywall: paywall)
} else if showsOwnPaywall {
MyPaywall() // your own paywall view
} else {
ProgressView()
}
}
.task {
do {
paywall = try await BlainkPurchases.shared.paywall(offering: "onboarding")
} catch PurchasesError.customerBlocked {
// An operator blocked this customer: what they buy unlocks nothing, so offer nothing
} catch {
showsOwnPaywall = true // .paywallNotFound, .paywallUnreadable, .unavailable, …
}
}
}
}From UIKit
There is no view controller of its own: host the view in a UIHostingController (an NSHostingController on macOS), and dismiss it from the callbacks.
import BlainksPaywalls
import BlainksPurchases
import SwiftUI
import UIKit
@MainActor
func presentPaywall(from presenter: UIViewController) {
weak var host: UIViewController?
let paywall = BlainkPaywallView(
onPurchaseCompleted: { _ in host?.dismiss(animated: true) },
onRestoreCompleted: { info in
if !info.activeEntitlements.isEmpty { host?.dismiss(animated: true) }
},
onClose: { host?.dismiss(animated: true) },
onFailure: { error in print("Paywall:", error) }
)
let controller = UIHostingController(rootView: paywall)
host = controller
presenter.present(controller, animated: true)
}A close doesn't mean nothing was bought
An Ask to Buy request approved later, or a payment that clears after the paywall is gone, still unlocks the purchase. Keep listening to customerInfoUpdates (step 6) rather than deciding on the close.
Buy without a paywall
purchase shows Apple's sheet, with the device's Blaink user as the transaction's account token, waits for Blaink to record the transaction, and answers. It takes a Package from the offerings, an App Store product ID, or a StoreKit Product you loaded.
import BlainksPurchases
/// What to tell the customer after they chose a package on your own paywall.
func buy(_ package: Package) async -> String {
do {
// Also by App Store product ID, purchase("pro_monthly"), or with a StoreKit Product you loaded
switch try await BlainkPurchases.shared.purchase(package) {
case let .purchased(info):
return info.isActive("pro") ? "Welcome to Pro" : "Thank you"
case .cancelled:
return ""
case .pending:
// Ask to Buy, or a payment still to clear: customerInfoUpdates hears it once it goes through
return "Waiting for approval"
@unknown default:
return ""
}
} catch PurchasesError.refused(let reason) {
return "Refused (\(reason))" // final: asking again changes nothing
} catch PurchasesError.unavailable {
return "Try again in a moment" // nothing is lost: StoreKit hands the transaction over again
} catch PurchasesError.productNotFound(let productID) {
return "\(productID) isn't on sale"
} catch {
return error.localizedDescription // StoreKit's own errors pass through
}
}.purchased(info): Blaink recorded it;infois what the customer may use now..cancelled: the customer closed the sheet, or StoreKit couldn't verify the transaction on the device..pending: Ask to Buy, or a payment still to clear. StoreKit hands the transaction over once it goes through, andcustomerInfoUpdateshears Blaink's answer.- Blaink finishes a transaction only once it has recorded or refused it. When Blaink can't be reached, the transaction stays unfinished and StoreKit hands it over again, so nothing bought is lost.
- A consumable is bought the same way and finished like anything else. It unlocks no entitlement, so deliver what it buys when
purchaseanswers.purchased.
| Error | What it means |
|---|---|
PurchasesError.refused(reason:) | Blaink refused it; reason is its key (the next table). Final: asking again changes nothing, and the transaction is finished — except in observer mode. |
.unavailable | Nothing was decided: Blaink couldn't be reached or didn't answer, the first launch's sign-in took over 30 seconds, or the account was deleted while the call waited. A transaction stays unfinished, and StoreKit hands it over again. Safe to try again. |
.productNotFound(_:) | The App Store has no product of that ID for this app; the ID is the case's value. |
.paywallNotFound | From paywall(offering:): none is published for the offering, there is no such offering or none is current, or the App Store sells none of its packages. |
.paywallUnreadable | From paywall(offering:): a paywall this SDK version can't draw, such as a newer format. Show your own. |
.customerBlocked | From paywall(offering:): an operator blocked this customer. What they buy unlocks nothing, so show no paywall. |
| StoreKit's own errors | Loading the product and the purchase itself throw them unchanged; restorePurchases() passes on the App Store sync's, such as a cancelled sign-in. |
PurchasesError and PurchaseResult may gain cases in a later SDK: end a switch over either with @unknown default, as the sample does.
| Refusal key | From | What it means |
|---|---|---|
purchase_evidence_rejected | Purchase, restore | The App Store didn't sign the transaction, doesn't know it, or it is another app's. Every transaction from a StoreKit configuration file is refused this way (step 12). |
purchase_store_not_configured | Purchase, restore | The SDK key the app signed in with isn't an iOS platform's in the console. |
purchase_owned_by_another_customer | Purchase, restore | What it named stays with another customer: the account the device logged out of, or a first owner the project's shared-purchases setting keeps it with (Shared purchases and transfers). |
purchase_app_user_id_invalid | logIn | The ID is empty or over 255 characters, starts or ends with whitespace, or holds a control character. |
purchase_login_token_required | logIn | The project requires signed logins, and no token was sent. |
purchase_login_token_invalid | logIn | The token isn't valid for this ID, this project and this moment (Sign logins). |
purchase_attribute_key_invalid, purchase_attribute_key_reserved, purchase_attribute_value_invalid, purchase_attribute_limit_reached | setAttributes | An attribute broke a rule; nothing was written (step 9). |
paywall(offering:) turns purchase_paywall_not_found and purchase_customer_blocked into their own cases. reason carries any key that starts with purchase_, so a newer server may send one not listed here: treat it as final too.
Check entitlements
customerInfo() asks Blaink what the customer may use now. isActive("pro") checks one entitlement; entitlements holds every one ever granted, each with isActive, expirationDate (nil for life), willRenew, hasBillingIssue, periodType, store and isSandbox. An entitlement granted from the console or by your server reads with store .unknown, as the SDK has no case for a grant, and productIdentifier promotional; its isActive is right all the same.
customerInfoUpdates hears every answer Blaink gives this device: after your purchases, restores, customerInfo() calls, logins and logouts, after start's launch report, and after each transaction StoreKit hands over while the app runs — a renewal, an Ask to Buy approval, a purchase made with the same Apple Account on another device. A new listener hears the latest answer first. After the account is deleted, here or from the console or your server, it hears the new anonymous customer.
Nothing else reaches it: Blaink pushes nothing to the device. A grant or a block made in the console or by your server, or a subscription that lapses, reaches the app only the next time it asks — so ask again when the app returns to the foreground.
import BlainksPurchases
import SwiftUI
@MainActor
final class Entitlements: ObservableObject {
@Published private(set) var isPro = false
/// Every answer Blaink gives this device, the latest one first.
func follow() async {
for await info in BlainkPurchases.shared.customerInfoUpdates {
isPro = info.isActive("pro")
}
}
/// What Blaink knows now: a grant, a block or a lapsed subscription reaches the app only when it asks.
func refresh() async {
if let info = try? await BlainkPurchases.shared.customerInfo() {
isPro = info.isActive("pro")
}
}
}
struct RootView: View {
@StateObject private var entitlements = Entitlements()
@Environment(\.scenePhase) private var scenePhase
var body: some View {
Text(entitlements.isPro ? "Pro" : "Free")
.task { await entitlements.follow() } // stops when the view goes away
.onChange(of: scenePhase) { phase in
if phase == .active { Task { await entitlements.refresh() } }
}
}
}Restore purchases
restorePurchases() is your Restore Purchases button. It asks the App Store to sync the account's transactions, which may ask the customer to sign in, then reports each one that entitles them now and answers what Blaink decided. Every transaction is tried, and the first failure is thrown after the rest; with nothing to report, it answers as customerInfo() does. Unlike the launch report, a restore can move a purchase from another account, as the project's shared-purchases setting allows (Shared purchases and transfers).
import BlainksPurchases
/// Your Restore Purchases button.
func restore() async -> Bool {
do {
let info = try await BlainkPurchases.shared.restorePurchases()
return info.isActive("pro")
} catch {
// A PurchasesError, or StoreKit's own: the customer cancelled the App Store sign-in, say
return false
}
}Log customers in
The customer starts as the device's anonymous one. If your app has its own accounts, call logIn after your sign-in, with your user's ID: their purchases then follow them to every device, and what this device bought before comes with them (what moves, and when: Log in to your account). Blaink remembers the login per device, so don't call it on every launch.
import BlainksPurchases
/// After your own sign-in. `loginToken`: one your backend signed for `userID` just now, or nil
/// while the project accepts unsigned logins.
func didSignIn(userID: String, loginToken: String?) async {
do {
let info = try await BlainkPurchases.shared.logIn(userID, loginToken: loginToken)
print(info.appUserID ?? userID, "holds", info.activeEntitlements)
} catch PurchasesError.refused(let reason) {
// purchase_login_token_required, purchase_login_token_invalid or purchase_app_user_id_invalid
print("Login refused:", reason)
} catch {
// .unavailable: nothing changed; safe to call again
}
}
/// After your own sign-out.
func didSignOut() async {
_ = try? await BlainkPurchases.shared.logOut()
}
/// Who Blaink's last answer says the customer is; nil while logged out.
var currentAppUserID: String? { BlainkPurchases.shared.appUserID }- The ID is yours: 1 to 255 characters, taken as it is, so case counts, with no whitespace at either end and no control characters; otherwise
purchase_app_user_id_invalid. It is kept on the device unencrypted, so use an opaque ID, not an email address. loginToken(SDK 2.4.0) proves the login is your user's: a short-lived token your backend signs for that ID (Sign logins). Fetch a new one right before eachlogIn; an empty one counts as none. Once the project requires signed logins, a login without one is refused. Until then Blaink trusts the ID it is sent, so use one nobody can guess.logIn(_:), without a token, still works for a project that accepts unsigned logins.appUserIDis who Blaink's last answer says the customer is; nil while logged out.logOut()makes the device's anonymous customer the customer again. Purchases stay with the account: until the customer logs in again, restoring them, or buying them again, is refused withpurchase_owned_by_another_customer(Log out).logIn,logOut,setAttributesandsetConsumptionConsentrun one at a time, in the order you call them, and finish even if the screen that called them goes away.
Set attributes
Attributes (SDK 2.4.0) are your own facts about the customer — a sign-up source, a plan tier — which the console's audiences can match (Customers).
import BlainksPurchases
func recordSignUp(source: String) async {
do {
let held = try await BlainkPurchases.shared.setAttributes([
"signup_source": source, // set
"coupon": nil // nil or "" removes it
])
print("The customer now holds", held) // every attribute, after the write
} catch PurchasesError.refused(let reason) {
print("Nothing written:", reason) // purchase_attribute_key_invalid, …
} catch {
// .unavailable: nothing written; safe to try again
}
}setAttributessets each key you give and removes each whose value is nil or empty; keys you leave out keep their values. It answers every attribute the customer holds after the write, so an empty write reads them.- They are for whoever the device is once earlier logins and logouts have answered: the account, else the anonymous customer. A first login moves the device's attributes to the account.
- A key is a letter, then letters, digits,
_,-or., at most 40 characters, case-sensitive and not starting with$, which is Blaink's. A value is at most 500 characters, with no control characters. A customer holds at most 50. - A write that breaks a rule changes nothing and is refused:
purchase_attribute_key_invalid,purchase_attribute_key_reserved,purchase_attribute_value_invalidorpurchase_attribute_limit_reached. - Debug logs show the keys, never the values.
Refund-request consent
When a customer asks Apple for a refund, Apple asks your server what it knows about the purchase and weighs the answer. Blaink answers for you, but only for a customer whose consent your app recorded (SDK 2.4.0), as Apple requires, and only once the project turns on Refund requests (Consent and refund requests).
Ask the person in your app first — what is shared, and why — then record their answer, false included. They can change it at any time; only the latest counts. The answer is the consent as Blaink keeps it: consented, source (.sdk, or .s2s when your server recorded it) and recordedAt.
import BlainksPurchases
/// After you asked the person, in your own words, whether Blaink may tell Apple about their
/// purchases when they ask Apple for a refund. Record a "no" too.
func recordRefundConsent(_ agreed: Bool) async {
do {
let consent = try await BlainkPurchases.shared.setConsumptionConsent(consented: agreed)
print(consent.consented, consent.source, consent.recordedAt) // source: .sdk, or .s2s from your server
} catch {
// .unavailable: nothing recorded; try again later
}
}Delete an account
Blaink.shared.deleteAccount(), in the core SDK (2.4.0), deletes the device's Blaink user and what Blaink keeps about them. For purchases, that means:
- Their customer is deleted from Purchases in every project: the app user ID, grants, attributes, consent and virtual-currency balances. Their purchases and revenue stay, owned by nobody.
- A device logged in to an account is logged out first, and the account is kept. To delete the account too, do it from your server (Delete a customer).
- Nothing is cancelled at the App Store: tell the person to cancel any subscription in their Apple Account settings.
- Once it succeeds, the device forgets
appUserIDand the last answer and signs in as a new anonymous user, andcustomerInfoUpdateshears the new customer. A purchases call made before the deletion and not yet sent throws.unavailable. - A user deleted another way — from the console, or by your server — is forgotten the same way when the SDK's next request learns of it. Your app hears it only through
customerInfoUpdates.
import Blainks
func deleteMyAccount() async -> Bool {
do {
try await Blaink.shared.deleteAccount()
// Gone. Remind the person to cancel any subscription in their Apple Account settings.
return true
} catch {
// A BlainkError: what each case means is in the core SDK guide
return false
}
}Its errors and when to try again: the core iOS guide.
Test
Sign a sandbox Apple Account in on the device under Settings → Developer, and buy from a development or TestFlight build. Sandbox purchases unlock entitlements as real ones do, with isSandbox true, and stay out of revenue. Once the customer owns a purchase, they appear on the console's Customers page.
StoreKit configuration files are local
Xcode signs those transactions with its own certificate, not Apple's, so Blaink refuses them with purchase_evidence_rejected. Use one to work on your paywall's layout; test purchases against the App Store sandbox.
Before release, go through Go live.
Google Play Billing sells. Play signs nothing an app sends, so Blaink looks each purchase up with Google as your app's service account, records it under the customer, and answers what they may use — their entitlements, the same ones your iOS app and your server read. Set up Google Play first: Connect your stores.
Install
blaink-purchases comes from the same Maven repository as blaink, https://blainks.com/maven (see the core Android guide), at the same version. It brings Google Play Billing with it and needs API 23; an app without purchases keeps blaink's API 21. For the ready-made paywall, add blaink-paywalls too: it brings blaink-purchases and Jetpack Compose with it, and also needs API 23.
android {
compileSdk = 34 // or higher: AndroidX libraries the SDK uses need it
defaultConfig {
minSdk = 23 // blaink-purchases and blaink-paywalls
}
buildFeatures {
compose = true // only for the BlainkPaywall composable (on Kotlin 2, with the Compose compiler plugin)
}
}
dependencies {
implementation("com.blainks:blaink:2.3.0")
implementation("com.blainks:blaink-purchases:2.3.0") // brings Google Play Billing
// The ready-made paywall: BlainkPaywall (Compose) and BlainkPaywallContract; brings blaink-purchases
implementation("com.blainks:blaink-paywalls:2.3.0")
// What the blaink, blaink-core and blaink-push POMs leave out. Without these the app builds,
// then crashes when the SDK first runs. The versions are the ones the SDK is built with.
implementation("com.squareup.retrofit2:retrofit:2.11.0")
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:1.0.0")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.3")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
implementation("androidx.security:security-crypto:1.1.0-alpha06")
implementation("androidx.core:core-ktx:1.13.1")
implementation(platform("com.google.firebase:firebase-bom:33.7.0"))
implementation("com.google.firebase:firebase-messaging")
}- The POMs of
blaink,blaink-coreandblaink-pushdeclare none of the libraries those modules use, so Gradle doesn't fetch them: list them yourself, as above. Without them the app builds, then crashes when the SDK first runs. The purchases and paywalls POMs do bring Play Billing and Compose. - Compile against API 34 or higher: the AndroidX versions the SDK uses require it.
- The
BlainkPaywallcomposable needs Compose turned on in your app module, which on Kotlin 2 means theorg.jetbrains.kotlin.plugin.composeplugin too.BlainkPaywallContract, for an app without Compose, needs neither. - Import
com.blaink.purchases.Packageby name wherever you use a package: without that import,Packagemeansjava.lang.Package, and the compiler's type mismatch says nothing about Blaink.
Start it
Call start once, in your Application's onCreate, after Blaink's setup. It reports what Play holds for the customer now — so a purchase made before Blaink, or offline, is recorded — and listens for purchases Play completes while the app runs, such as a pending payment that goes through.
import android.app.Application
import com.blaink.Blaink
import com.blaink.purchases.BlainkPurchases
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
Blaink.getInstance().setup(this, "YOUR_SDK_KEY") // first, as in the core SDK guide
BlainkPurchases.start(this)
}
}- Only the first call counts. Later calls are ignored, a different
completionincluded. - Every
BlainkPurchasesmember throwsIllegalStateExceptionuntilstarthas run. - On a first launch, Blaink's sign-in may still be under way. Every purchases call waits for it up to 30 seconds, then throws
PurchasesException.Unavailablewith nothing sent or bought; calling again is safe. Ifstart's own report gives up the same way, it is made again on the next launch. From the second launch the device's Blaink user is known, and nothing waits.
Another billing library still running? Start in observer mode instead: Blaink records every purchase and acknowledges none. That includes what BlainkPurchases.purchase buys, and Play refunds a purchase nobody acknowledges within three days, so keep buying through the other library until you switch. Moving from another provider: Migrate.
import android.app.Application
import com.blaink.Blaink
import com.blaink.purchases.BlainkPurchases
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
Blaink.getInstance().setup(this, "YOUR_SDK_KEY")
// Blaink records every purchase and acknowledges none: your existing billing code still must
BlainkPurchases.start(this, BlainkPurchases.Completion.OBSERVER)
}
}Read offerings
An offering is a set of packages your operators arrange in the console, so what your paywall sells changes without an app release. offerings() reads them from Blaink each time — nothing is cached — with what Google Play says about each package's product.
import com.blaink.purchases.BlainkPurchases
import com.blaink.purchases.MetadataValue
import com.blaink.purchases.Package // without it, Package means java.lang.Package
import com.blaink.purchases.StoreProduct
/** One row of your own paywall. */
data class PaywallRow(
val pack: Package,
val price: String?, // null: Play didn't describe it; show the row without a price
val introOffer: StoreProduct.IntroductoryOffer? // a trial or intro price Play offers this customer
)
suspend fun currentPaywallRows(): Pair<String?, List<PaywallRow>> {
val offerings = BlainkPurchases.offerings() // read from Blaink each time
val current = offerings.current ?: return null to emptyList() // none is current yet
val headline = (current.metadata["headline"] as? MetadataValue.StringValue)?.value
val rows = current.packages.map { pack -> // the console's order, Play packages only
PaywallRow(pack, pack.storeProduct?.priceString, pack.storeProduct?.introductoryOffer)
}
return headline to rows
}currentis null until an operator makes an offering current. While an experiment runs, it can differ between customers.offerings["sale"]reads any offering by its identifier.packagesare in the console's order, and only those with a Play product.current["annual"]finds one by identifier.storeProductis null when Play didn't describe the product or base plan: hide the price, not the package, as buying it may still work.priceStringis Play's price, formatted for the customer, after any trial or introductory price.metadatais the JSON your operators gave the offering, asMetadataValuesubclasses. Every app receives it, so it holds nothing secret.
Base plans and offers
A package can name a Play base plan, and an offer on it, when the console gives one (on the package, or as the product's default). The SDK sells:
- the named offer, when Play returns it for this customer;
- otherwise, the named base plan's own price;
- with no plan named, the first base-plan price Play lists, never a promotional offer.
A named base plan Play doesn't have sells nothing: ProductNotFound. Only offers whose eligibility in the Play Console is New customer acquisition are supported, as Play returns those only to customers who may have them. A Developer determined offer would be sold to everyone, and an Upgrade offer bought as a second subscription. storeProduct.introductoryOffer is the trial or introductory price of the offer Play returned, and isEligibleForIntroOffer is simply whether there is one.
Show a paywall
blaink-paywalls draws a paywall your operators designed and published in the console (Paywalls): its packages with Play prices, a purchase button and Restore. It buys and restores through BlainkPurchases, so what it buys reaches customerInfoUpdates too.
In Compose
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import com.blaink.paywalls.BlainkPaywall
@Composable
fun UpgradeScreen(onPro: () -> Unit) {
var showsPaywall by rememberSaveable { mutableStateOf(true) }
if (showsPaywall) {
BlainkPaywall(
offering = null, // null: the current offering's paywall
variables = mapOf("user_name" to "Ada"), // fills {{custom.user_name}}
onPurchaseCompleted = { info ->
if (info.isActive("pro")) onPro()
showsPaywall = false
},
onRestoreCompleted = { info ->
// It says "nothing to restore" itself: act only on what was found
if (info.isActive("pro")) {
onPro()
showsPaywall = false
}
},
onClose = { showsPaywall = false },
onFailure = { error ->
// It didn't load (it shows its own message and a close button), or a
// purchase or restore failed (it says so and stays open)
Log.w("Paywall", error)
}
)
}
}BlainkPaywall(offering = …)loads that offering's paywall;null, the default, is the current offering's.BlainkPaywall(paywall = …)draws one you loaded withBlainkPurchases.paywall(offering).variablesfills{{custom.<name>}}in its texts; the paywall's own defaults cover the rest.- Its callbacks run on the main thread, and the latest ones you pass are the ones called.
onPurchaseCompletedfollows a purchase Blaink recorded. A cancelled purchase calls nothing; a pending one shows "Your purchase is waiting for approval." and calls nothing either.onRestoreCompletedfollows every restore, even one that found nothing — the paywall then says so itself, so show no message of your own.onClosefollows its close button and Back.onFailurefollows a paywall that couldn't load (it shows "This offer isn't available right now." and a close button) or a purchase or restore that failed (it says so and stays open).- Without
onPurchaseCompletedoronClose, it calls the activity's Back after a purchase or a close; withoutonRestoreCompleted, after a restore that unlocked something. - It needs a
ViewModelStoreOwner, and anActivityinLocalContextto buy with: without one, its purchase button does nothing. A rotation is neither a close nor a new impression. - It is served in the language of
Locale.getDefault(). Its own labels exist in English, Turkish, German, Spanish, French and Russian; other languages get English ones.
From an activity, without Compose
BlainkPaywallContract starts BlainkPaywallActivity and answers how it ended: Purchased; Restored, only when a restore unlocked something; Closed, by its close button or Back, with the last purchase or restore that failed as lastError; or Failed, when no paywall could be shown. An activity the system ended without an answer reads as Closed().
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import com.blaink.paywalls.BlainkPaywallContract
import com.blaink.paywalls.PaywallResult
import com.blaink.purchases.CustomerInfo
class UpgradeActivity : ComponentActivity() {
private val paywall = registerForActivityResult(BlainkPaywallContract()) { result ->
when (result) {
is PaywallResult.Purchased -> render(result.customerInfo)
is PaywallResult.Restored -> render(result.customerInfo) // only when a restore unlocked something
is PaywallResult.Closed -> result.lastError?.let { Log.w("Paywall", it) } // it told the customer
is PaywallResult.Failed -> showOwnPaywall() // nothing could be shown
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Only on a fresh start: after a rotation or process death the paywall is already up, or was closed
if (savedInstanceState == null) {
paywall.launch(BlainkPaywallContract.Input(offering = null, variables = mapOf("user_name" to "Ada")))
}
}
private fun render(info: CustomerInfo) {
// Your own: unlock what info.isActive("pro") allows
}
private fun showOwnPaywall() {
// Your own paywall
}
}A close doesn't mean nothing was bought
A pending payment that clears after the paywall is gone still unlocks the purchase. Keep collecting customerInfoUpdates (step 6) rather than deciding on the close.
Buy without a paywall
purchase shows Play's sheet, with the device's Blaink user as the purchase's obfuscated account ID, waits for Blaink to record the purchase, and only then acknowledges it — or consumes it, for a consumable. It takes a Package from the offerings, which sells the base plan or offer it names, or a Play product ID. Call it from a coroutine, with the activity to show the sheet on.
import android.app.Activity
import com.blaink.purchases.BlainkPurchases
import com.blaink.purchases.Package
import com.blaink.purchases.PurchaseResult
import com.blaink.purchases.PurchasesException
/** What to tell the customer after they chose a package on your own paywall. */
suspend fun buy(activity: Activity, pack: Package): String =
try {
// Also by Play product ID: BlainkPurchases.purchase(activity, "pro_monthly")
when (val result = BlainkPurchases.purchase(activity, pack)) {
is PurchaseResult.Purchased -> if (result.customerInfo.isActive("pro")) "Welcome to Pro" else "Thank you"
PurchaseResult.Cancelled -> ""
// A payment still to clear: customerInfoUpdates hears it if Play completes it while the app runs
PurchaseResult.Pending -> "Waiting for your payment"
}
} catch (e: PurchasesException) {
when (e) {
is PurchasesException.Refused -> "Refused (${e.reason})" // final: the purchase is acknowledged
PurchasesException.Unavailable -> "Try again in a moment" // left unacknowledged: reported again
is PurchasesException.ProductNotFound -> "${e.productId} isn't on sale"
else -> e.message.orEmpty()
}
}
/** A consumable (coins, a hint) is consumed, so it can be bought again. */
suspend fun buyCoins(activity: Activity): PurchaseResult =
BlainkPurchases.purchase(activity, "coins_100", consumable = true)Purchased: Blaink recorded it;customerInfois what the customer may use now.Cancelled: the customer closed the sheet.Pending: a payment still to clear. When Play completes it while the app runs, Blaink records it andcustomerInfoUpdateshears the answer; otherwise the next launch'sstartpicks it up.- When Blaink can't be reached, the purchase stays unacknowledged, and Play hands it over again at the next
start.
Connect Google Play before you ship
Without a Play service account saved in the console, Blaink refuses every Play purchase with purchase_store_not_configured, and the SDK, taking the refusal as final, acknowledges the purchase anyway: the customer is charged, Blaink records nothing, and Play never hands that purchase over again. Save the service account (Google Play: add a service account) before anyone can buy.
| Exception | What it means |
|---|---|
PurchasesException.Refused | Blaink refused it; reason is its key (the next table). Final: asking again changes nothing, and the purchase is acknowledged or consumed — except in observer mode. |
PurchasesException.Unavailable | Nothing was decided: Blaink couldn't be reached or didn't answer, the first launch's sign-in took over 30 seconds, or the account was deleted while the call waited. Also Play's own failures — the billing service unavailable, the sheet not opening, an item already owned — where nothing was bought. A purchase Blaink wasn't told about stays unacknowledged and is reported again. Safe to try again. |
PurchasesException.ProductNotFound | Play has no product of that ID for this app, or no base plan of the name the package gives; productId says which. |
PurchasesException.PaywallNotFound | From paywall(): none is published for the offering, there is no such offering or none is current, or Play sells none of its packages. |
PurchasesException.PaywallUnreadable | From paywall(): a paywall this SDK version can't draw, such as a newer format. Show your own. |
PurchasesException.CustomerBlocked | From paywall(): an operator blocked this customer. What they buy unlocks nothing, so show no paywall. |
IllegalStateException | Not a PurchasesException: a call made before BlainkPurchases.start(context). |
Catch PurchasesException as a whole, as the sample does: one that escapes lifecycleScope.launch crashes the app.
| Refusal key | From | What it means |
|---|---|---|
purchase_evidence_rejected | Purchase, restore | Google doesn't know the purchase, or it is another app's. |
purchase_store_not_configured | Purchase, restore | No Play service account is saved in the console, so Blaink can't look the purchase up. The purchase is acknowledged anyway: see the warning above. |
purchase_owned_by_another_customer | Purchase, restore | What it named stays with another customer: the account the device logged out of, or a first owner the project's shared-purchases setting keeps it with (Shared purchases and transfers). |
purchase_app_user_id_invalid | logIn | The ID is empty or over 255 characters, starts or ends with whitespace, or holds a control character. |
purchase_login_token_required | logIn | The project requires signed logins, and no token was sent. |
purchase_login_token_invalid | logIn | The token isn't valid for this ID, this project and this moment (Sign logins). |
purchase_attribute_key_invalid, purchase_attribute_key_reserved, purchase_attribute_value_invalid, purchase_attribute_limit_reached | setAttributes | An attribute broke a rule; nothing was written (step 9). |
paywall() turns purchase_paywall_not_found and purchase_customer_blocked into their own exceptions. reason carries any key that starts with purchase_, so a newer server may send one not listed here: treat it as final too.
Consumables
Pass consumable = true for coins, hints and the like: the purchase is consumed, so it can be bought again; anything else is acknowledged. A consumable unlocks no entitlement, so deliver what it buys when purchase answers Purchased. Two limits:
- A paywall always buys with
consumable = false, so sell consumables through your own purchase call, not from a paywall. - The SDK remembers that a product is consumable only while the app runs. A consumable whose report failed, and that is reported again on a later launch, is acknowledged rather than consumed, and can't be bought again.
Check entitlements
customerInfo() asks Blaink what the customer may use now. isActive("pro") checks one entitlement; entitlements holds every one ever granted, each with isActive, expirationDate (null for life), willRenew, hasBillingIssue, periodType, store and isSandbox. An entitlement granted from the console or by your server reads with store UNKNOWN, as the SDK has no value for a grant, and productIdentifier promotional; its isActive is right all the same.
customerInfoUpdates emits only the answers this device receives: after your purchases, restores, customerInfo() calls, logins and logouts, after start's launch report, and after a purchase Play completes while the app runs. A new collector gets the latest answer first. After the account is deleted, here or from the console or your server, it emits the new anonymous customer.
It doesn't poll, and Blaink pushes nothing to the device: a renewal, a refund, a purchase on another device, or a grant or block made in the console or by your server, reaches the app only the next time it asks. So ask whenever a screen starts, and collect with repeatOnLifecycle, so collecting stops while the screen is stopped.
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.blaink.purchases.BlainkPurchases
import com.blaink.purchases.CustomerInfo
import com.blaink.purchases.PurchasesException
import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
// Ask Blaink each time the screen starts: its answer reaches the flow below too
launch {
try {
BlainkPurchases.customerInfo()
} catch (e: PurchasesException) {
// Unavailable: the flow keeps the last answer
}
}
// The latest answer at once, then every answer this device gets
BlainkPurchases.customerInfoUpdates.collect { info -> render(info) }
}
}
}
private fun render(info: CustomerInfo) {
// Your own: show what info.isActive("pro") allows
}
}Restore purchases
restorePurchases() is your Restore Purchases button. It reports every paid purchase Play holds for the Google account — subscriptions and one-time products — and answers what Blaink decided; it shows nothing to the customer. Every purchase is tried, and the first failure is thrown after the rest; with nothing to report, it answers as customerInfo() does. Unlike the launch report, a restore can move a purchase from another account, as the project's shared-purchases setting allows (Shared purchases and transfers).
import com.blaink.purchases.BlainkPurchases
import com.blaink.purchases.PurchasesException
/** Your Restore Purchases button, from a coroutine. */
suspend fun restore(): Boolean =
try {
BlainkPurchases.restorePurchases().isActive("pro")
} catch (e: PurchasesException) {
false // the first failure, after every purchase was tried
}Log customers in
The customer starts as the device's anonymous one. If your app has its own accounts, call logIn after your sign-in, with your user's ID: their purchases then follow them to every device, and what this device bought before comes with them (what moves, and when: Log in to your account). Blaink remembers the login per device, so don't call it on every launch.
import android.util.Log
import com.blaink.purchases.BlainkPurchases
import com.blaink.purchases.PurchasesException
/**
* After your own sign-in. loginToken: one your backend signed for userId just now, or null while
* the project accepts unsigned logins.
*/
suspend fun didSignIn(userId: String, loginToken: String?) {
try {
val info = BlainkPurchases.logIn(userId, loginToken = loginToken)
Log.i("Purchases", "${info.appUserID ?: userId} holds ${info.activeEntitlements}")
} catch (e: PurchasesException.Refused) {
// purchase_login_token_required, purchase_login_token_invalid or purchase_app_user_id_invalid
Log.w("Purchases", "Login refused: ${e.reason}")
} catch (e: PurchasesException) {
// Unavailable: nothing changed; safe to call again
}
}
/** After your own sign-out: BlainkPurchases.logOut(), not the core SDK's logout(). */
suspend fun didSignOut() {
try {
BlainkPurchases.logOut()
} catch (e: PurchasesException) {
// Unavailable: still logged in; safe to call again
}
}
/** Who Blaink's last answer says the customer is; null while logged out. */
val currentAppUserId: String?
get() = BlainkPurchases.appUserID- The ID is yours: 1 to 255 characters, taken as it is, so case counts, with no whitespace at either end and no control characters; otherwise
purchase_app_user_id_invalid. It is kept on the device unencrypted, so use an opaque ID, not an email address. loginToken(SDK 2.3.0) proves the login is your user's: a short-lived token your backend signs for that ID (Sign logins). Fetch a new one right before eachlogIn. Once the project requires signed logins, a login without one is refused. Until then Blaink trusts the ID it is sent, so use one nobody can guess.appUserIDis who Blaink's last answer says the customer is; null while logged out. Like every member, it throwsIllegalStateExceptionbeforestart.logOut()makes the device's anonymous customer the customer again. Purchases stay with the account: until the customer logs in again, restoring them, or buying them again, is refused withpurchase_owned_by_another_customer(Log out).- Sign a person out with
BlainkPurchases.logOut(), not the core SDK'sBlaink.getInstance().logout(), which drops the device's Blaink session until the next launch. logIn,logOutandsetAttributesrun one at a time, in the order you call them, and a login or logout already sent finishes even if the screen that called it goes away.
Set attributes
Attributes (SDK 2.3.0) are your own facts about the customer — a sign-up source, a plan tier — which the console's audiences can match (Customers).
import android.util.Log
import com.blaink.purchases.BlainkPurchases
import com.blaink.purchases.PurchasesException
suspend fun recordSignUp(source: String) {
try {
val held: Map<String, String> = BlainkPurchases.setAttributes(
mapOf(
"signup_source" to source, // set
"coupon" to null // null or "" removes it
)
)
Log.i("Purchases", "The customer now holds $held") // every attribute, after the write
} catch (e: PurchasesException.Refused) {
Log.w("Purchases", "Nothing written: ${e.reason}") // purchase_attribute_key_invalid, …
} catch (e: PurchasesException) {
// Unavailable: nothing written; safe to try again
}
}setAttributessets each key you give and removes each whose value is null or empty; keys you leave out keep their values. It answers every attribute the customer holds after the write, so an empty map reads them.- They are for whoever the device is once earlier logins and logouts have answered: the account, else the anonymous customer. A first login moves the device's attributes to the account.
- A key is a letter, then letters, digits,
_,-or., at most 40 characters, case-sensitive and not starting with$, which is Blaink's. A value is at most 500 characters, with no control characters. A customer holds at most 50. - A write that breaks a rule changes nothing and is refused:
purchase_attribute_key_invalid,purchase_attribute_key_reserved,purchase_attribute_value_invalidorpurchase_attribute_limit_reached. - Debug logs show the keys, never the values.
Refund-request consent
Not on Android. Consent lets Blaink answer Apple's questions when a customer asks Apple for a refund; Google Play asks no such questions, so the Android SDK has nothing to record. An app on both stores records consent from its iOS app (see the iOS & macOS tab).
Delete an account
Blaink.getInstance().deleteAccount(), in the core SDK (2.3.0), deletes the device's Blaink user and what Blaink keeps about them. For purchases, that means:
- Their customer is deleted from Purchases in every project: the app user ID, grants, attributes, consent and virtual-currency balances. Their purchases and revenue stay, owned by nobody.
- A device logged in to an account is logged out first, and the account is kept. To delete the account too, do it from your server (Delete a customer).
- Nothing is cancelled at Google Play: tell the person to cancel any subscription in the Play Store.
- Once it succeeds, the device forgets
appUserIDand the last answer and signs in as a new anonymous user, andcustomerInfoUpdatesemits the new customer. A purchases call made before the deletion and not yet sent throwsUnavailable. - A user deleted another way — from the console, or by your server — is forgotten the same way when the SDK's next request learns of it. Your app hears it only through
customerInfoUpdates.
import android.util.Log
import com.blaink.Blaink
suspend fun deleteMyAccount(): Boolean =
Blaink.getInstance().deleteAccount()
.onSuccess { /* Gone. Remind the person to cancel any subscription in Google Play. */ }
.onFailure { error -> Log.w("Blaink", "Not deleted", error) } // a BlainkException: see the core SDK guide
.isSuccessIts errors and when to try again: the core Android guide.
Test
Play has no local test store. Add your testers' Google accounts under License testing in the Play Console, create the products there, and install the app from a Play testing track. Licence testers' purchases reach Blaink as sandbox purchases: they unlock entitlements as real ones do, with isSandbox true, and stay out of revenue. Once the customer owns a purchase, they appear on the console's Customers page.
A test purchase is recorded only once the service account is saved and the product is in Blaink's catalogue (Google Play: add a service account). Before release, go through Go live.
One API over the iOS and Android SDKs' purchases: the same products, the same entitlements, the same customer on both stores. Each call runs the native SDK's, so each platform's rules apply, and this tab says where they differ. Set up both stores first: Connect your stores.
Install
Purchases are an add-on to react-native-blaink: an app without it links no purchases code and no Play Billing. Install both at the same version — the add-on requires exactly its own version of the core — and upgrade them together.
# Keep both at the same version: the add-on requires exactly its own version of the core
npm install react-native-blaink react-native-blaink-purchases
cd ios && pod install- The add-on brings the native purchases SDKs and their ready-made paywalls:
BlainksPurchasesandBlainksPaywalls2.4.0 or later on iOS,blaink-purchasesandblaink-paywalls2.3.0 on Android, with Play Billing and the Jetpack Compose runtime. You add no Gradle lines of your own beyond the Maven repository the core React Native guide adds. - iOS: the pods build for iOS 13, but purchases need iOS 15 at run time. On an older iOS every call rejects as
unsupported. - Android: the add-on needs API 24, the libraries'
minSdk. It needs no manifest changes. - It is custom native code, so Expo Go can't run it.
Start it
Call start() once per launch, after Blaink.setup(). It reports what the store holds for the customer now — so a purchase made before Blaink, or offline, is recorded — and listens for what the store completes while the app runs (on iOS a renewal, an Ask to Buy approval or a purchase on another device; on Android a pending payment that goes through). It resolves at once, without waiting for that report.
import { Platform } from 'react-native';
import { Blaink } from 'react-native-blaink';
import { BlainkPurchases } from 'react-native-blaink-purchases';
// Once per launch, outside any component (in index.js, say): an effect can run twice in development.
// Each platform has its own key: a device signed in under the other platform's key can't buy.
Blaink.setup({
sdkKey: Platform.OS === 'ios' ? 'YOUR_IOS_SDK_KEY' : 'YOUR_ANDROID_SDK_KEY',
});
BlainkPurchases.start().catch((error) => {
// unsupported: iOS older than 15, or the add-on isn't linked
console.warn('Blaink purchases did not start', error);
});One SDK key per platform
Replace YOUR_IOS_SDK_KEY and YOUR_ANDROID_SDK_KEY with your iOS and Android platforms' keys. A device set up with the other platform's key signs in under the wrong platform: Blaink then has no store connection for it and refuses every purchase as purchase_store_not_configured, after the store has taken the payment.
- Only the first call counts. Later calls are ignored, a different
observerincluded. - Android: every call rejects as
notStarteduntilstart()has run, so call it before anything else. - On a first launch, Blaink's sign-in may still be under way. Every purchases call waits for it up to 30 seconds, then rejects as
unavailablewith nothing sent or bought; calling again is safe. From the second launch the device's Blaink user is known, and nothing waits.
Another purchases library still running? Start in observer mode instead: Blaink records every purchase and finishes (iOS) or acknowledges (Android) none. That includes what BlainkPurchases.purchase buys — and Play refunds a purchase nobody acknowledges within three days — so keep buying through the other library until you switch. Moving from another provider: Migrate.
import { BlainkPurchases } from 'react-native-blaink-purchases';
// In place of start(): Blaink records every purchase and finishes (iOS) or acknowledges (Android)
// none, so your existing billing code still must
BlainkPurchases.start({ observer: true }).catch((error) => console.warn(error));Read offerings
An offering is a set of packages your operators arrange in the console, so what your paywall sells changes without an app release. getOfferings() reads them from Blaink each time — nothing is cached — with what the store says about each package's product.
import { BlainkPurchases, type Package } from 'react-native-blaink-purchases';
/** One row of your own paywall. */
export interface PaywallRow {
pack: Package;
price: string | null; // null: the store didn't describe it; show the row without a price
}
export async function currentPaywallRows(): Promise<{ headline: string | null; rows: PaywallRow[] }> {
const { current } = await BlainkPurchases.getOfferings(); // read from Blaink each time
if (!current) return { headline: null, rows: [] }; // none is current yet
const headline = typeof current.metadata.headline === 'string' ? current.metadata.headline : null;
const rows = current.packages.map((pack) => ({ // the console's order, this store's packages only
pack,
price: pack.storeProduct?.priceString ?? null,
}));
return { headline, rows };
}currentisnulluntil an operator makes an offering current. While an experiment runs, it can differ between customers.allholds every offering by identifier.packagesare in the console's order, and only those with a product on this device's store.storeProductisnullwhen the store didn't describe the product: hide the price, not the package, as buying it may still work. It holdstitle,description,price,priceString(formatted for the customer) andcurrencyCode; no subscription period or introductory offer reaches JavaScript.- Android only:
basePlanIdentifierandofferIdentifiername the Play base plan and offer the package sells, by the Android SDK's rules (see the Android tab). On iOS both arenull. metadatais the JSON your operators gave the offering. Every app receives it, so it holds nothing secret; a whole number beyond 253 loses precision in JavaScript.
Show a paywall
BlainkPurchases.presentPaywall() shows a paywall your operators designed and published in the console (Paywalls), drawn natively — in SwiftUI on iOS, in a full-screen activity on Android — with its packages, store prices, a purchase button and Restore. It is modal: there is no component to embed.
import { BlainkPurchases, PurchasesError, isEntitlementActive } from 'react-native-blaink-purchases';
/** 'ownPaywall': there's none to show, so show yours. */
export async function showPaywall(): Promise<'pro' | 'closed' | 'ownPaywall'> {
try {
const result = await BlainkPurchases.presentPaywall({
offering: 'onboarding', // left out: the current offering's paywall
variables: { user_name: 'Ada' }, // fills {{custom.user_name}}
presentation: 'sheet', // iOS only: 'sheet' (the default) or 'fullScreen'
});
if (result.outcome === 'closed') {
// The paywall already told the customer about lastError: this is for what you do next
if (result.lastError?.reason === 'purchase_owned_by_another_customer') {
// ask them to log in
}
return 'closed';
}
return isEntitlementActive(result.customerInfo, 'pro') ? 'pro' : 'closed'; // 'purchased' or 'restored'
} catch (error) {
if (error instanceof PurchasesError && (error.kind === 'paywallNotFound' || error.kind === 'paywallUnreadable')) {
return 'ownPaywall';
}
throw error; // customerBlocked, unavailable, paywallAlreadyShown, noActivity, …
}
}offering: whose paywall to show; left out, the current offering's.variablesfills{{custom.<name>}}in its texts; the paywall's own defaults cover the rest. A value that isn't a string is dropped.presentation, iOS only:'sheet'(the default), which the customer can swipe away, or'fullScreen', closed by its button alone. Android always shows its own full-screen activity.
It resolves once, after the paywall is gone, with a PaywallResult:
outcome: 'purchased', withcustomerInfo: Blaink recorded a purchase.outcome: 'restored', withcustomerInfo: a restore unlocked something. One that found nothing says so on the paywall, which stays open.outcome: 'closed': closed with nothing bought through it.lastErroris the last purchase or restore that failed while it was shown, which the paywall has already told the customer; a later restore that found nothing clears it, and on Android so does a cancelled or pending purchase. Show no message of your own.
It rejects only when no paywall is shown: paywallNotFound or paywallUnreadable (show your own), customerBlocked, unavailable, paywallAlreadyShown (one at a time), noActivity (no window on iOS; on Android, no resumed activity — presenting a second paywall straight from the first one's result can hit this), notStarted (Android) or unsupported. getPaywall(offering) reads the paywall's details without showing it, to decide before presenting.
A close doesn't mean nothing was bought
An Ask to Buy request approved later, or a payment that clears after the paywall is gone, still unlocks the purchase. Keep a customer info listener (step 6) rather than deciding on 'closed'.
Buy without a paywall
purchasePackage(pack) buys a package from the offerings, and purchase(productId) a store product by ID. Each shows the store's sheet, waits for Blaink to record the purchase, and resolves with a status. Android needs a foreground activity to show the sheet on.
import { BlainkPurchases, PurchasesError, isEntitlementActive, type Package } from 'react-native-blaink-purchases';
/** What to tell the customer after they chose a package on your own paywall. */
export async function buy(pack: Package): Promise<string> {
try {
// Also by product ID: BlainkPurchases.purchase('pro_monthly')
const outcome = await BlainkPurchases.purchasePackage(pack);
switch (outcome.status) {
case 'purchased':
return outcome.customerInfo && isEntitlementActive(outcome.customerInfo, 'pro') ? 'Welcome to Pro' : 'Thank you';
case 'cancelled':
return '';
case 'pending':
// Ask to Buy, or a payment still to clear: the customer info listener hears it once it goes through
return 'Waiting for approval';
}
} catch (error) {
if (!(error instanceof PurchasesError)) throw error;
switch (error.kind) {
case 'refused':
return `Refused (${error.reason})`; // final: asking again changes nothing
case 'unavailable':
return 'Try again in a moment'; // nothing is lost: the store hands the purchase over again
case 'productNotFound':
return `${error.productId} isn't on sale`;
default:
return error.message;
}
}
}
/** Android: a consumable (coins, a hint) is consumed, so it can be bought again. iOS needs no flag. */
export const buyCoins = () => BlainkPurchases.purchase('coins_100', { consumable: true });'purchased', withcustomerInfo: Blaink recorded it.'cancelled': the customer closed the sheet.'pending': Ask to Buy, or a payment still to clear. Blaink records it when the store completes it, and the customer info listener hears the answer.- The store's purchase is finished (iOS) or acknowledged (Android) only once Blaink has recorded or refused it. When Blaink can't be reached, it stays open, and the store hands it over again, so nothing bought is lost.
Connect Google Play before you ship
Without a Play service account saved in the console, Blaink refuses every Play purchase with purchase_store_not_configured, and the Android SDK, taking the refusal as final, acknowledges the purchase anyway: the customer is charged, Blaink records nothing, and Play never hands that purchase over again. Save the service account (Google Play: add a service account) before anyone can buy.
Every failure rejects as a PurchasesError; its kind says why.
| kind | What it means |
|---|---|
refused | Blaink refused it; reason is its key (the next table). Final: asking again changes nothing, and the purchase is finished or acknowledged — except in observer mode. |
unavailable | Nothing was decided: Blaink couldn't be reached or didn't answer, the first launch's sign-in took over 30 seconds, or the account was deleted while the call waited. On iOS, StoreKit's own errors — a cancelled App Store sign-in during a restore, say — arrive this way too, in message; on Android, so do Play's, such as an item already owned. A purchase Blaink wasn't told about is handed over again. Safe to try again. |
productNotFound | The store has no product of that ID for this app, or Play no base plan of the name the package gives; productId says which. |
unsupported | The OS is older than purchases need (iOS 15, Android API 23), or the add-on isn't linked. |
notStarted | Android only: a call before start(). |
noActivity | Nowhere to show the sheet or the paywall: no foreground activity on Android (a resumed one, for a paywall), no window on iOS. |
paywallNotFound | From presentPaywall or getPaywall: none is published for the offering, there is no such offering or none is current, or this store sells none of its packages. |
paywallUnreadable | From presentPaywall or getPaywall: a paywall this SDK version can't draw, such as a newer format. Show your own. |
customerBlocked | From presentPaywall or getPaywall: an operator blocked this customer. What they buy unlocks nothing, so show no paywall. |
paywallAlreadyShown | A paywall an earlier presentPaywall started is still loading or on screen. |
unknown | Anything else; message says what — such as an attribute value that is neither a string nor null, for which nothing is sent. |
| Refusal key | From | What it means |
|---|---|---|
purchase_evidence_rejected | Purchase, restore | The store didn't sign the purchase, doesn't know it, or it is another app's. On iOS, every transaction from a StoreKit configuration file is refused this way (step 12). |
purchase_store_not_configured | Purchase, restore | Android: no Play service account is saved in the console, and the purchase is acknowledged anyway (the warning above). iOS: the SDK key the app signed in with isn't an iOS platform's. |
purchase_owned_by_another_customer | Purchase, restore | What it named stays with another customer: the account the device logged out of, or a first owner the project's shared-purchases setting keeps it with (Shared purchases and transfers). |
purchase_app_user_id_invalid | logIn | The ID is empty or over 255 characters, starts or ends with whitespace, or holds a control character. |
purchase_login_token_required | logIn | The project requires signed logins, and no token was sent. |
purchase_login_token_invalid | logIn | The token isn't valid for this ID, this project and this moment (Sign logins). |
purchase_attribute_key_invalid, purchase_attribute_key_reserved, purchase_attribute_value_invalid, purchase_attribute_limit_reached | setAttributes | An attribute broke a rule; nothing was written (step 9). |
reason carries any key that starts with purchase_, so a newer server may send one not listed here: treat it as final too.
Consumables
On Android, pass { consumable: true } for coins, hints and the like: the purchase is consumed, so it can be bought again. iOS needs no flag and ignores it. A consumable unlocks no entitlement, so deliver what it buys when the purchase resolves 'purchased'. On Android a paywall always buys as not consumable, so sell consumables through your own purchase call, not from a paywall; and a consumable whose report failed, reported again on a later launch, is acknowledged rather than consumed and can't be bought again.
Check entitlements
getCustomerInfo() asks Blaink what the customer may use now; isEntitlementActive(info, 'pro') checks one entitlement. entitlements holds every one ever granted, each with isActive, expirationDate, willRenew, hasBillingIssue, periodType, store and isSandbox. Dates are ISO 8601 strings in UTC, and an entitlement for life has a null expirationDate. One granted from the console or by your server reads with store 'unknown' and productIdentifier 'promotional'; its isActive is right all the same.
addCustomerInfoListener hears the answers this device receives, as the native SDK hands them over, and returns the function that stops listening:
- On both: after your purchases, restores,
getCustomerInfo()calls, logins and logouts, afterstart()'s launch report, and — after the account is deleted, here or from the console or your server — the new anonymous customer. - iOS also: each transaction StoreKit hands over while the app runs — a renewal, an Ask to Buy approval, a purchase with the same Apple Account on another device. The first listener added also hears the latest answer at once.
- Android also: a purchase Play completes while the app runs. A listener hears only the answers that come after it is added.
Nothing else reaches it: Blaink pushes nothing to the device. A grant or a block made in the console or by your server, a subscription that lapses — and on Android a renewal, a refund or a purchase on another device — reaches the app only the next time it asks. So read getCustomerInfo() when a component mounts and when the app returns to the foreground, and remove the listener when it unmounts.
import { useEffect, useState } from 'react';
import { AppState } from 'react-native';
import { BlainkPurchases, isEntitlementActive } from 'react-native-blaink-purchases';
/** For a component that mounts after BlainkPurchases.start(). */
export function useIsPro(): boolean {
const [pro, setPro] = useState(false);
useEffect(() => {
const refresh = () => {
BlainkPurchases.getCustomerInfo()
.then((info) => setPro(isEntitlementActive(info, 'pro')))
.catch(() => {}); // unavailable: keep the last answer
};
refresh();
// Every answer this device gets from now on
const stopListening = BlainkPurchases.addCustomerInfoListener((info) => setPro(isEntitlementActive(info, 'pro')));
// A grant, a block or a lapsed subscription reaches the app only when it asks
const foreground = AppState.addEventListener('change', (state) => {
if (state === 'active') refresh();
});
return () => {
stopListening();
foreground.remove();
};
}, []);
return pro;
}Restore purchases
restorePurchases() is your Restore Purchases button. It reports every purchase the store holds for the account — on iOS after asking the App Store to sync, which may ask the customer to sign in; on Android with nothing shown — and resolves with what Blaink decided. Every purchase is tried, and it rejects with the first failure after the rest. Unlike the launch report, a restore can move a purchase from another account, as the project's shared-purchases setting allows (Shared purchases and transfers).
import { BlainkPurchases, isEntitlementActive } from 'react-native-blaink-purchases';
/** Your Restore Purchases button. */
export async function restore(): Promise<boolean> {
try {
return isEntitlementActive(await BlainkPurchases.restorePurchases(), 'pro');
} catch {
return false; // a PurchasesError: the first failure, after every purchase was tried
}
}Log customers in
The customer starts as the device's anonymous one. If your app has its own accounts, call logIn after your sign-in, with your user's ID: their purchases then follow them to every device, and what this device bought before comes with them (what moves, and when: Log in to your account). Blaink remembers the login per device, so don't call it on every launch.
import { BlainkPurchases, PurchasesError } from 'react-native-blaink-purchases';
/**
* After your own sign-in. loginToken: one your backend signed for userId just now, or undefined
* while the project accepts unsigned logins.
*/
export async function didSignIn(userId: string, loginToken?: string): Promise<void> {
try {
const info = await BlainkPurchases.logIn(userId, loginToken);
console.log(info.appUserID ?? userId, 'holds', info.activeEntitlements);
} catch (error) {
if (error instanceof PurchasesError && error.kind === 'refused') {
// purchase_login_token_required, purchase_login_token_invalid or purchase_app_user_id_invalid
console.warn('Login refused:', error.reason);
}
// unavailable: nothing changed; safe to call again
}
}
/** After your own sign-out. */
export async function didSignOut(): Promise<void> {
await BlainkPurchases.logOut().catch(() => undefined); // unavailable: still logged in; safe to call again
}
/** Who Blaink's last answer says the customer is; null while logged out. */
export const currentAppUserID = (): Promise<string | null> => BlainkPurchases.getAppUserID();- The ID is yours: 1 to 255 characters, taken as it is, so case counts, with no whitespace at either end and no control characters; otherwise
purchase_app_user_id_invalid. It is kept on the device unencrypted, so use an opaque ID, not an email address. loginToken(2.3.0) proves the login is your user's: a short-lived token your backend signs for that ID (Sign logins). Fetch a new one right before eachlogIn; the native SDKs never store it. Once the project requires signed logins, a login without one is refused. Until then Blaink trusts the ID it is sent, so use one nobody can guess.getAppUserID()resolves with who Blaink's last answer says the customer is;nullwhile logged out. On Android it rejects asnotStartedbeforestart().logOut()makes the device's anonymous customer the customer again. Purchases stay with the account: until the customer logs in again, restoring them, or buying them again, is refused withpurchase_owned_by_another_customer(Log out).logIn,logOut,setAttributesandsetConsumptionConsentrun one at a time, in the order you call them.
Set attributes
Attributes (2.3.0) are your own facts about the customer — a sign-up source, a plan tier — which the console's audiences can match (Customers).
import { BlainkPurchases, PurchasesError } from 'react-native-blaink-purchases';
export async function recordSignUp(source: string): Promise<void> {
try {
const held = await BlainkPurchases.setAttributes({
signup_source: source, // set
coupon: null, // null or '' removes it
});
console.log('The customer now holds', held); // every attribute, after the write
} catch (error) {
if (error instanceof PurchasesError && error.kind === 'refused') {
console.warn('Nothing written:', error.reason); // purchase_attribute_key_invalid, …
}
// unavailable: nothing written; safe to try again
}
}setAttributessets each key you give and removes each whose value isnullor''; keys you leave out keep their values. It resolves with every attribute the customer holds after the write, so an empty write reads them.- A value that is neither a string nor
null—undefinedincluded — rejects asunknown, with nothing sent. - They are for whoever the device is once earlier logins and logouts have answered: the account, else the anonymous customer. A first login moves the device's attributes to the account.
- A key is a letter, then letters, digits,
_,-or., at most 40 characters, case-sensitive and not starting with$, which is Blaink's. A value is at most 500 characters, with no control characters. A customer holds at most 50. - A write that breaks a rule changes nothing and is refused:
purchase_attribute_key_invalid,purchase_attribute_key_reserved,purchase_attribute_value_invalidorpurchase_attribute_limit_reached.
Refund-request consent
iOS only. When a customer asks Apple for a refund, Apple asks your server what it knows about the purchase and weighs the answer. Blaink answers for you, but only for a customer whose consent your app recorded (2.3.0), as Apple requires, and only once the project turns on Refund requests (Consent and refund requests).
Ask the person in your app first — what is shared, and why — then record their answer, false included. They can change it at any time; only the latest counts. On iOS it resolves with the consent as Blaink keeps it: consented, source ('sdk', or 's2s' when your server recorded it) and recordedAt. On Android it resolves null with nothing sent, as Google Play asks no such questions, though it still rejects as any call does when purchases can't run.
import { Platform } from 'react-native';
import { BlainkPurchases } from 'react-native-blaink-purchases';
/**
* iOS: after you asked the person, in your own words, whether Blaink may tell Apple about their
* purchases when they ask Apple for a refund. Record a "no" too.
*/
export async function recordRefundConsent(agreed: boolean): Promise<void> {
if (Platform.OS !== 'ios') return; // Android resolves null: Google Play has no consumption requests
const consent = await BlainkPurchases.setConsumptionConsent(agreed);
console.log(consent?.consented, consent?.source, consent?.recordedAt); // source: 'sdk', or 's2s' from your server
}Delete an account
Blaink.deleteAccount(), in react-native-blaink (2.3.0), deletes the device's Blaink user and what Blaink keeps about them. For purchases, that means:
- Their customer is deleted from Purchases in every project: the app user ID, grants, attributes, consent and virtual-currency balances. Their purchases and revenue stay, owned by nobody.
- A device logged in to an account is logged out first, and the account is kept. To delete the account too, do it from your server (Delete a customer).
- Nothing is cancelled at the App Store or Google Play: tell the person to cancel any subscription in their store.
- Once it succeeds, the device forgets the app user ID and the last answer and signs in as a new anonymous user, and the customer info listener hears the new customer. A
logIn,logOut,setAttributesmade before the deletion and not yet sent rejects asunavailable, and so does asetConsumptionConsenton iOS (on Android it sends nothing and resolvesnull). - A user deleted another way — from the console, or by your server — is forgotten the same way when the SDK's next request learns of it. Your app hears it only through the customer info listener.
import { Blaink, BlainkError } from 'react-native-blaink';
export async function deleteMyAccount(): Promise<boolean> {
try {
await Blaink.deleteAccount();
return true; // gone: remind the person to cancel any subscription in the App Store or Google Play
} catch (error) {
if (error instanceof BlainkError) return false; // what each kind means: the core SDK guide
throw error;
}
}Its errors and when to try again: the core React Native guide.
Test
Each platform tests as its native SDK does. Sandbox and test purchases unlock entitlements as real ones do, with isSandbox true, stay out of revenue, and put the customer on the console's Customers page.
- iOS: sign a sandbox Apple Account in on the device under Settings → Developer, and buy from a development or TestFlight build.
- Android: add your testers' Google accounts under License testing in the Play Console, create the products there, and install the app from a Play testing track. A test purchase is recorded only once the service account is saved and the product is in Blaink's catalogue.
StoreKit configuration files are local
Xcode signs those transactions with its own certificate, not Apple's, so Blaink refuses them with purchase_evidence_rejected. Use one to work on your paywall's layout; test purchases against the App Store sandbox.
Before release, go through Go live.
Paywalls
The screen that sells an offering. You design and publish it in the console; the SDK draws it natively, with the store’s own prices, and you change it without an app release.
What a paywall is
A small document bound to one offering: a theme (seven colours for light and for dark, a corner radius, four text styles), a tree of components — stacks, text, images, a features list, the packages, purchase and restore buttons, terms and privacy links, a close button, spacers — and its words in each language. It holds plain text and https links only, and never a price: the SDK fills prices in from the store, in the customer’s currency.
Each platform draws it natively: SwiftUI on iOS and macOS (BlainksPaywalls), Jetpack Compose on Android (blaink-paywalls), and those same native screens, presented over your app, from React Native (react-native-blaink-purchases). The paywall buys and restores through the SDK, so its results also reach your customer-info listener. It has a close button only if its document has one; on Android, Back closes it too.
An app is served the latest published version of its offering’s paywall, with only the packages its own store sells, in the device’s language when the paywall has words in it, else in its default language. On iOS that is the device’s first preferred language, even if your app chose another with Blaink’s Localisation. Words the SDK writes itself, such as Free, follow the paywall’s language when it is English, Turkish, German, Spanish, French or Russian, and are English otherwise.
Design and publish it
On the console’s Paywalls page. Developers can read and preview; app managers and owners edit, publish and generate.
What publishing needs
- A packages component with at least one package, and a purchase button.
- Only packages of the paywall’s own offering.
- Words in the default language for every text, written in place or in Localisation.
- Your own links. The templates’ terms and privacy links point at
example.com, and publishing refuses them.
Words and languages
Each text is written in place, in 1 to 20 languages, or names a key of the project’s Localisation. Change a Localisation key’s words, and every published paywall that reads it shows them the next time an app asks: no new version, and none of the publishing checks.
Translate into the app’s other languages writes each text written in place, from the default language, in every language of the app that the paywall lacks, and leaves Localisation keys to Localisation. Nothing is kept until you save the draft. A language is left out when its translation changed a {{…}} variable, ran out of time or came out too long, or when its code has a region, such as pt-br.
Draft it with AI
Generate with AI takes a description of up to 2,000 characters — what it sells, to whom, what to stress — a tone (Friendly, Bold, Minimal, Premium or Playful), one of the app’s languages, up to three brand colours as #RRGGBB, and whether to start from the current draft. Anthropic’s Claude writes the paywall from that and the offering’s packages and products; nothing about your customers is sent, and the description isn’t stored. It links only to addresses already in the draft or in your description.
The result replaces the draft and is never published: review it in the preview, then publish as usual. A project has 20 generations per 24 hours, failed ones included, and a paywall one at a time.
Variables
Put a variable in any text, and the device fills it in from the store’s product. In a package’s title, detail or badge it is that package’s; anywhere else it is the selected package’s, so a purchase button reading Subscribe for {{price_per_period}} follows the customer’s choice.
| Variable | What the device fills in |
|---|---|
{{price}} | The package’s price, as the store formats it: $39.99. |
{{period}} | Its billing period, in the paywall’s language: year. Empty for a one-time purchase. |
{{price_per_period}} | The two together: $39.99/year. The price alone for a one-time purchase. |
{{price_per_month}} | The price spread over the months it covers: $3.33/month. |
{{currency}} | The price’s ISO 4217 code: USD. |
{{product_name}} | The product’s name in the store. |
{{trial_period}} | The free trial’s length, 1 week. Empty when this customer has none. |
{{intro_price}} | The introductory price, or Free for a free trial. Empty when there is none, or the customer isn’t eligible for it. |
{{intro_period}} | How long the introductory price lasts. Empty when there is none, or the customer isn’t eligible for it. |
{{custom.<name>}} | Your app’s value for a variable the paywall declares, else the default the paywall gives it. |
A custom variable is declared in the document’s variables, with the text shown when your app sets none: up to 20, each named by a lower-case letter and then up to 31 lower-case letters, digits or _. Your app passes its values when it shows the paywall (below). A component can also be shown only when some packages are selected, or only when the customer is, or isn’t, eligible for the introductory offer or for a Google Play offer; the preview’s intro offer and store offer choices show each state.
What the SDK reports
For the version it shows, the SDK reports an impression when the paywall appears, a purchase start, with the package, when Buy is tapped, and a close. Reports are queued and never hold the screen up, and Blaink records at most 120 from a device in an hour.
The Paywall conversion page turns them into how often a view led to a new purchase within 24 hours, the last view before it counting, by paywall, version, store and app. It is worked out every six hours, and a day’s figures settle after four days.
Test one paywall against another
Experiments test offerings, and each offering has its own paywall, so an experiment between two offerings with the same products compares their paywalls. An app that shows the current offering’s paywall — no offering named — shows each customer in the experiment their variant’s; an app that names an offering always shows that one. Nothing warns you when a variant’s offering has no published paywall, so publish each before you start. Results are on the Experiments page; each version’s conversion is on Paywall conversion.
Show it in your app
| What | iOS and macOS | Android | React Native |
|---|---|---|---|
| Package | BlainksPaywalls (iOS 15, macOS 12) | com.blainks:blaink-paywalls (API 23) | react-native-blaink-purchases |
| The current offering’s | BlainkPaywallView(), a SwiftUI view | BlainkPaywall() in Compose, or BlainkPaywallContract() through registerForActivityResult | BlainkPurchases.presentPaywall() |
| Another offering’s | BlainkPaywallView(offering: "sale") | BlainkPaywall(offering = "sale") | presentPaywall({ offering: 'sale' }) |
| Custom variables | variables: ["app_name": "My App"] | variables = mapOf("app_name" to "My App") | variables: { app_name: 'My App' } |
| Presented | As you choose: a sheet, a full-screen cover, a push; in UIKit, inside a UIHostingController | Anywhere in your Compose layout; the activity is full screen | Modally, over your app: presentation: 'sheet' or 'fullScreen', honoured on iOS only |
| What happened | onPurchaseCompleted, onRestoreCompleted, onClose, onFailure | The same four callbacks; the activity ends with a PaywallResult: Purchased, Restored, Closed or Failed | The promise resolves purchased, restored or closed once the paywall is gone |
| None published | onFailure with PurchasesError.paywallNotFound | onFailure with PurchasesException.PaywallNotFound, or Failed | Rejects with kind 'paywallNotFound' |
When none is published, show your own screen. Each platform’s full sample is under Add it to your app.
Customers and accounts
Who owns a purchase, and how it follows a person from device to device: the customer every install starts as, your own accounts, and what your team can do to a customer by hand.
Every install starts as a customer
When your app starts Blaink, the SDK signs in once and Blaink makes a user for the install. That user is an anonymous customer: what is bought on the device is theirs until the app logs in. Your server knows them by the device's Blaink user ID, their customerID (Name the customer).
An app with no accounts of its own can stop here. A purchase stays with the store account that paid for it: a new device, or the app installed again, reports what the store holds, and the purchase comes to it as long as no account owns it and Shared purchases allows it (step 5).
Log in to your account
When someone signs in to your app, call logIn with your own ID for their account. Blaink makes a customer for that ID the first time it's used, and maps the device to it: from then on the device buys, restores and reads as the account. Every device that logs in with the same ID shares what the account holds, iOS and Android alike, since a project's apps share one catalogue.
- The ID is taken exactly as you send it, and is case-sensitive: 1–255 characters, with no white space at either end and no control characters, or the login is refused with
purchase_app_user_id_invalid. - It's kept on the device and sent in query strings, so use an opaque ID, never an email address.
What moves when a device logs in:
- From anonymous to an account, what the device holds moves to the account: its purchases, with the store notifications about them, its custom attributes, its virtual-currency balances, access given by hand, the deferred link that brought it, and its place in an offering experiment. Where both hold something, the account keeps its own: an attribute key the account already has keeps the account's value, and an entitlement the account already holds by hand stays the account's grant.
- From one account straight to another, nothing moves: what the first account holds stays with it.
- Logging in again with the same ID changes nothing.
- A login is never a transfer, and sends no webhook event. Nothing moves to or from a blocked customer.
| Step | On the phone | The phone's own customer | Account user-42 |
|---|---|---|---|
| 1 | pro_monthly bought before signing in | Owns pro_monthly | Doesn't exist yet |
| 2 | logIn("user-42") | Holds nothing | Made now. Owns pro_monthly, with the phone's attributes and balances |
| 3 | remove_ads bought while logged in | Holds nothing | Owns pro_monthly and remove_ads |
| 4 | logOut() | Anonymous and empty: unlocks nothing | Keeps all of it |
| 5 | A tablet logs in as user-42 | The tablet's own holds nothing | Unlocks pro_monthly on the tablet too |
| To | iOS 2.4.0 | Android 2.3.0 | React Native 2.3.0 |
|---|---|---|---|
| Log in | BlainkPurchases.shared.logIn(_:loginToken:) | BlainkPurchases.logIn(appUserID, loginToken) | BlainkPurchases.logIn(appUserID, loginToken) |
| Log out | BlainkPurchases.shared.logOut() | BlainkPurchases.logOut() | BlainkPurchases.logOut() |
| Read who's logged in | BlainkPurchases.shared.appUserID | BlainkPurchases.appUserID | BlainkPurchases.getAppUserID() |
| Hear the customer change | customerInfoUpdates | customerInfoUpdates | addCustomerInfoListener |
| Delete the install's data | Blaink.shared.deleteAccount() | Blaink.getInstance().deleteAccount() | Blaink.deleteAccount(), from react-native-blaink |
Each login and logout answers the customer the device now is. The code for each platform is under Add it to your app.
Log out
Call logOut when someone signs out of your app. Everything stays with the account, and the device is its own anonymous customer again, holding nothing: it unlocks nothing the account owns, even though the store on that device still holds the purchase.
- While it's logged out, the device can't take the account's purchases: a purchase or restore of one is refused with
409 purchase_owned_by_another_customer. To use them on this device, log in to the same account. - What the device buys while logged out is its own, and moves to whichever account it next logs in to.
- Android only:
Blaink.logout()on the core SDK is not this. It drops the device's Blaink session, and nothing signs in again until the next launch, so every Blaink and Purchases request fails until then. Sign a person out withBlainkPurchases.logOut().
Sign logins
A plain logIn trusts the ID it's given: anyone who knows or guesses a customer's account ID can log in as them on their own phone and use what they bought. A signed login closes that. Your server, which knows who really signed in, signs a short-lived token for that account ID, the app passes it to logIn beside the ID, and Blaink refuses a login whose token isn't right.
- Make a secret on the console's Purchases page, under Signed logins, and keep it on your server.
- Have your server mint a token after each sign-in, and hand it to the app: the token's rules and samples are under Sign logins in the server section.
- Pass it as
loginToken. iOS 2.4.0, Android 2.3.0 and React Native 2.3.0 send it; an earlier SDK can't. - Once every version of your app in use sends a token, choose Require a signed login. From then on a login without a valid token is refused, and nothing changes on the device. Until then, leave it on Accept unsigned logins: a token that is sent is checked either way.
A refused login reaches the app as the SDK's refused error, with purchase_login_token_required or purchase_login_token_invalid as its reason. Devices that aren't logged in keep buying and restoring as before.
Give access by hand
For a support gesture, a beta or a partner, give a customer an entitlement without a purchase: Give access on their page in the console, with an optional end and a reason for your team, or from your server. Your app reads it like any entitlement.
- It never shortens what the customer bought: Blaink weighs it with their purchases, and the one that gives more access wins.
- A customer holds one grant per entitlement; giving it again replaces the earlier one. Take back ends it, and what they bought from a store stays theirs.
- A device's grant moves to its account when it logs in, stays behind when your team moves the customer's purchases, and goes when the customer is deleted.
Block a customer
For fraud or abuse: Block customer on their page in the console, with a reason for your team that the customer, the audit log and webhooks never see. While they're blocked:
- Nothing they hold reads as active, in your app or to your server, which also reads
blocked: true. - Their purchases are still recorded, and the store keeps charging a subscription they keep. Nothing moves to or from them: not by a login, a restore or your team's Move purchases. A restore that would move a purchase is refused with
409 purchase_owned_by_another_customer. - No paywall is served to them: the SDKs' paywall call fails with their customer-blocked error, so show your own screen.
- They're in no Purchases audience, and lifecycle automations skip them. A push campaign sent from the core push composer still reaches them. Your server can't take their virtual currency.
- Apple's refund requests about them wait unanswered, and one is answered if you lift the block within Apple's 12 hours.
- Webhooks get
customer_blocked, andcustomer_unblockedwhen you choose Unblock.
A device logged in to an account can't be blocked on its own: its purchases are the account's, so block the account.
Delete a customer for a privacy request
An install and an account are two customers, so a person who asks to be erased may need both deleted. Either way, what names them goes and their purchases stay with no owner, so your revenue doesn't change; the full list is under Delete a customer.
- From the app:
deleteAccounton the core SDK, from iOS 2.4.0, Android 2.3.0 and React Native 2.3.0. It deletes the install's Blaink user, with its devices, push tokens, sent notifications and analytics, and its customer in every project it touched, each with acustomer_deletedwebhook event. A device logged in to an account is logged out first, and the account is kept. On success the SDK forgets the user and starts again as a new anonymous customer. - From your server:
DELETEthe customer, naming an account byappUserID(Delete a customer). Devices logged in to it are logged out, and each keeps its own install's user. - From the console: Delete customer on their page. Only the project's owner can, and a device logged in to an account is refused: delete the account.
For a person with an account, delete the account from your server, and call deleteAccount in the app if it's still installed. When the install's user is deleted from the console or your server instead, the app's next request finds it gone: the SDK forgets it and starts as a new anonymous customer, which the app hears through its customer-info updates, with nothing to call.
Nothing is cancelled at the store
A subscription belongs to the person's Apple ID or Google account, and keeps renewing after the deletion, with no owner in Blaink. Tell them to cancel it in their App Store or Google Play settings.
Find a customer in the console
The console's Purchases › Customers page lists everyone who owns a purchase, holds access given by hand or is blocked, 25 to a page, newest first, filtered by status. Find takes exact IDs only: a customer ID, your app's user ID (case-sensitive), a client ID, an App Store transaction or original transaction ID, or a Play order ID or purchase token. A purchase nobody owns yet finds nobody. The customer's page shows what they may use, what they bought, their linked IDs and what the stores said; giving access, moving, blocking and deleting are there. App managers and owners see these pages.
From your server
Ask Blaink what a customer may use, give access by hand, and hear every store event as it happens, so your backend gates content on the same entitlements your apps read.
Authenticate
Every call goes to https://blainks.com/api/v1/purchases/s2s/YOUR_PROJECT_ID/… and is refused unless all three of these hold:
- Your project's ID is in the path. It's the ID in the address of your project's page in the console, and the Signed logins panel on the Purchases page shows it too, as Token audience (aud).
- The
X-API-Keyheader carries the project's API key, from the project's page. It's the key the push API takes. Only the project's owner can give it a new key, and the old one stops working at once. - The call comes from an allowed IP address. The console has no field for these: write to us with your servers' addresses to add them. Each entry is one exact IPv4 or IPv6 address. A range such as
10.0.0.0/8, a host name or a port never matches, and a project with no addresses allows no call at all.
Keep the API key on your server
It reads and changes every customer of your project, and sends pushes to them. Never ship it in an app or a web page.
Every answer is JSON: "error": false and the answer in body, or "error": true with a reason. A Purchases refusal's reason is a key that starts with purchase_; the table at the end of this section lists every one. Dates are ISO 8601 in UTC, and Blaink reads a UUID in either case.
{
"error": true,
"reason": "purchase_customer_unknown"
}| Status | Meaning |
|---|---|
403 | The address isn't allowed. The reason reads IP not allowed: and the address Blaink saw: that's the one to send us. |
404 | No project has that ID, or the API key isn't its key. Blaink doesn't say which. |
Name the customer
Each call says whom it's about in its query string, by one of three names:
| Name | What it is |
|---|---|
appUserID | Your own account ID, exactly as the app logged in with it (Customers and accounts). Case-sensitive. Blaink knows it once a device has logged in with it, or an import named it. |
customerID | Blaink's ID for the customer, a UUID: the customerID webhooks carry, and the console's Customers page shows. For a device that never logged in, it's the device's Blaink user ID, the blainkUserId the SDK hands your app when it registers. |
clientID | The client ID Blaink registered the device under: the SDK's, not yours. Of several users that share one, the one whose device signed in last. |
Which names a call takes, and what it answers for a name Blaink doesn't know, follow two rules:
- The customer check, grant, revoke and virtual-currency transactions take
appUserID,customerIDorclientID. A device that has logged in answers as its account: acustomerIDorclientIDof a logged-in device reads, grants to and spends the account's. - Consent, attributes and delete take only
appUserIDorcustomerID. A client ID is never read here, since its device may be logged in as someone other than the person you mean. AcustomerIDof a device that's logged in is refused with409 purchase_customer_logged_in: name the account byappUserID.
| Call | Unknown appUserID or clientID | Unknown customerID |
|---|---|---|
| Customer check | 404 | 200 with no entitlements |
| Grant, virtual-currency transaction | 404 | 404 purchase_customer_unknown |
| Revoke | 404 | 404 purchase_customer_unknown (a known customer with no such grant is 404 purchase_grant_not_found) |
| Consent, attributes, delete | 404 purchase_customer_unknown for an appUserID; a clientID alone is 400 | 404 purchase_customer_unknown |
A clientID is looked up across Blaink, not only your project: one Blaink knows from another project's app, but not from yours, answers as an unknown customerID does, not as an unknown clientID.
A call that names nobody is 400. Given more than one name, appUserID wins, then customerID. Because a customer check by an unknown customerID answers 200 with nothing in it, check that the ID is right before you read "no entitlements" as "never paid". An appUserID travels in the query string and so reaches web server logs on the way: use an opaque ID, never an email address.
Check a customer's entitlements
A GET of the customer answers what the SDKs read as the customer's info: what they may use now, and why.
# By your own account ID, once a device has logged in with it
curl "https://blainks.com/api/v1/purchases/s2s/YOUR_PROJECT_ID/customer?appUserID=YOUR_ACCOUNT_ID" \
-H "X-API-Key: YOUR_API_KEY"
# By Blaink's ID for the customer (or ?clientID=, the SDK's client ID)
curl "https://blainks.com/api/v1/purchases/s2s/YOUR_PROJECT_ID/customer?customerID=BLAINK_USER_ID" \
-H "X-API-Key: YOUR_API_KEY"{
"error": false,
"reason": "OK",
"body": {
"requestDate": "2027-01-15T08:00:00Z",
"appUserID": "user-42",
"blocked": false,
"activeEntitlements": ["beta", "pro"],
"entitlements": [
{
"identifier": "beta",
"isActive": true,
"willRenew": false,
"hasBillingIssue": false,
"periodType": "normal",
"productIdentifier": "promotional",
"store": "promotional",
"isSandbox": false,
"ownershipType": "purchased",
"originalPurchaseDate": "2027-01-10T09:30:00Z",
"latestPurchaseDate": "2027-01-10T09:30:00Z",
"expirationDate": "2027-02-15T08:00:00Z"
},
{
"identifier": "pro",
"isActive": true,
"willRenew": true,
"hasBillingIssue": false,
"periodType": "normal",
"productIdentifier": "pro_monthly",
"store": "app_store",
"isSandbox": false,
"ownershipType": "purchased",
"originalPurchaseDate": "2026-12-15T08:00:00Z",
"latestPurchaseDate": "2027-01-15T08:00:00Z",
"expirationDate": "2027-02-15T08:00:00Z"
}
],
"virtualCurrencies": [
{ "code": "GEMS", "name": "Gems", "balance": 100 }
]
}
}| Field | Meaning |
|---|---|
activeEntitlements | The entitlements active now. Gate on this, or on each entitlement's isActive. |
entitlements | Every entitlement the customer ever held, inactive ones included, sorted by identifier. |
isActive, expirationDate | Whether it unlocks now, and until when, a grace period included. expirationDate is absent for access for life. |
willRenew, hasBillingIssue | Whether the subscription renews, and whether the store is retrying a failed payment. |
periodType | trial, introductory or normal. |
productIdentifier, store | The product that unlocks it, and where it was bought: app_store or play_store. Access given by hand reads promotional in both. |
isSandbox | Sandbox purchases unlock too, so TestFlight and Play testers can use what they buy. A backend that should only honour real money checks this. |
ownershipType | purchased, or family_shared for an App Store purchase shared through Family Sharing. |
originalPurchaseDate, latestPurchaseDate | The first purchase, and the latest charge or renewal. |
appUserID | Your account ID for the customer. Absent for a device that never logged in. |
blocked | true while an operator has the customer blocked in the console: every entitlement then reads inactive, and activeEntitlements is empty. The SDKs don't read it; your backend can. |
virtualCurrencies | Every currency of the project with the customer's balance, zero for one they never held, sorted by code. A refund can leave a balance below zero. |
requestDate | When Blaink answered. |
A purchase of a product your catalogue doesn't list is recorded but unlocks nothing. Two purchases of one entitlement are weighed: the active one, then the one that ends later, then the later purchase.
| Status | Meaning |
|---|---|
200 | The customer's entitlements; none, for a customer who bought nothing, and for a customerID Blaink doesn't know. |
400 | None of appUserID, customerID and clientID was given. |
403 | The request came from an address your project doesn't allow. |
404 | No such project, the key isn't its key, or no customer has that appUserID or clientID. |
Give access by hand
For a support gesture, a beta or a partner: grant gives the customer an entitlement, for life or until expiresAt, and revoke takes it back. Name the customer as for a check. The body is optional, expiresAt and a reason for your team that the customer never sees; send none for access for life.
- The entitlement needn't be one your catalogue's products unlock, but it must be an identifier: 1–100 ASCII letters, digits,
.,_or-. - A customer holds one grant per entitlement: granting again replaces the earlier one.
- Both calls answer the customer as a check does. A grant reads
"store": "promotional","productIdentifier": "promotional"and"willRenew": false. - Blaink weighs a grant with what the stores sold, so it never shortens a purchase, and revoking touches only the grant.
- A device's grant moves to its account when it logs in, unless the account already holds a grant of that entitlement. It stays where it is when an operator moves the customer's purchases, and goes when the customer is deleted.
- The same is Give access on the customer's page in the console.
# For a month, with a note for your team. Send no body for life.
curl -X POST "https://blainks.com/api/v1/purchases/s2s/YOUR_PROJECT_ID/customer/entitlements/beta/grant?customerID=BLAINK_USER_ID" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"expiresAt": "2027-02-15T08:00:00Z", "reason": "Ticket 42"}'
curl -X POST "https://blainks.com/api/v1/purchases/s2s/YOUR_PROJECT_ID/customer/entitlements/beta/revoke?customerID=BLAINK_USER_ID" \
-H "X-API-Key: YOUR_API_KEY"| Refusal | Meaning |
|---|---|
422 purchase_entitlement_invalid | The entitlement in the path isn't an identifier. |
422 purchase_grant_expiry_invalid | expiresAt has already passed. |
404 purchase_customer_unknown | The customer isn't one of the project's app users, or was deleted meanwhile. |
404 purchase_grant_not_found | Revoke only: the customer holds no grant of that entitlement that hasn't been taken back. |
Receive webhooks
On the console's Purchases › Webhooks page, choose Add a connection: an https URL of your backend, the environments it hears (production and sandbox, or one of them), every kind of event or only those you tick, and On. Every event of the project, from Apple and from Google, is then posted as JSON to each connection that hears it. A project has up to ten connections; app managers and owners set them up.
- The URL is https, up to 2,048 characters, on a public server. Blaink won't post to a private, loopback or internal address in any spelling, to a single-label name or one under
.local,.localhost,.internalor.home.arpa, and checks the address again when it sends. A refused one reads "Not sent" in the console. - The signing secret,
whsec_and 64 hex characters, is made with the connection and shown beside it. It can't be changed. To move to a new one, add a second connection to the same URL, let your backend accept either secret, then remove the old connection once its deliveries read Delivered: meanwhile each event arrives twice, with oneBlaink-Event-ID. Removing a connection drops whatever it was still owed.
{
"apiVersion": 1,
"event": {
"appUserID": "user-42",
"customerID": "6F1C2A4E-1B7D-4C39-9A51-0D3E8B2F7C44",
"environment": "production",
"id": "app_store:7c5e1f02-3d4b-4a6e-8f91-2b0c6d7e9a13",
"originalTransactionID": "2000000100000000",
"productID": "pro_monthly",
"projectID": "3A8D9B1C-5E2F-4071-B6C4-9E0F1A2B3C4D",
"receivedAt": "2027-01-15T08:00:00Z",
"store": "app_store",
"storeType": "DID_RENEW",
"transactionID": "2000000100000123",
"type": "renewal"
}
}| Field | Meaning |
|---|---|
apiVersion | 1. Fields are added under it, so ignore keys you don't know. |
id | The store and its notification's ID, such as app_store:…. Blaink's own events read blaink:test-…, blaink:customer-deleted-…, blaink:customer-blocked-… and blaink:customer-unblocked-…; a transfer <store>:blaink-transfer-…. The same on every retry. |
type | Blaink's name for the event, the same for both stores (table below). |
storeType | The store's own: Apple's notification type and subtype, such as DID_RENEW or SUBSCRIBED/RESUBSCRIBE, or Play's, such as SUBSCRIPTION_RENEWED. Blaink's own events read BLAINK_TEST, BLAINK_TRANSFER, BLAINK_CUSTOMER_DELETED, BLAINK_CUSTOMER_BLOCKED or BLAINK_CUSTOMER_UNBLOCKED. |
store | app_store or play_store, a transfer included (its purchase's store); blaink for the test event and the customer events (customer_deleted, customer_blocked, customer_unblocked). |
environment | production or sandbox; all on customer_deleted, customer_blocked and customer_unblocked, which every connection that hears the type gets, whatever its environments. |
projectID | Your project. |
customerID, appUserID | Whom it's about: Blaink's ID for the customer, and your account ID once they've logged in. Both are absent while nobody owns the purchase yet (below). customer_blocked and customer_unblocked carry customerID alone, even for a customer who has logged in. |
originalTransactionID | Apple's original transaction ID, or the Play purchase token. |
transactionID, productID | The transaction the store's notification carried, and its product; on a transfer, the purchase's latest charge. Absent from the test event and the customer events, and when a notification carries no transaction. |
expirationReason | On expiration only: voluntary, billing_error, price_increase_declined, product_unavailable or unknown. Google Play never says why, so its expirations always read unknown. |
receivedAt | When Blaink received the store's notification. |
transferredFromCustomerID, transferredFromAppUserID | On a transfer alone: the customer the purchase moved from. |
Each post carries three headers:
Blaink-Signature:t=<unix seconds>,v1=<hex>, an HMAC-SHA256 of"<t>.<body>"with the connection's secret (step 6).Blaink-Event-ID: the event'sid, the same on every retry, so handle each event once. Two connections that hear an event each get it, with the same ID.Content-Type: application/json.
Delivery and retries
- An event usually goes out within a minute. Answer any
2xxwithin 10 seconds; Blaink gives up connecting after 5. Anything else, no answer in time, or a redirect, which is never followed, is a failed attempt. - A failed post is tried again after a minute, five, fifteen, then one, three, six and twelve hours: eight attempts in all, about 22 hours, before Blaink gives up. The console lists each connection's latest 20 deliveries as Delivered, Pending or Gave up, and keeps them 30 days.
- An event about a purchase nobody owns yet, such as a store's notification that beats the app's own report, is held five minutes for that report, then sent with whatever Blaink knows.
customerIDandappUserIDare filled in at send time once Blaink knows them. - Retries can bring events out of order. Read the customer's entitlements (step 3) rather than rebuild them from events.
- While a connection is off, new events skip it for good; what it was already owed waits until it's back on.
- A
customer_deletedevent names the customer one last time. Once it's delivered, or given up, Blaink's copy names nobody.
Test events
Send test event beside a connection posts this within a minute, whatever kinds and environments the connection hears, but only while it's on, and at most one every ten seconds. The stores' own test notifications, the one Apple sends when you choose Ask Apple to test the production URL (or the sandbox one) on the Purchases page, and Play's, arrive as "type": "test" with their store and storeType (TEST, TEST_NOTIFICATION).
{
"apiVersion": 1,
"event": {
"environment": "sandbox",
"id": "blaink:test-0b6f3c1e-8a2d-4e57-9c3b-5f1a7d2e4c90",
"projectID": "3A8D9B1C-5E2F-4071-B6C4-9E0F1A2B3C4D",
"receivedAt": "2027-01-15T08:00:00Z",
"store": "blaink",
"storeType": "BLAINK_TEST",
"type": "test"
}
}Check the signature
Check it against the raw body, before parsing it, with the secret's characters as the key, whsec_ included, and refuse a timestamp more than five minutes old:
import crypto from 'node:crypto';
import express from 'express';
function isFromBlaink(rawBody, header, secret, toleranceSeconds = 300) {
const parts = Object.fromEntries((header ?? '').split(',').map((part) => part.split('=')));
const timestamp = Number(parts.t);
if (!Number.isInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) {
return false;
}
const expected = crypto.createHmac('sha256', secret).update(timestamp + '.' + rawBody).digest();
const given = Buffer.from(parts.v1 ?? '', 'hex');
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
}
const app = express();
app.post('/blaink', express.raw({ type: 'application/json' }), (req, res) => {
const body = req.body.toString('utf8');
if (!isFromBlaink(body, req.get('Blaink-Signature'), process.env.BLAINK_WEBHOOK_SECRET)) {
return res.sendStatus(400);
}
const { event } = JSON.parse(body);
// event.id (also the Blaink-Event-ID header) is the same on every retry: handle it once
res.sendStatus(200);
});import Crypto
import Foundation
/// The `Blaink-Signature` header checked against the raw body: `t=<unix seconds>,v1=<hex>`.
func isFromBlaink(body: String, signature: String, secret: String, now: Date = Date()) -> Bool {
var parts: [String: String] = [:]
for part in signature.split(separator: ",") {
let pair = part.split(separator: "=", maxSplits: 1)
if pair.count == 2 { parts[String(pair[0])] = String(pair[1]) }
}
guard let stamp = parts["t"], let seconds = TimeInterval(stamp),
abs(now.timeIntervalSince1970 - seconds) < 300,
let given = parts["v1"].flatMap(hexBytes)
else { return false }
return HMAC<SHA256>.isValidAuthenticationCode(
given, authenticating: Data("\(stamp).\(body)".utf8), using: SymmetricKey(data: Data(secret.utf8))
)
}
private func hexBytes(_ hex: String) -> Data? {
guard hex.count.isMultiple(of: 2) else { return nil }
var bytes: [UInt8] = []
var index = hex.startIndex
while index < hex.endIndex {
let next = hex.index(index, offsetBy: 2)
guard let byte = UInt8(hex[index ..< next], radix: 16) else { return nil }
bytes.append(byte)
index = next
}
return Data(bytes)
}Event types
All 31 values of event.type, and which store sends each. After any of them, ask for the customer's entitlements (step 3): every store event makes Blaink read the purchase again.
event.type | From | When |
|---|---|---|
initial_purchase | Both stores | A subscription bought for the first time. |
resubscription | App Store | A subscription bought again after it had expired. |
renewal | Both stores | A subscription renewed. |
one_time_purchase | Both stores | A consumable, non-consumable or non-renewing product bought. |
renewal_disabled | Both stores | Auto-renew turned off: a cancellation. Access lasts to the period's end. |
renewal_enabled | Both stores | Auto-renew turned back on. |
product_changed | App Store | Moved to another product at once: an upgrade. |
product_change_scheduled | App Store | Moves to another product at the next renewal: a downgrade or crossgrade. |
product_change_canceled | App Store | A scheduled change withdrawn: the subscription renews as it is. |
billing_issue | Both stores | A renewal's payment failed and the store is retrying. Access continues only in a grace period. |
billing_recovery | Both stores | A failed payment went through: access is back. |
account_hold | Both stores | The store still retries, but access is gone: Play's account hold, or Apple's grace period ending. |
expiration | Both stores | A subscription ended. expirationReason says why. |
refund | Both stores | Refunded. On Google Play, a voided purchase. |
refund_reversed | App Store | Apple reversed a refund it had given. |
refund_declined | App Store | Apple declined a refund request. |
revocation | Both stores | Access taken back before it ran out: Family Sharing withdrawn on the App Store, a subscription revoked with a refund on Google Play. |
subscription_extended | Both stores | The renewal date moved later, at no charge. |
offer_redeemed | App Store | A subscription offer redeemed. |
price_increase | App Store | The customer was told of a price increase they must accept, or one that applies on its own. |
price_increase_accepted | Both stores | The customer accepted a price increase. |
paused | Google Play | A subscription paused. |
pause_schedule_changed | Google Play | A subscription's pause schedule changed. |
pending_purchase_canceled | Google Play | A purchase still waiting for payment was cancelled. |
consumption_request | App Store | Apple asks what the customer used, to decide their refund request (step 9). |
test | Both stores, and Blaink | A store's test notification, or the console's Send test event (step 5). |
transfer | Blaink | A purchase moved to this customer from another: by a restore under the project's shared-purchase setting, or by an operator's Move purchases. A login that brings a device's purchases to its account is no transfer, and sends none. |
customer_blocked | Blaink | An operator blocked the customer: nothing they hold reads as active. The reason the operator wrote is never sent. |
customer_unblocked | Blaink | An operator lifted the block. |
customer_deleted | Blaink | A customer deleted for a privacy request, from the console, your backend or the app. customerID and appUserID name them one last time, so your backend can erase what it received. |
unknown | Both stores | A store notification Blaink doesn't name, such as Apple's summary of a renewal extension for many customers, or a type the store added since. storeType is the store's own. |
A connection that hears every kind gets each new type as Blaink adds it. Answer 2xx to a type you don't know and ignore it: it isn't retried, and nothing waits on it.
Sign logins
Without this, anyone who knows a customer's account ID can log in as them and use what they bought. With it, your server signs a short-lived token each time someone signs in to your app, and the app sends it with the login.
- On the console's Purchases page, under Signed logins, choose Make a secret. It's
loginsk_and 64 hex characters, shown once: keep it on your server, never in the app. App managers and owners manage it. - After your own sign-in, mint a JWT signed with HS256, with the secret's characters as the key:
sub: the account ID exactly as the app logs in with it.aud: your project's ID, the panel's Token audience (aud). A list of audiences that includes it works too.iatandexp, both required, at most ten minutes apart. Blaink allows its clock and yours to differ by 60 seconds either way.
- Hand the token to the app, which passes it with the account ID:
logIn(_:loginToken:)from iOS 2.4.0,logIn(appUserID, loginToken)from Android 2.3.0 and React Native 2.3.0 (Customers and accounts). A token that's sent is always checked, whether or not you require one, and again when the device is already logged in as that ID. An empty one counts as none. - Once every version of your app in use sends a token, choose Require a signed login and save. Blaink refuses this until a secret exists. With it on, every login without a token is refused, so every login from an app on an older SDK, or one that passes no token, fails. Devices that aren't logged in keep buying and restoring as before. The console's SDK versions page shows which devices can sign their logins.
import jwt from 'jsonwebtoken';
// On your server, after your own sign-in. The secret is the one the console showed you.
// jsonwebtoken writes iat itself, and expiresIn writes exp.
export function blainkLoginToken(accountID) {
return jwt.sign({ sub: accountID, aud: 'YOUR_PROJECT_ID' }, process.env.BLAINK_LOGIN_SECRET, {
algorithm: 'HS256',
expiresIn: '5m'
});
}
// Hand it to the app, which logs in with the same account ID and this token.import Foundation
import JWTKit
struct BlainkLogin: JWTPayload {
let sub: SubjectClaim
let aud: AudienceClaim
let iat: IssuedAtClaim
let exp: ExpirationClaim
func verify(using algorithm: some JWTAlgorithm) throws {}
}
/// On your server, after your own sign-in. `secret` is the one the console showed you.
func blainkLoginToken(for accountID: String, secret: String) async throws -> String {
let keys = await JWTKeyCollection().add(hmac: HMACKey(from: secret), digestAlgorithm: .sha256)
let now = Date()
return try await keys.sign(BlainkLogin(
sub: SubjectClaim(value: accountID),
aud: AudienceClaim(value: ["YOUR_PROJECT_ID"]),
iat: IssuedAtClaim(value: now),
exp: ExpirationClaim(value: now.addingTimeInterval(300))
))
}| Refusal | Meaning |
|---|---|
422 purchase_app_user_id_invalid | Checked first: the account ID is empty, longer than 255 characters, starts or ends with white space, or holds a control character. |
403 purchase_login_token_required | Your project requires a signed login, and this one carried no token. |
403 purchase_login_token_invalid | The token isn't an HS256 JWT signed with one of your project's secrets, its sub isn't this account ID, its aud doesn't name your project, it lacks iat or exp, they're more than ten minutes apart, or it isn't current within the 60 seconds' allowance. |
- A refused login changes nothing: the device stays as it was. The status is never
401, which the SDKs read as their own session expiring. - Replace the secret keeps the old one working for a day, so your server can switch without failed logins.
- Blaink keeps no list of the tokens it has seen: a token works for any number of logins of its account until it expires, so keep it short-lived. Five minutes is plenty.
- The setting is one per project, for production and sandbox alike.
Consent and refund requests
When a customer asks Apple for a refund, Apple asks your app what it knows: whether the purchase was delivered, whether you showed a sample first, and what you'd prefer. Apple takes an answer for 12 hours after it asks. Blaink can answer for you, App Store purchases only, and only for customers who agreed to it.
Record each customer's answer
Ask them in your own words, and record their answer, yes or no, each time it changes. Only the latest counts, and a customer with none recorded counts as no; one recorded within the 12 hours is still in time.
- From the app:
setConsumptionConsent(consented:)from iOS 2.4.0,setConsumptionConsent(consented)from React Native 2.3.0. The Android SDK has none, and React Native's resolvesnullon Android and records nothing: record it from your server. - From your server: the call below, naming the customer by the second rule (step 2). It answers what Blaink now keeps, with
"source": "s2s", or"sdk"for the app's. Your backend's changes are noted in the console's audit log, under the project's API key.
# Send false when they decline or change their mind.
curl -X POST "https://blainks.com/api/v1/purchases/s2s/YOUR_PROJECT_ID/customer/consumption-consent?appUserID=YOUR_ACCOUNT_ID" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"consented": true}'{
"error": false,
"reason": "OK",
"body": {
"consented": true,
"source": "s2s",
"recordedAt": "2027-01-15T08:00:00Z"
}
}Turn answering on
Under Refund requests on the console's Purchases page:
- Make the two statements. Delivery: that your app unlocks purchases only through Blaink's entitlements, which an app in observer mode can't truthfully say. And whether the app shows a sample, a trial or what it does before purchase.
- Choose a Refund preference: no preference, prefer that Apple declines, a full refund, or a prorated one. A prorated refund is asked for auto-renewable subscriptions only; for any other product, no preference is sent.
- Turn Answering Apple on. It needs both statements.
Refund rules, below those settings, pick the preference per request. They're tried in order, and the first whose every condition holds decides; when none does, the project's preference goes. A rule can test the product, the entitlements it unlocks, the environment, days paying, total spent, earlier refund requests and refunds, the share of the period used, and how soon after the charge Apple asked, each at most once. A project has up to 50 rules. A dry run on a recent request shows what today's rules pick and sends nothing. Total spent is in the project's reporting currency, and Google Play purchases add nothing to it: Blaink records no price for them.
What Blaink tells Apple
- That the purchase was delivered, only when Blaink's own records hold the charge under the customer and it unlocked an entitlement or credited a virtual currency. A free trial counts as a sample. Blaink never says how much was used.
- Nothing at all while answering is off, for a customer with no consent, or for a purchase that changed hands since Apple asked. A blocked customer's request waits, and is answered if the block is lifted within the 12 hours. A device that logs in to an account from anonymous isn't a change of hands.
- The customer's page in the console shows their latest answer, and the latest 100 refund requests Apple sent about them, each with what Blaink did and the rule that picked its preference. Each request is a
consumption_requestwebhook event too.
Spend and credit virtual currency
Add coins, gems or credits on the console's Purchases › Virtual currencies page: a code of 1–10 ASCII letters, digits or _, case-sensitive, and a name. Then say how much of each a product grants when you edit it in the catalogue, from 1 to 1,000,000 per charge, in up to ten currencies.
- What credits: every verified paid charge, once, however often the store or the app reports it: a consumable's coins, or each paid renewal of a subscription. A free trial or another free period credits nothing, and neither does a family member's copy under Family Sharing: the organiser's own charge credits the organiser. A free consumable from an offer code credits like a bought one.
- Only charges made since a product began granting a currency credit it, so history Blaink reads again, or imports, never pays twice; a changed amount counts for every charge not credited yet.
- A refund takes the credit back: all of it, or for a prorated refund its share, rounded up. A refund can leave a balance below zero, a debt the customer can't spend. Apple reversing a refund gives the credit back.
- Sandbox purchases credit nothing until you switch Sandbox purchases on, on the same page, while your team tests. App Review buys with sandbox accounts too: switch it on while a build is in review and off once it's through, or the reviewer's coin purchase changes no balance, a common reason for a Guideline 2.1 rejection. While it's on, a TestFlight tester can buy currency for nothing that their App Store build then spends, since both builds are the same customer.
- Balances come with every answer about the customer, as
virtualCurrencies. A device's balances move to its account when it logs in. The SDKs have no currency calls: your backend spends them.
A transaction names the customer by the first rule (step 2), and a device that has logged in spends its account's balance.
adjustmentstakes whole amounts by currency code: negative spends, positive credits, such as a reward or a referral bonus. Each is non-zero and at most 1,000,000,000 either way, in up to ten currencies at once: every one of them changes, or none does.reference, optional, is yours, up to 255 characters, and shows in the customer's ledger.- The
Idempotency-Keyheader is required: 1–255 visible ASCII characters, letters, digits and punctuation, no spaces. A key is unique across your project and never expires. Send the same key when you retry: the same request again changes nothing and answers"replayed": true. A different request under a used key is refused. - A spend that would take a balance below zero is refused, and nothing changes.
- While an operator has the customer blocked, a transaction that takes any currency away is refused; a credit still applies. Their balances still read as they stand, beside
blocked: true. - Each change is in the customer's ledger on their console page, with your
reference. Your backend's changes aren't in the audit log, since the ledger records them; an operator's adjustment by hand is. - A currency can't be removed while a product grants it or any ledger entry names it.
# Negative spends, positive credits. One key per spend: send it again on a retry, never a new one.
curl -X POST "https://blainks.com/api/v1/purchases/s2s/YOUR_PROJECT_ID/customer/virtual-currencies/transactions?appUserID=YOUR_ACCOUNT_ID" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Idempotency-Key: order-42-gems" \
-H "Content-Type: application/json" \
-d '{"adjustments": {"GEMS": -30}, "reference": "order-42"}'{
"error": false,
"reason": "OK",
"body": {
"replayed": false,
"virtualCurrencies": [
{ "code": "GEMS", "name": "Gems", "balance": 70 }
]
}
}| Refusal | Meaning |
|---|---|
422 purchase_idempotency_key_invalid | No Idempotency-Key, or not 1–255 visible ASCII characters. |
422 purchase_idempotency_key_reused | The key was used for a different request. |
422 purchase_virtual_currency_unknown | The project has no currency of that code. |
422 purchase_virtual_currency_adjustment_invalid | A currency code that isn't well formed, no adjustments, more than ten, an amount of zero or beyond 1,000,000,000 either way, a reference over 255 characters, or a balance that would overflow. |
409 purchase_virtual_currency_insufficient | The spend would take a balance below zero. |
409 purchase_customer_blocked | The customer is blocked, and the transaction takes currency away. |
404 purchase_customer_unknown | The customer isn't one of the project's app users. |
Set custom attributes
Tell Blaink what you know about a customer, such as a plan tier, a favourite genre or a company size, and use it in the console's Audiences, beside what they bought and what their devices did; today, audiences target offering experiments. Each value is text. A write sets the keys it names, leaves the others as they are, and answers every attribute the customer then holds.
- From the app:
setAttributes, from iOS 2.4.0, Android 2.3.0 and React Native 2.3.0, with the same rules. On a logged-in device it writes the account's. - From your server: the call below, naming the customer by the second rule (step 2). A customer the project doesn't know, an
appUserIDno device has logged in as yet among them, is404 purchase_customer_unknown. - Keys are a letter, then letters, digits,
_,-or., at most 40 in all, and case-sensitive. Keys that start with$are reserved for Blaink. - Values are at most 500 characters, with no control characters.
nullor an empty string clears a key. - Limits: at most 50 keys per customer, counted after the write, so clearing one makes room in the same call, and at most 50 named in one write. A request body is at most 128 KB.
- A refusal writes nothing. Each is a
422:purchase_attribute_key_invalid,purchase_attribute_key_reserved,purchase_attribute_value_invalidorpurchase_attribute_limit_reached. - When a device logs in, its attributes move to the account. On a key both hold, the account's value stays; past 50 keys, the device's most recently set move first, and the rest are dropped. A transfer of a purchase moves none, and deleting the customer erases them.
- Your backend's changes are noted in the console's audit log, under the project's API key, by key only, never the value. The customer's page shows the attributes they hold.
# null, or an empty string, clears a key; keys you leave out keep their values.
curl -X POST "https://blainks.com/api/v1/purchases/s2s/YOUR_PROJECT_ID/customer/attributes?appUserID=YOUR_ACCOUNT_ID" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"attributes": {"plan_tier": "gold", "favorite_genre": null}}'{
"error": false,
"reason": "OK",
"body": {
"attributes": {
"company_size": "11-50",
"plan_tier": "gold"
}
}
}Delete a customer
When a user of your app deletes their account, or asks you to erase their data, pass it on. Blaink deletes the customer by anonymizing them: what names them goes, and their purchases stay with no owner, so your revenue doesn't change. Name the customer by the second rule (step 2): to delete an account, name it by appUserID. The app can also delete its own install's data with deleteAccount (Customers and accounts).
curl -X DELETE "https://blainks.com/api/v1/purchases/s2s/YOUR_PROJECT_ID/customer?appUserID=YOUR_ACCOUNT_ID" \
-H "X-API-Key: YOUR_API_KEY"{
"error": false,
"reason": "OK",
"body": {
"customerID": "6F1C2A4E-1B7D-4C39-9A51-0D3E8B2F7C44",
"unlinkedPurchases": [
{ "store": "app_store", "originalTransactionID": "2000000100000000" }
],
"records": [
{ "record": "app_user_id", "count": 1, "isRemoved": true },
{ "record": "device_link", "count": 2, "isRemoved": true },
{ "record": "grant", "count": 0, "isRemoved": true },
{ "record": "consent_record", "count": 1, "isRemoved": true },
{ "record": "custom_attribute", "count": 3, "isRemoved": true },
{ "record": "event", "count": 14, "isRemoved": false },
{ "record": "refund_request", "count": 0, "isRemoved": false },
{ "record": "webhook_delivery", "count": 14, "isRemoved": false },
{ "record": "import_row", "count": 0, "isRemoved": false },
{ "record": "currency_entry", "count": 4, "isRemoved": false },
{ "record": "currency_balance", "count": 1, "isRemoved": true },
{ "record": "currency_move", "count": 1, "isRemoved": false },
{ "record": "app_user", "count": 0, "isRemoved": true },
{ "record": "app_user_device", "count": 0, "isRemoved": true },
{ "record": "push_notification", "count": 0, "isRemoved": true },
{ "record": "lifecycle_push", "count": 1, "isRemoved": true },
{ "record": "paywall_event", "count": 6, "isRemoved": false },
{ "record": "customer_note", "count": 0, "isRemoved": true },
{ "record": "customer_block", "count": 0, "isRemoved": true },
{ "record": "link_attribution", "count": 1, "isRemoved": true },
{ "record": "experiment_enrollment", "count": 1, "isRemoved": true }
]
}
}The answer gives Blaink's ID for the customer, unlinkedPurchases, each purchase now left with no owner by its store's ID, and records: every kind of record that names a customer, always all of them and in this order, with how many of theirs it held and whether those went ("isRemoved": true) or stay naming nobody.
record | Deleted or kept | What it is |
|---|---|---|
app_user_id | Deleted | Your account ID for them. |
device_link | Deleted | A device logged in as them, or the account they were logged in as. Those devices are logged out. |
grant | Deleted | Access given by hand, taken back or not. |
consent_record | Deleted | Their consent for refund requests, and each change of it. |
custom_attribute | Deleted | Their custom attributes, and those of devices logged in as them. |
event | Kept, naming nobody | Store notifications about their purchases. |
refund_request | Kept, naming nobody | Apple's refund requests about them; one still waiting is closed. |
webhook_delivery | Kept, naming nobody | Webhook deliveries kept for the console whose event named them. |
import_row | Kept, naming nobody | A RevenueCat import's row that named them, which can't name its purchase's owner again. |
currency_entry | Kept, naming nobody | Their virtual-currency ledger, without the references and reasons typed into it, so each currency's totals stay right. |
currency_balance | Deleted | Their balances. |
currency_move | Kept, naming nobody | Balances a login or an operator moved into or out of them. |
app_user | Deleted | For a customer who never logged in: the device's own Blaink user, when no device of theirs is left in another project. |
app_user_device | Deleted | That user's devices on the project, with their push tokens, analytics and Live Activity tokens. |
push_notification | Deleted | Pushes the project sent that user. |
lifecycle_push | Deleted | Pushes an automation owed or sent them. A moment of theirs is never pushed afterwards. |
paywall_event | Kept, naming nobody | Paywalls they saw, closed or bought from, so conversion still counts them. |
customer_note | Deleted | Your team's notes on them. |
customer_block | Deleted | Blocks on them, with their reasons. Devices logged in as them keep their own blocks, without the reason. |
link_attribution | Deleted | The deferred link that brought them, so their purchases count for no link any more. |
experiment_enrollment | Deleted | Their place in an offering experiment, or a logged-in device's. |
- A device's ID that's logged in is refused with
409 purchase_customer_logged_in: delete the account. A call that names nobody is400. - Once deleted, there is nobody of that name: asking again is
404 purchase_customer_unknown, which a retry can treat as done. - A customer who never logged in is the device's own Blaink user, which goes too, on this project. If the app is still installed, its next request finds it deleted: iOS 2.4.0, Android 2.3.0 and React Native 2.3.0 then forget it and start again as a new anonymous customer, which the app hears through its customer-info updates.
- Deleting an account logs out the devices logged in to it; each keeps its own Blaink user, which is the install, not the person.
- A store subscription isn't cancelled: it belongs to the person's Apple ID or Google account, so tell them to cancel it there. Its renewals keep reaching your charts with no owner. If the app on one of their devices reports it again, that device's customer has it, as with any purchase nobody owns; a store notification never gives it back on its own, and neither does an import.
- Every connection that hears
customer_deletedgets one (step 7), so your backend can erase what it received. - Deletions are noted in the console's audit log under the project's API key, by Blaink's ID for the customer alone. Afterwards, Blaink still holds that ID in:
- the audit log's entry;
- the account token your app attached when buying, which the store's charges carry, and with them each Apple notification Blaink forwarded for you, kept for 30 days once passed on or given up;
- the
customer_deleteddelivery, until it's delivered or given up, then kept for 30 days naming nobody; - a push your backend scheduled for that user, which keeps their ID and, sent later, finds no device;
- another project where the same Blaink user still has a device;
- files already sent to an export bucket, which Blaink can't reach.
Every refusal
What the server-to-server routes refuse with, and where. A 4xx without a purchase_ key is about the request itself: no customer named or a body that can't be read (400), an address not allowed (403), a project, key, appUserID or clientID Blaink doesn't know (404), a body sent without Content-Type: application/json (415), or a project ID that isn't a UUID (422).
| Status | reason | Calls | Meaning |
|---|---|---|---|
404 | purchase_customer_unknown | Grant, revoke, currency, consent, attributes, delete | The customer isn't one of the project's app users, or was deleted meanwhile. |
409 | purchase_customer_logged_in | Consent, attributes, delete | The customerID is a device that's logged in: name its account by appUserID. |
422 | purchase_entitlement_invalid | Grant | The entitlement isn't an identifier. |
422 | purchase_grant_expiry_invalid | Grant | The grant's end has passed. |
404 | purchase_grant_not_found | Revoke | No grant of that entitlement to take back. |
422 | purchase_idempotency_key_invalid | Currency | No Idempotency-Key, or not 1–255 visible ASCII characters. |
422 | purchase_idempotency_key_reused | Currency | The key was used for a different request. |
422 | purchase_virtual_currency_unknown | Currency | No currency of that code. |
422 | purchase_virtual_currency_adjustment_invalid | Currency | A malformed currency code, none, more than ten, zero, beyond 1,000,000,000 either way, a reference over 255 characters, or an overflow. |
409 | purchase_virtual_currency_insufficient | Currency | The spend would take a balance below zero. |
409 | purchase_customer_blocked | Currency | The customer is blocked, and the transaction takes currency away. |
422 | purchase_attribute_key_invalid | Attributes | Not a letter followed by letters, digits, _, - or ., at most 40. |
422 | purchase_attribute_key_reserved | Attributes | Starts with $. |
422 | purchase_attribute_value_invalid | Attributes | Over 500 characters, or holds a control character. |
422 | purchase_attribute_limit_reached | Attributes | More than 50 keys after the write, or more than 50 named in it. |
The app's own logins add 422 purchase_app_user_id_invalid, 403 purchase_login_token_required and 403 purchase_login_token_invalid (step 8).
Run it from the console
Everything under Purchases in the console’s side menu: what each page is for, and who on your team is offered it.
The pages
Roles run owner, app manager, developer, viewer; a viewer is offered no Purchases page. The side menu offers each role only the pages it may use, and every page checks the role again on the server; on the Purchases page, a panel your role can’t use isn’t shown.
| Side menu | What you do there | Who is offered it |
|---|---|---|
| Purchases | The catalogue (Products), the Overview, App Store keys with each app’s notification URL, App Store Connect keys, Google Play service accounts, Shared purchases, Signed logins, and Refund requests with their rules. | Developers read the products; everything else, and changing products, app managers and owners |
| Offerings | Offerings and their packages, and which offering is current. | Developers read; app managers and owners change |
| Virtual currencies | Currencies, the products that grant them, and whether sandbox purchases credit them. | Developers read; app managers and owners change |
| Paywalls | Each offering’s paywall: design, preview, publish, restore a version, translate, draft with AI. | Developers read and preview; app managers and owners change and publish |
| Customers | Find a customer by an exact ID; see what they may use and why; give access, move purchases, block, add notes, adjust balances, delete. | App managers and owners; deleting, owners only |
| Audiences | Rules that group customers, with a preview of who is in each. | App managers and owners |
| Experiments | Offerings tested against each other, and the results. | App managers and owners |
| Charts | MRR, revenue, refunds, subscriptions, trials, churn and conversion over time; the reporting currency. | App managers and owners |
| Cohorts | Customers by the week or month of their first purchase: who kept paying, and what they were worth. | App managers and owners |
| Paywall conversion | How often each paywall, and each version of it, turned a view into a purchase. | App managers and owners |
| Link revenue | What the customers each deferred link brought went on to buy. | App managers and owners |
| Transactions | Every charge, renewal, refund, revocation and upgrade credit, the newest first. | App managers and owners |
| Webhooks | Connections to your backend, their deliveries and test events; forwarding Apple’s notifications to another service. | App managers and owners |
| Exports | Daily or weekly CSV files sent to your own Amazon S3 or Google Cloud Storage bucket. | App managers and owners |
| Automations | Pushes Blaink sends on its own: at a billing issue, before a trial ends, after a subscription lapses. | App managers and owners |
| Retention messages | What Apple shows a subscriber who taps Cancel Subscription. | App managers and owners |
| Audit log | Who changed what in the project’s Purchases setup and customers, and when. | App managers and owners |
| Import | Purchases brought over from another provider’s export, checked with the store before anything is written. | App managers and owners |
| App Store products | An iOS app’s products read from App Store Connect, and the ones you choose added to the catalogue. | App managers and owners |
| App Store prices | An app’s auto-renewable subscription prices by territory, and changes you preview and schedule. | App managers and owners |
| SDK versions | Which SDK versions your apps run, and which Purchases features each version can use. | Developers and up |
Outside Purchases, setting up needs Platforms (each app’s bundle ID or package name; developers and up), Test devices (automation tests reach enrolled devices only), and your project’s own page, which shows the API key your server sends; only an owner replaces it, and the old key stops working at once. Moving from another provider? The Import page and Apple notification forwarding are explained in the migration section.
Overview and Charts
The Overview, on the Purchases page, is live: active subscriptions, free trials, new purchases, refunds, lapsed subscriptions, revenue, refunded and upgrade credits, each active now or over the last 30 × 24 hours, for production unless you choose Show sandbox. Its revenue is net of refunds and upgrade credits. It warns when store notifications have no customer yet, which means the SDK isn’t reporting purchases in that app.
Charts are worked out every six hours, in whole UTC days, one environment at a time: MRR, revenue (charged less upgrade credits, refunds shown apart), refunds, active subscriptions and trials, churn, and trial conversion. Choose 30, 90 or 365 days or your own range of up to 1,100 days, by day, week or month; break a range down by app, store, product or country (the top 20 and everything else, over the last 400 days); or compare it with the period before. Because the two count differently, the Overview and Charts can disagree near the ends of a range: read today on the Overview, and trends on Charts.
Money is what the store charged, before its fees, added up in the project’s reporting currency — US dollars until someone changes it with Use on Charts, which changes it for everyone — each amount at the European Central Bank’s rate for its day. Google Play purchases carry no price yet: they count as subscribers and trials, and add no revenue (Known limits).
Customers
25 to a page, the most recently recorded first, filtered by status: Active, Trial, Billing issue, Refunded or revoked, Expired, Never paid or Blocked. Find takes exact IDs only: a customer ID, your app’s user ID (case-sensitive), a client ID, an App Store transaction or original transaction ID, or a Play order ID or purchase token. A customer’s page shows their entitlements, what was given by hand, balances, purchases, linked IDs, custom attributes (read-only, with values that look like email addresses masked), refund requests and consent, and the store’s notifications about them. From it:
- Give access: an entitlement, an optional end and an optional reason.
- Move purchases to another customer, found by an exact customer, app user or client ID. Purchases and balances move; grants and past notifications stay.
- Block customer, with a reason for your team: nothing they hold reads as active, in your app or to your backend, though their purchases are still recorded. The reason never reaches the audit log or webhooks.
- Adjust balance: add or take away whole units of a currency, with a reason, never below zero.
- Delete customer, for a privacy request; owners only. A device logged in to an account can’t be deleted: delete the account.
Webhooks
Add a connection, up to ten: an https address of your backend, the environments it hears (production and sandbox, production only, or sandbox only), every kind of event or the ones you tick, and On. The page shows each connection’s signing secret and its latest deliveries, as Delivered, Pending or Gave up. Send test event reaches it within a minute. While a connection is off, new events skip it for good.
A secret can’t be replaced. To rotate one, add a second connection to the same address, move your backend to its secret, then remove the first; meanwhile each event arrives twice with the same Blaink-Event-ID. Removing a connection drops what it wasn’t yet sent. The payload, the signature and every event type are under From your server.
Audit log
Read-only, 50 entries a page: who changed what, and when — an operator, by a masked email, or your backend, by the project’s API key — across grants, blocks, keys, the catalogue, offerings, paywalls, automations and the project’s settings. Entries can’t be changed or removed, and are kept with no time limit. They never hold a secret, a full URL or what an operator typed freely, such as a block’s reason. An entry is written just after its change, so one can, rarely, be missing.
Automations
Three pushes Blaink sends on its own, each off until you turn it on:
- Billing issue: 0 to 72 hours after a renewal’s payment fails; at once by default.
- Trial ending: 1 to 168 hours before a free trial ends; 24 by default.
- Win-back: 1 to 720 hours after a subscription expires; 72 by default.
Edit sets the words in up to 30 languages with a fallback, an optional deep link, the timing and the environments, production only by default. {{app_name}} works in all three; {{days_left}} and {{hours_left}} in trial ending. To turn one on, choose Send a test, enter a customer ID or a device’s app user ID, choose Preview for them and then Send test, which reaches your enrolled test devices only; then Turn on. Saving new words turns it off again until they are previewed and tested.
An automation acts only on what happens after it was turned on, and sends a customer at most one push of its kind a day. Billing issues and expiries come from the stores’ notifications, so set those up first (Connect the stores).
Retention messages
App Store only. When a subscriber taps Cancel Subscription, Apple can first show them a message of yours; Blaink keeps your messages at Apple, answers Apple’s real-time request with the right one, and records what the subscriber did next: kept, cancelled or switched. Apple grants real-time Retention Messaging to each developer account on request, and each app needs its In-App Purchase key and Apple ID on the Purchases page.
Under Settings, turn real-time answers on and choose the environments. Give Apple’s access form the app’s URL from this page. Once Apple grants access: Give Apple the sandbox URL, Start performance test with an active sandbox subscription’s original transaction ID, Check result, then Give Apple the production URL. New message takes the app, a subscription, an App Store locale, a kind — Text, or Switch plan to suggest another subscription — a header of up to 66 characters and a body of up to 144. Every save goes to Apple’s review, and the approved words show until the new ones pass.
Refund requests
Apple only; Google Play asks nothing. When a customer asks Apple for a refund, Apple asks your app what it knows. Blaink can answer for you, only for customers whose consent your app or backend recorded (From your server), and never says how much was used. Under Refund requests on the Purchases page, make the two statements — whether your app unlocks purchases only through Blaink’s entitlements, and whether it shows a sample, a trial or what it does before purchase — choose a refund preference (none, decline, full, or prorated for auto-renewable subscriptions), then turn on Answering Apple.
Refund rules, below the settings, pick the preference for each request: the first rule whose every condition holds decides, otherwise the project’s preference applies. A Dry run sends nothing. An app in observer mode can’t truthfully say it unlocks purchases only through Blaink.
Virtual currencies
Add currency with a code of 1 to 10 letters, digits or _, which can’t change later, and a name. How much a product grants is set in its product dialog on the Purchases page. The Sandbox purchases switch chooses whether sandbox purchases credit currency: on while your team tests and while a build is in App Review, off otherwise (Test and go live). A currency can’t be removed while a product grants it or any customer’s ledger names it. Each customer’s balances are on their page, where Adjust balance changes one; your backend does the same over the server API.
Imports
App Store products reads up to 2,000 of an iOS app’s products from App Store Connect, with a catalogue key (step 5 of Connect the stores). Choose Read from App Store Connect, tick the products to add, give each its entitlements — and its access days, for a non-renewing subscription — then Add … to the catalogue. Kinds come over; prices, offers and localisations don’t, and nothing changes in App Store Connect. Import brings purchases over from another provider’s export: see the migration section.
Exports
Add destination, up to five: Amazon S3 or Google Cloud Storage; the bucket, and for S3 its region; a folder; credentials — for Google Cloud Storage a service account’s JSON key with Storage Object User on the bucket, for S3 an access key allowed s3:PutObject; the datasets (transactions, customers, subscription_events, daily_figures); daily or weekly; and the first day to send. Saving writes blaink-connection-check.txt to the bucket first, and saves nothing if that fails.
Files land at <folder><dataset>/dt=YYYY-MM-DD/part-NNNN.csv, with money in thousandths of a unit, dates in UTC, and customers by their Blaink ID only. A day is sent once it has ended. After a failure Blaink waits six hours before trying again; saving the destination lifts the wait.
Moving from RevenueCat
Run Blaink beside RevenueCat, compare the two, bring RevenueCat's App Store history over, then switch in one release. Until you switch, RevenueCat keeps running your purchases as it does today.
Connect the stores beside RevenueCat
Set up each store as Connect the stores says: the App Store's In-App Purchase key, the Google Play service account, and each app's notification URL. Both stores then tell Blaink and RevenueCat alike:
- Google Play sends Real-time Developer Notifications to one Pub/Sub topic, and every subscription to that topic gets every message. Add a second push subscription to that topic, beside RevenueCat's, with Blaink's Real-time Developer Notifications push URL as its endpoint. RevenueCat's subscription stays as it is.
- The App Store takes one notification URL per environment, so one service has to pass the notifications on. Enter Blaink's App Store Server Notifications URL in App Store Connect for both Production and Sandbox. Then, on the console's Purchases › Webhooks page, choose Forward on the iOS app's row and paste RevenueCat's App Store Server Notifications URL. Blaink passes each notification on exactly as Apple sent it, once it has accepted it, and retries a failed one like a webhook, for about 22 hours. One forwarding URL serves both environments.
Or keep RevenueCat's URL in App Store Connect for both Production and Sandbox, and let RevenueCat pass the notifications on. In RevenueCat, on the App Store app's settings, paste Blaink's App Store Server Notifications URL as the Apple Server Notification Forwarding URL. RevenueCat forwards every notification it receives, including those about purchases it doesn't track, so Blaink hears each one as it happens while RevenueCat stays first for the customers it already has. Leave Forward on Blaink's Webhooks page off, or each notification goes back and forth between the two. If a forward is lost, Blaink's six-hourly read of Apple's notification history recovers it, and its webhooks still go out.
Or leave RevenueCat's URL without forwarding, and move it when you switch. Blaink still verifies everything the app reports, and with the In-App Purchase key it reads Apple's notification history every six hours, two days back, so it learns of renewals and refunds hours late rather than at once.
Forwarding passes on only what reaches Blaink live
A notification Blaink recovers from Apple's history later, after an outage, is never forwarded. Forwarding is for the App Store only, and carries no Blaink signature.
List your products
Blaink unlocks only what its own catalogue lists: a purchase of a product it doesn't list is recorded, but unlocks nothing until you add it. Give each product the entitlements RevenueCat gives it, under the same names, and your app's checks keep working.
- App Store products: save an App Store Connect key for the Catalogue under App Store Connect on the Purchases page. On App Store products in the side menu, choose the iOS app and Read from App Store Connect, which reads up to 2,000 products. Tick the ones to add, give each its entitlements, and access days for a non-renewing subscription, then choose Add N to the catalogue. The kind comes from App Store Connect; prices, offers, localisations and subscription groups aren't imported, and nothing changes in App Store Connect.
- Google Play products: choose Add product under Products on the Purchases page, with the product ID exactly as the Play Console names it.
- Offerings: make them on the Offerings page. Offering and package IDs may contain
$, so RevenueCat's$rc_monthlyand$rc_annualcarry over unchanged.
Ship Blaink in observer mode
Add Blaink to your app beside RevenueCat (Add it to your app), started in observer mode. Blaink then records every purchase the store holds, and finishes, acknowledges or consumes none of them, so RevenueCat keeps doing that as it does today.
| Platform | Start Blaink Purchases in observer mode |
|---|---|
| iOS and macOS | BlainkPurchases.shared.start(completion: .observer) |
| Android | BlainkPurchases.start(context, BlainkPurchases.Completion.OBSERVER) |
| React Native | BlainkPurchases.start({ observer: true }) |
- Log in to Blaink with the same ID you give RevenueCat, wherever your app logs in to it, so both name each customer alike, and the import in step 5 lands under the same customers.
- Keep buying through RevenueCat while Blaink observes. On Android this matters most: in observer mode Blaink acknowledges nothing, so a purchase made with
BlainkPurchases.purchaseis acknowledged by nobody unless RevenueCat does it, and Google Play refunds a purchase left unacknowledged for three days. - A store notification about a purchase RevenueCat made carries no account Blaink knows, so Blaink logs it with no customer until the app reports that purchase, usually seconds later. Webhook events about it wait five minutes for that report. The Overview on the Purchases page warns while store notifications have no customer: if the count stays high, check that Blaink runs in that app.
- Leave Answering Apple under Refund requests off: while RevenueCat unlocks your purchases, you can't truthfully say your app unlocks them only through Blaink.
Compare
- On the console's Customers page, Find a customer by your app user ID, exactly and case-sensitive, by a client ID or by a store transaction ID, and compare their Entitlements with what RevenueCat says for the same customer. The list shows everyone who owns a purchase, holds access given by hand or is blocked.
- Ask Blaink's server-to-server API the questions your backend asks RevenueCat today (Check a customer's entitlements), and point a test endpoint at Blaink's webhooks (Receive webhooks).
- Compare Google Play by counts, not money: Blaink records no price for a Play purchase, so Play sales count as subscribers and trials but add nothing to revenue (Known limits). Revenue elsewhere is what the stores charged, before their fees.
- The Overview, charts and transaction feed show production unless you ask for sandbox: on the Overview, with Show sandbox.
Import RevenueCat's history
Active customers need no import: the first time the updated app starts, it reports what the store holds, and Blaink records it from the store itself. The import brings in the rest of your App Store customers now, such as those who haven't opened an updated app, with their past purchases, so your server and charts see them from the start.
- Set up RevenueCat's scheduled Transactions data export, and take a file it delivers: a CSV, or the
.csv.gzas it comes. It must have the columnsrc_original_app_user_id,store,store_transaction_id,original_store_transaction_id,product_identifier,start_timeandis_sandbox, and be at most 32 MB and 100,000 rows; export a shorter date range, or split a larger one. - On Import in the side menu, Import from RevenueCat, choose Upload and check. The check starts at once and writes nothing: every App Store purchase is asked of Apple with the app's In-App Purchase key, and nothing is recorded on RevenueCat's word alone.
- Read the report. Each purchase comes out as To import, Matches, Differs, Unverified or Skipped, with a reason. Check again asks Apple again about the unverified ones.
- Choose Import N purchases. It asks first and can't be undone: what's still unverified is left out. Carry on picks up an import that stalled.
- App Store rows only. Google Play rows are skipped, since the export carries no purchase token to ask Google with. The app's first launch with Blaink reports a customer's active Play purchases. Promotional and other stores' rows are skipped too.
- Customers: a purchase is imported under the app user ID RevenueCat last saw for the customer, else its original one, and Blaink makes that customer the first time the ID is used, so your backend's IDs keep working. A customer RevenueCat only knew as
$RCAnonymousID:…is imported with no owner, and the first device to report the purchase claims it. - Nothing Blaink already holds under an owner changes: such a purchase is only compared, and reads Matches or Differs. One an earlier import left with no owner takes the customer RevenueCat names, and store notifications Blaink logged with no customer for an imported purchase become that customer's.
- A customer whose history at Apple is too long to read whole is skipped; the app's first launch reports what they hold while it's active. An App Store app with no In-App Purchase key leaves its purchases unverified until you add one.
- One import runs at a time per project. App managers and owners run them.
Switch
- In one release, start Blaink Purchases in its default mode, move your paywall's purchases, restores and entitlement checks to
BlainkPurchases, and remove RevenueCat. - If App Store Connect still sends to RevenueCat's URL and RevenueCat forwards to Blaink, the URL can stay with RevenueCat until the older versions are gone; then enter Blaink's URL for both Production and Sandbox, and remove RevenueCat's forwarding URL. Without forwarding, enter Blaink's URL for both Production and Sandbox now.
- If RevenueCat forwards to Blaink, turn off its Track new purchases from server-to-server notifications once your app buys through Blaink: otherwise RevenueCat files each of those purchases under an anonymous customer of its own.
- Older versions of your app keep buying through RevenueCat until their users update. Keep forwarding Apple's notifications to RevenueCat, and keep its Pub/Sub subscription, while those versions are in use. Once they're gone, choose Stop forwarding on the Webhooks page, which drops anything not yet forwarded, and delete RevenueCat's subscription.
- Then turn on what needs Blaink alone: Answering Apple under Refund requests, once no version in use unlocks through RevenueCat, and Require a signed login, once every version in use sends a login token (Sign logins).
Test and go live
What to check before real customers buy, store by store, and what to decide on the day you switch over.
On the App Store
purchase_evidence_rejected: set the scheme’s StoreKit Configuration to None to test purchases.productNotFound.On Google Play
productNotFound.On the day, on both stores
Blaink-Signature and answers any 2xx within 10 seconds, and the delivery reads Delivered. A backend that treats every event as real money should hear production only.start() on iOS and in React Native, start(context) on Android — or Blaink keeps finishing nothing, and on Android acknowledges nothing. Where Apple’s notifications go meanwhile is in the migration section.0.0.0-dev, and reads as unable to use the newest features.Known limits
What Blaink Purchases doesn’t do yet, or does differently from what you might expect — each with what to do about it.
Stores
- On Google Play, an upgrade, a downgrade or a resubscription is a new purchase that Blaink doesn’t link to the one it replaces: there is no upgrade credit, and each counts as a new sale, in the charts and in paywall conversion. Read Play plan changes in your figures as new sales.
- Blaink reads every voided Google Play purchase as a full refund: the purchase stops unlocking anything, for good. To let a customer keep access after a Play refund, give it back with a grant.
- Blaink checks Google Play base plan and offer IDs by their format only. Copy them from the Play Console: a mistyped one shows as a package with no price, and buying it fails with
productNotFound.
Charts and figures
- Google Play purchases record no price, so Play revenue doesn’t appear in revenue charts yet. Play sales count as subscribers and trials, and add nothing to revenue, MRR, refunds, cohort value, link revenue, experiment revenue or a refund rule’s total spent. Read Play revenue in the Play Console until this changes.
- Revenue is what the store charged, before its fees: Blaink has no proceeds figure. Use the stores’ own reports for what they pay you.
- Charts are up to six hours old, in whole UTC days, while the Overview is live over the last 30 × 24 hours, so the two can differ near the ends of a range. Read today on the Overview and trends on Charts.
- Charts cover at most 1,100 days; breakdowns the last 400, as 20 series and everything else; cohorts keep 52 weeks or 36 months. For longer histories, send the data to your own bucket with Exports.
- Apple’s upgrade credits are estimates from the charge’s dates until Apple’s daily report replaces them, in production only, and only with an App Store Connect key for reports and its vendor number (Connect the stores, step 5).
- Experiments compare each variant with A in a basic 95% test, with no correction when there are several variants, and give no verdict under 100 customers or 5 outcomes in a variant. Prefer two variants, and wait for the verdict. Nothing warns you about a variant whose offering has no packages on a store or no published paywall: check each before you start.
- Paywall conversion: a day’s figures settle after four days, a version is judged against its offering as it stands now, and views aren’t split by environment, so your testers’ views count too. Read conversion once real traffic has arrived.
- Link revenue counts only installs that open their link within 48 hours.
Customers
- The Customers page’s statuses mix sandbox and production: a tester with a sandbox subscription reads as Active. The entitlement on their page says whether it is sandbox.
- The SDKs keep the app user ID on the device unencrypted. Log customers in with an opaque ID of your own, never an email address or other personal data.
- An app hears of a change made elsewhere — a grant, a block, a refund Google reports — only when it next asks Blaink: the SDKs don’t poll, and Blaink doesn’t push. Read the customer again (
customerInfo(), orgetCustomerInfo()in React Native) when your app comes back to the foreground. - Offerings and paywalls aren’t cached on the device: with no connection, reading them fails as unavailable. Have a screen of your own for that case.
- Deleting a blocked customer leaves their purchases with no owner and no block, so the next device that reports them takes them. Keep a customer you mean to stop blocked; delete only for a privacy request.
Automations
- Billing-issue and win-back pushes start from the stores’ notifications: without them, they never go out. Set up both stores’ notifications first (Connect the stores).
- Trial ending counts free trials only, not offer codes or promotional offers.
- There are no quiet hours: a push goes out when its timing falls, whatever the hour where the customer is. Choose timings with that in mind.
- “Sent” means handed to the push service, not delivered, and a push isn’t linked to any purchase it led to. Measure what a win-back brings with your own analytics.
- A customer gets at most one push of each kind a day, and a project at most 200 every five minutes. A push still owed is dropped when the purchase moves to another customer.
Retention messages
- App Store only, as text or switch-plan messages, and only once Apple has granted your developer account real-time Retention Messaging. There is no win-back offer builder.
- A header’s 66 and a body’s 144 characters are counted in UTF-16 units, so an emoji can count as two.
- A switch-plan message’s suggested subscription isn’t checked against the subscription group. Choose one in the same group.
- Turning Retention messages off doesn’t remove your messages at Apple. Delete them first, while it is on.
Refund requests
- Apple only: Google Play sends no such requests.
- Blaink never tells Apple how much was used, and answers about a consumable only when the virtual-currency ledger credited it.
- Recording consent from the app needs iOS 2.4.0 or React Native 2.3.0 on iOS. For customers on older app versions, record it from your backend (From your server).
- A refund rule’s dry run ignores blocks and consent: a request it shows as answered may still be held back for either.
Signed logins
- Until you require them,
logIntrusts the app user ID it is given: anyone who knows a customer’s ID can log in as them and use what they bought. Require signed logins once your apps send tokens. - The setting is one per project, not per environment, so requiring it applies to TestFlight builds and licence testers too. Sign tokens in your test backend as well.
- A token can be used again until it expires, at most ten minutes after it was issued. Keep its lifetime short.
- Only iOS 2.4.0, Android 2.3.0, React Native 2.3.0 and later send a token. Check the SDK versions page before you require them.
Imports, forwarding and exports
- The Import page can’t bring over Google Play purchases: the export it reads has no purchase token to check them with. An Android customer’s active subscriptions and non-consumables are recorded when their app first launches with Blaink.
- An import takes up to 32 MB and 100,000 rows, one at a time, and leaves out every row the store couldn’t confirm.
- Forwarding passes on only the notifications Apple delivered to Blaink live; one Blaink recovers later from Apple’s history isn’t forwarded. It is App Store only, and Blaink doesn’t sign what it forwards.
- A day an export has sent is never sent again, even if it changes later, and a dataset added later isn’t backfilled. Deleting a customer can’t reach copies already in your bucket: erase those yourself.
The API and webhooks
- A webhook’s signing secret can’t be replaced. Rotate it by adding a second connection and removing the first (Webhooks).
- A project has up to 10 connections. Your endpoint must answer within 10 seconds; a failed delivery is retried for about 22 hours, then given up.
- Webhooks, the server API and Charts don’t say which deferred link brought a customer; only the Link revenue page does.
- The server API’s IP allowlist takes exact addresses only, with no ranges, an empty list allows nothing, and the console can’t edit it. Write to us with your servers’ addresses.
- Asking the server API about an unknown
customerIDanswers200with no entitlements, not404. Name customers byappUserIDwhere you can.
SDK platform gaps
- No web purchases: a web app’s offerings and paywall reads are refused with
purchase_store_not_configured, and Stripe isn’t supported. Sell on the web through your own checkout, and give access with a grant from your server. - No SDK has virtual-currency calls in these versions. Your app reads balances, and spends currency, through your backend and the server API.
- iOS: a purchase can carry no promotional or win-back offer, and the SDK shows no offer-code sheet, so a customer gets only the introductory offer Apple gives them. Offer codes redeemed in the App Store still arrive, as
offer_redeemed. - Android: a package’s Play offer is sold only when Google offers it to that customer, and only offers whose eligibility is “New customer acquisition” work. A “Developer determined” offer would be sold to everyone, and an “Upgrade” offer bought as a second subscription. With no base plan named on the package or the product, the SDK sells the first base plan’s own price that Google lists.
- Android: there is no upgrade or downgrade path, so buying a second subscription product starts a second subscription beside the first. While a customer’s subscription is active, don’t offer them another on Android.
- React Native: a paywall is presented modally only, with no component to place in your own screen, and
presentationis honoured on iOS only. There is no Expo config plugin, and the packages can’t run in Expo Go. - React Native and the console round offering metadata numbers above 253. Keep large numbers in metadata as strings.
Stuck somewhere?
The SDKs are open to read, and we answer integration questions within a working day.