@kissmyappss/react-native 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,43 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@kissmyappss/react-native`. Releases follow
4
+ [semantic versioning](https://semver.org).
5
+
6
+ ## 1.1.0
7
+
8
+ Install attribution, deep links and revenue.
9
+
10
+ - On the first launch, right after `app_installed`, the SDK calls `/v1/attribution/install`
11
+ once to match the install to the smart link that brought it. Offline, it tries again on the
12
+ next three launches with the same details.
13
+ - Links that open the app are read from `Linking` (`getInitialURL()` and `url` events) and
14
+ reported to `/v1/attribution/open`. The first launch's opening link goes with the install
15
+ call instead.
16
+ - `KissMyApps.onDeepLink(handler)` receives the deferred deep link after an install and the
17
+ deep link of each link that opens the app, once each; one that arrives before a handler is
18
+ set waits for it.
19
+ - `KissMyApps.handleDeepLink(url)` reports a link that reached the app another way.
20
+ - New options `attribution`, `deepLinks` and `clipboardHandoff`.
21
+ - An optional native module, `KissMyAppsAttribution` (Swift and Kotlin, linked by
22
+ autolinking), adds the device key (a SHA-256 hash of `identifierForVendor` or `ANDROID_ID`),
23
+ the Google Play install referrer, the Apple Ads token and the iPhone clipboard handoff.
24
+ Without it, as in Expo Go, the install call runs without those fields. The iOS pod brings a
25
+ privacy manifest.
26
+ - `KissMyApps.revenue(amount, currency, options?)` records a payment as a `purchase` event
27
+ (`refund` for a negative amount) with the reserved properties `kma_revenue` and
28
+ `kma_currency`, plus `kma_product_id` and `kma_transaction_id` from the `productId` and
29
+ `transactionId` options. `event` names the event and `properties` adds more. A
30
+ transaction ID makes the app's call and a RevenueCat or Adapty webhook for the same
31
+ payment count once. An amount that is 0 or over 1,000,000,000 either way, or a currency
32
+ that is not three letters, sends nothing.
33
+ - The SDK string is now `kma-react-native/1.1.0`.
34
+
35
+ ## 1.0.0 (2026-10-30)
36
+
37
+ The first release.
38
+
39
+ - Automatic `session_started`, `app_installed`, `app_updated`, `app_opened`,
40
+ `app_backgrounded` and `screen_viewed` events, with screens from React Navigation.
41
+ - `track`, `screen`, `identify`, `setTraits`, `reset`, `optOut`, `optIn` and `flush`.
42
+ - An offline queue in AsyncStorage (up to 1,000 events) with batching and retries with
43
+ backoff.
@@ -0,0 +1,29 @@
1
+ # The optional native module KissMyAppsAttribution for iOS: the device key, the Apple Ads
2
+ # token and the clipboard handoff for install attribution. Linked by autolinking with
3
+ # `pod install`; without it the SDK still runs, minus those fields.
4
+ require 'json'
5
+
6
+ package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
7
+
8
+ Pod::Spec.new do |s|
9
+ s.name = 'KissMyAppsReactNative'
10
+ s.version = package['version']
11
+ s.summary = 'Native part of @kissmyappss/react-native: device key and Apple Ads attribution.'
12
+ s.homepage = package['homepage']
13
+ s.license = { :type => package['license'], :file => 'LICENSE' }
14
+ s.author = 'KissMyApps'
15
+ s.source = { :path => '.' }
16
+ s.platforms = { :ios => '12.4' }
17
+ s.swift_version = '5.0'
18
+ s.source_files = 'ios/**/*.{h,m,swift}'
19
+ s.resource_bundles = { 'KissMyAppsReactNativePrivacy' => ['ios/PrivacyInfo.xcprivacy'] }
20
+ # AdServices is there from iOS 14.3; older systems skip Apple Ads.
21
+ s.weak_frameworks = 'AdServices'
22
+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
23
+
24
+ if respond_to?(:install_modules_dependencies, true)
25
+ install_modules_dependencies(s)
26
+ else
27
+ s.dependency 'React-Core'
28
+ end
29
+ end
package/README.md CHANGED
@@ -7,8 +7,8 @@
7
7
  <h1 align="center">KissMyApps for React Native</h1>
8
8
 
9
9
  <p align="center">
10
- Installs, sessions, screens and your own events, from your app to your KissMyApps dashboard.<br>
11
- Plain JavaScript: nothing to link, works with Expo.
10
+ Installs, sessions, screens, your own events, install attribution and deep links, from your app to your KissMyApps dashboard.<br>
11
+ Plain JavaScript that works with Expo, plus an optional native module for exact install matching.
12
12
  </p>
13
13
 
14
14
  <p align="center">
@@ -27,8 +27,12 @@
27
27
  recorded on their own; React Navigation screens take one line.
28
28
  - **Nothing is lost offline.** Events wait in storage, survive a restart and go out with
29
29
  backoff once there is a connection.
30
- - **No native code.** Pure JavaScript with TypeScript types, so it works in Expo Go and needs
31
- no `pod install`.
30
+ - **Know which link brought each install.** On the first launch the SDK matches the install
31
+ to the smart link that brought it and hands your app the link's deep link, even when the
32
+ person had to install the app first.
33
+ - **Native code only if you want it.** The core is plain JavaScript with TypeScript types, so
34
+ it works in Expo Go. The small optional native module adds the device key, the Google Play
35
+ install referrer and the Apple Ads token; it links itself.
32
36
  - **Respectful by default.** A random ID per install, no advertising ID, no fingerprinting,
33
37
  and an opt-out that is remembered across launches.
34
38
  - **One dashboard for every platform.** It sends the same events as the
@@ -79,7 +83,8 @@ KissMyApps.init({
79
83
  </details>
80
84
 
81
85
  Storage is what lets the SDK recognise a returning person and keep events through a restart.
82
- Without it the SDK still works, but every launch counts as a new install.
86
+ Without it the SDK still works, but every launch counts as a new install (and installs are
87
+ not matched to links).
83
88
 
84
89
  ## Track what matters
85
90
 
@@ -122,21 +127,166 @@ Event names use letters, numbers and `_ . : -`, start with a letter and are up t
122
127
  characters; other names are ignored. Calls made before `init` are kept and run once it is
123
128
  called.
124
129
 
130
+ ### Revenue
131
+
132
+ Record each payment once the store has confirmed it, so the console can show what the
133
+ people from each ad or link paid and the return on what you spent:
134
+
135
+ ```ts
136
+ // The amount in major units (9.99, not 999) and its ISO 4217 currency code
137
+ KissMyApps.revenue(9.99, 'USD', {
138
+ productId: 'annual',
139
+ transactionId: purchase.transactionId, // the store's ID for this payment
140
+ })
141
+
142
+ // A refund is a negative amount, with the same transaction ID
143
+ KissMyApps.revenue(-9.99, 'USD', { transactionId })
144
+ ```
145
+
146
+ It sends a `purchase` event (`refund` for a negative amount) with the reserved properties
147
+ `kma_revenue` (the amount), `kma_currency` (sent upper case) and, when given,
148
+ `kma_product_id` and `kma_transaction_id`. `event` gives the event your own name, such as
149
+ `subscription_started`, and `properties` adds more; the four `kma_` properties always come
150
+ from the call itself. An amount that is 0, not a number or over 1,000,000,000 either way,
151
+ or a currency that is not three letters, sends nothing (with a warning when `debug` is
152
+ on). A product or transaction ID longer than 200 characters is left out. Reports show
153
+ revenue in the project's currency, converted with the European Central Bank's daily rates.
154
+
155
+ **Transaction IDs** make one payment count once. When the project also has RevenueCat or
156
+ Adapty connected in the console, their webhook reports the same purchase: pass the store's
157
+ transaction ID (on iOS the StoreKit transaction ID, on Android the Google Play order ID,
158
+ `GPA.…`), which is the one those tools report, and the payment counts once. Without a
159
+ transaction ID each call is a separate payment. If you cannot get the same ID, record
160
+ payments in one place only: the webhook or the app.
161
+
162
+ From a server, send the same event to `POST https://events.kissmyapps.dev/v1/events` with a
163
+ server key (`kma_sk_`), the user ID you pass to `identify` and the same `kma_` properties;
164
+ the [iOS and Android SDK guide](https://github.com/onorhime/kissmyapps-mobile#revenue)
165
+ shows the request.
166
+
125
167
  ### Everything at a glance
126
168
 
127
- | Call | What it does |
128
- | ---------------------------------- | ----------------------------------------------------- |
129
- | `KissMyApps.init(options)` | Starts recording. Call once. |
130
- | `KissMyApps.track(name, props?)` | Records one of your events. |
131
- | `KissMyApps.screen(name, props?)` | Records a screen view. |
132
- | `trackNavigation(ref)` | Records every React Navigation screen. |
133
- | `KissMyApps.identify(id, traits?)` | Ties this install to your user ID. |
134
- | `KissMyApps.setTraits(traits)` | Updates what you know about the person. |
135
- | `KissMyApps.reset()` | Forgets the person and starts a new anonymous one. |
136
- | `KissMyApps.optOut()` / `optIn()` | Stops or resumes sending. Remembered across launches. |
137
- | `KissMyApps.flush()` | Sends what is queued now; returns a promise. |
138
- | `KissMyApps.getAnonymousId()` | This install's random ID, for support tickets. |
139
- | `KissMyApps.getSessionId()` | The current session's ID. |
169
+ | Call | What it does |
170
+ | ------------------------------------------------ | ----------------------------------------------------- |
171
+ | `KissMyApps.init(options)` | Starts recording. Call once. |
172
+ | `KissMyApps.track(name, props?)` | Records one of your events. |
173
+ | `KissMyApps.revenue(amount, currency, options?)` | Records a payment, or a refund (negative). |
174
+ | `KissMyApps.screen(name, props?)` | Records a screen view. |
175
+ | `trackNavigation(ref)` | Records every React Navigation screen. |
176
+ | `KissMyApps.onDeepLink(handler)` | Receives deep links; returns a function to stop. |
177
+ | `KissMyApps.handleDeepLink(url)` | Reports a link that opened the app another way. |
178
+ | `KissMyApps.identify(id, traits?)` | Ties this install to your user ID. |
179
+ | `KissMyApps.setTraits(traits)` | Updates what you know about the person. |
180
+ | `KissMyApps.reset()` | Forgets the person and starts a new anonymous one. |
181
+ | `KissMyApps.optOut()` / `optIn()` | Stops or resumes sending. Remembered across launches. |
182
+ | `KissMyApps.flush()` | Sends what is queued now; returns a promise. |
183
+ | `KissMyApps.getAnonymousId()` | This install's random ID, for support tickets. |
184
+ | `KissMyApps.getSessionId()` | The current session's ID. |
185
+
186
+ ## Install attribution and deep links
187
+
188
+ Smart links (`https://<you>.go.kissmyapps.dev/…`, or your own domain) send people to the App
189
+ Store, Google Play or your website, and open your app when it is installed. With attribution
190
+ turned on for the project in the console, the SDK:
191
+
192
+ - on the **first launch**, right after `app_installed`, asks KissMyApps once which link brought
193
+ the install, and hands you that link's deep link (a _deferred_ deep link);
194
+ - each time a **smart link opens the app** later, reports it and hands you its deep link.
195
+
196
+ ```tsx
197
+ import { KissMyApps } from '@kissmyappss/react-native'
198
+
199
+ // For example next to your navigation container, as early as you can.
200
+ useEffect(
201
+ () =>
202
+ KissMyApps.onDeepLink((link) => {
203
+ // link.value: the deep link value you set on the smart link, such as 'lesson'
204
+ // link.params: its parameters as text, such as { id: '4' }
205
+ // link.deferred: true after an install, false when a link opened the app
206
+ // link.url: the link that opened the app, or null after a store install
207
+ if (link.value === 'lesson') navigation.navigate('Lesson', { id: link.params.id })
208
+ }),
209
+ [],
210
+ )
211
+ ```
212
+
213
+ Each deep link is handed over once. One that arrives before you set a handler waits for it
214
+ (only the newest is kept). `onDeepLink` returns a function that removes the handler.
215
+
216
+ The SDK reads the link that opened the app (`Linking.getInitialURL()`) and links opened while
217
+ it runs (Linking's `url` events) by itself, so your own linking setup (React Navigation's
218
+ `linking`, Expo Router) keeps working as it is. If a link reaches your app some other way,
219
+ pass it on with `KissMyApps.handleDeepLink(url)`; it returns `false` when nothing is sent (not
220
+ an https link, attribution off, opted out). The same link reported twice within 3 seconds
221
+ counts once.
222
+
223
+ The install call is made once. If the phone is offline it is tried again on the next three
224
+ launches, with the same details. Until attribution is on for the project, both calls answer
225
+ "off" and nothing is stored.
226
+
227
+ ### Let your app open your links
228
+
229
+ The console's **Attribution → Setup** shows the exact lines for your link domains. The
230
+ [iOS and Android SDK guide](https://github.com/onorhime/kissmyapps-mobile#attribution-and-deep-links) explains
231
+ them in full; in short:
232
+
233
+ - **iOS:** in Xcode, under **Signing & Capabilities**, add **Associated Domains** with
234
+ `applinks:<your link domain>`. React Native's `Linking` needs the app delegate to pass
235
+ Universal Links on, as in React Native's
236
+ [linking guide](https://reactnative.dev/docs/linking#enabling-deep-links):
237
+
238
+ ```objc
239
+ // AppDelegate.mm
240
+ #import <React/RCTLinkingManager.h>
241
+
242
+ - (BOOL)application:(UIApplication *)application
243
+ continueUserActivity:(NSUserActivity *)userActivity
244
+ restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> *))restorationHandler
245
+ {
246
+ return [RCTLinkingManager application:application
247
+ continueUserActivity:userActivity
248
+ restorationHandler:restorationHandler];
249
+ }
250
+ ```
251
+
252
+ - **Android:** in `AndroidManifest.xml`, inside the activity that opens links, an intent
253
+ filter with `android:autoVerify="true"` for `https` and your link domains.
254
+
255
+ - **Expo:** set `ios.associatedDomains` (`["applinks:<your link domain>"]`) and
256
+ `android.intentFilters` (with `autoVerify: true`) in `app.json`; Expo writes both for you.
257
+
258
+ ### The optional native module
259
+
260
+ The package brings a small native module, `KissMyAppsAttribution`, that React Native's
261
+ autolinking adds to your app: run `cd ios && pod install` after installing; Android needs
262
+ nothing. It adds to the install call:
263
+
264
+ | Field | Platform | What it gives |
265
+ | --------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
266
+ | Device key | Both | A SHA-256 hash of `identifierForVendor` (iOS) or `ANDROID_ID` (Android), so a reinstall is recognised and not counted (or paid) twice. The identifier itself never leaves the phone. |
267
+ | Play referrer | Android | The Google Play install referrer, which names the exact click that led to the install. |
268
+ | Apple Ads | iOS | The Apple Ads attribution token, on iOS 14.3 and later, for installs from Apple Search Ads. |
269
+ | Clipboard click | iOS | With `clipboardHandoff` on, the click ID the smart link's page copied (see below). |
270
+
271
+ Without the module, as in **Expo Go**, the install call still runs, without those fields: an
272
+ install is still matched when a smart link opens the app on its first launch (or when the
273
+ person signs in on a site that saw the click), but not from the Play referrer, Apple Ads or
274
+ the clipboard, and a reinstall is not recognised. The module works in **Expo development
275
+ builds** and **bare** apps (`npx expo prebuild` links it like any native module). There is
276
+ no Expo config plugin: the module needs none, and your link domains go in `app.json` as
277
+ above.
278
+
279
+ **Clipboard handoff for iPhone.** The App Store passes nothing from the link to the app, so
280
+ an iPhone install that no link opens is otherwise matched only through Apple Ads or a later
281
+ sign-in. With
282
+ **Clipboard handoff for iPhone** on in the console, the smart link's page copies the click
283
+ before opening the App Store; turn on `clipboardHandoff: true` too and the SDK reads it on the
284
+ first launch. iOS asks the person before an app reads what another app copied, so this is off
285
+ by default.
286
+
287
+ No advertising identifier is used (no IDFA, no GAID, no `AD_ID` permission) and no tracking
288
+ prompt is shown. The iOS pod brings a privacy manifest that declares the device ID and product
289
+ interaction, used for analytics and not for tracking.
140
290
 
141
291
  ## What gets recorded
142
292
 
@@ -153,6 +303,8 @@ Every request also carries iOS or Android and the OS version, phone or tablet, t
153
303
  model on Android (iPhone or iPad on iOS), screen size, language, time zone, app version and
154
304
  the SDK version. Country, region and city are worked out by the KissMyApps server from the
155
305
  request's address, which is only ever kept as a salted hash. There is no advertising ID.
306
+ The two attribution calls send what is described under
307
+ [Install attribution and deep links](#install-attribution-and-deep-links).
156
308
 
157
309
  A session ends after 30 minutes in the background or without events. Events are sent every
158
310
  10 seconds, at once when 30 are waiting, and when the app goes to the background. While
@@ -161,19 +313,24 @@ backoff, including on the next launch.
161
313
 
162
314
  ## Options
163
315
 
164
- | Option | Default | What it does |
165
- | ----------------------- | ------------------------------- | -------------------------------------------------------------- |
166
- | `key` | Required | The project's client key. |
167
- | `storage` | None | AsyncStorage or anything with `getItem` and `setItem`. |
168
- | `appVersion` | None | The version shown in the dashboard. |
169
- | `build` | None | The build number, used to spot updates. |
170
- | `endpoint` | `https://events.kissmyapps.dev` | Where events are sent. |
171
- | `sessionTimeoutMinutes` | `30` | Minutes in the background or idle before a new session starts. |
172
- | `flushIntervalSeconds` | `10` | How often queued events are sent while the app is open. |
173
- | `maxQueue` | `1000` | The most events kept while offline. |
174
- | `trackLifecycle` | `true` | Record installs, updates, opens and backgrounding. |
175
- | `debug` | `false` | Log refused events and other problems to the console. |
316
+ | Option | Default | What it does |
317
+ | ----------------------- | ------------------------------- | --------------------------------------------------------------- |
318
+ | `key` | Required | The project's client key. |
319
+ | `storage` | None | AsyncStorage or anything with `getItem` and `setItem`. |
320
+ | `appVersion` | None | The version shown in the dashboard. |
321
+ | `build` | None | The build number, used to spot updates. |
322
+ | `endpoint` | `https://events.kissmyapps.dev` | Where events are sent. |
323
+ | `sessionTimeoutMinutes` | `30` | Minutes in the background or idle before a new session starts. |
324
+ | `flushIntervalSeconds` | `10` | How often queued events are sent while the app is open. |
325
+ | `maxQueue` | `1000` | The most events kept while offline. |
326
+ | `trackLifecycle` | `true` | Record installs, updates, opens and backgrounding. |
327
+ | `attribution` | `true` | Match the install to a link and report links that open the app. |
328
+ | `deepLinks` | `true` | Read links from `Linking`; off, call `handleDeepLink` yourself. |
329
+ | `clipboardHandoff` | `false` | iPhone: read the click the smart link's page copied. |
330
+ | `debug` | `false` | Log refused events and other problems to the console. |
176
331
 
177
332
  ## License
178
333
 
179
334
  MIT © KissMyApps
335
+
336
+ Withdrawing consent with `optOut` clears queued events, identity, session and pending install attribution. After `optIn`, tracking starts with a new anonymous ID.
@@ -0,0 +1,65 @@
1
+ // The optional native module KissMyAppsAttribution for Android: the Google Play install
2
+ // referrer and the device key for install attribution. Linked by autolinking; without it the
3
+ // SDK still runs, minus those fields. No advertising ID, no AD_ID permission.
4
+ buildscript {
5
+ def kotlinVersion = rootProject.ext.has('kotlinVersion') ? rootProject.ext.get('kotlinVersion') : '1.9.24'
6
+ repositories {
7
+ google()
8
+ mavenCentral()
9
+ }
10
+ dependencies {
11
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
12
+ }
13
+ }
14
+
15
+ apply plugin: 'com.android.library'
16
+ apply plugin: 'kotlin-android'
17
+
18
+ def safeExtGet(name, fallback) {
19
+ rootProject.ext.has(name) ? rootProject.ext.get(name) : fallback
20
+ }
21
+
22
+ // Android Gradle plugin 7.3 and later take the namespace here; older ones read the manifest.
23
+ def supportsNamespace() {
24
+ def parts = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')
25
+ def major = parts[0].toInteger()
26
+ def minor = parts[1].toInteger()
27
+ return major > 7 || (major == 7 && minor >= 3)
28
+ }
29
+
30
+ android {
31
+ if (supportsNamespace()) {
32
+ namespace 'com.kissmyapps.reactnative'
33
+ sourceSets {
34
+ main {
35
+ manifest.srcFile 'src/main/AndroidManifestNew.xml'
36
+ }
37
+ }
38
+ }
39
+ compileSdkVersion safeExtGet('compileSdkVersion', 34)
40
+
41
+ defaultConfig {
42
+ minSdkVersion safeExtGet('minSdkVersion', 21)
43
+ targetSdkVersion safeExtGet('targetSdkVersion', 34)
44
+ }
45
+
46
+ // React Native 0.73 and later set both to 17 for every library.
47
+ compileOptions {
48
+ sourceCompatibility JavaVersion.VERSION_1_8
49
+ targetCompatibility JavaVersion.VERSION_1_8
50
+ }
51
+ kotlinOptions {
52
+ jvmTarget = '1.8'
53
+ }
54
+ }
55
+
56
+ repositories {
57
+ google()
58
+ mavenCentral()
59
+ }
60
+
61
+ dependencies {
62
+ // Resolved to react-android by React Native 0.71 and later.
63
+ implementation 'com.facebook.react:react-native:+'
64
+ implementation 'com.android.installreferrer:installreferrer:2.2'
65
+ }
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2
+ package="com.kissmyapps.reactnative" />
@@ -0,0 +1 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,138 @@
1
+ package com.kissmyapps.reactnative
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.content.Intent
5
+ import android.os.Handler
6
+ import android.os.Looper
7
+ import android.provider.Settings
8
+ import com.android.installreferrer.api.InstallReferrerClient
9
+ import com.android.installreferrer.api.InstallReferrerStateListener
10
+ import com.android.installreferrer.api.ReferrerDetails
11
+ import com.facebook.react.bridge.Arguments
12
+ import com.facebook.react.bridge.Promise
13
+ import com.facebook.react.bridge.ReactApplicationContext
14
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
15
+ import com.facebook.react.bridge.ReactMethod
16
+ import com.facebook.react.bridge.ReadableMap
17
+ import com.facebook.react.bridge.WritableMap
18
+ import java.security.MessageDigest
19
+ import java.util.concurrent.atomic.AtomicBoolean
20
+
21
+ /**
22
+ * The optional native part of @kissmyappss/react-native on Android: what the install call
23
+ * needs that JavaScript cannot read. The SDK works without it, minus these fields.
24
+ *
25
+ * - `deviceKey`: SHA-256 hex of Settings.Secure.ANDROID_ID. The ID itself never leaves the phone.
26
+ * - `referrer`, `referrerClickTs`, `installBeginTs`: from the Google Play Install Referrer API,
27
+ * on install tries only, waiting at most 10 seconds for Google Play (`retryReferrer` then).
28
+ *
29
+ * No advertising ID and no AD_ID permission.
30
+ */
31
+ class KissMyAppsAttributionModule(context: ReactApplicationContext) :
32
+ ReactContextBaseJavaModule(context) {
33
+
34
+ override fun getName(): String = NAME
35
+
36
+ @ReactMethod
37
+ fun getAttributionInfo(request: ReadableMap, promise: Promise) {
38
+ val install = request.hasKey("install") && request.getBoolean("install")
39
+ val info = Arguments.createMap()
40
+ deviceKey()?.let { info.putString("deviceKey", it) }
41
+ if (!install) {
42
+ promise.resolve(info)
43
+ return
44
+ }
45
+ readReferrer(info, promise)
46
+ }
47
+
48
+ /** Whether the activity was reopened from Recents: its link then opened the app before. */
49
+ @ReactMethod
50
+ fun launchedFromHistory(promise: Promise) {
51
+ val flags = reactApplicationContext.currentActivity?.intent?.flags ?: 0
52
+ promise.resolve(flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0)
53
+ }
54
+
55
+ private fun readReferrer(info: WritableMap, promise: Promise) {
56
+ val client = try {
57
+ InstallReferrerClient.newBuilder(reactApplicationContext).build()
58
+ } catch (error: Exception) {
59
+ null
60
+ }
61
+ if (client == null) {
62
+ promise.resolve(info)
63
+ return
64
+ }
65
+ val answered = AtomicBoolean(false)
66
+ val main = Handler(Looper.getMainLooper())
67
+ // `retry`: Google Play did not answer this time, so the next launch's try asks again.
68
+ fun finish(details: ReferrerDetails?, retry: Boolean) {
69
+ if (!answered.compareAndSet(false, true)) return
70
+ if (details != null) {
71
+ details.installReferrer?.takeIf { it.isNotEmpty() }?.let { info.putString("referrer", it) }
72
+ // Play answers 0 when it does not know.
73
+ val clicked = details.referrerClickTimestampSeconds
74
+ val began = details.installBeginTimestampSeconds
75
+ if (clicked > 0) info.putDouble("referrerClickTs", clicked.toDouble())
76
+ if (began > 0) info.putDouble("installBeginTs", began.toDouble())
77
+ }
78
+ if (retry) info.putBoolean("retryReferrer", true)
79
+ try {
80
+ client.endConnection()
81
+ } catch (ignored: Exception) {
82
+ // Already closed.
83
+ }
84
+ promise.resolve(info)
85
+ }
86
+ main.postDelayed({ finish(null, true) }, REFERRER_WAIT_MS)
87
+ try {
88
+ client.startConnection(object : InstallReferrerStateListener {
89
+ override fun onInstallReferrerSetupFinished(responseCode: Int) {
90
+ when (responseCode) {
91
+ InstallReferrerClient.InstallReferrerResponse.OK -> {
92
+ val details = try {
93
+ client.installReferrer
94
+ } catch (error: Exception) {
95
+ null
96
+ }
97
+ main.post { finish(details, details == null) }
98
+ }
99
+ InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE,
100
+ InstallReferrerClient.InstallReferrerResponse.SERVICE_DISCONNECTED,
101
+ -> main.post { finish(null, true) }
102
+ // No Play Store, or one without the API: asking again will not help.
103
+ else -> main.post { finish(null, false) }
104
+ }
105
+ }
106
+
107
+ override fun onInstallReferrerServiceDisconnected() {
108
+ main.post { finish(null, true) }
109
+ }
110
+ })
111
+ } catch (error: Exception) {
112
+ main.post { finish(null, true) }
113
+ }
114
+ }
115
+
116
+ @SuppressLint("HardwareIds")
117
+ private fun deviceKey(): String? = try {
118
+ val id = Settings.Secure.getString(
119
+ reactApplicationContext.contentResolver,
120
+ Settings.Secure.ANDROID_ID,
121
+ )
122
+ // Some old Android 2.2 phones all share this ID: it says nothing about the device.
123
+ if (id.isNullOrEmpty() || id == SHARED_ANDROID_ID) null else sha256Hex(id)
124
+ } catch (error: Exception) {
125
+ null
126
+ }
127
+
128
+ companion object {
129
+ const val NAME = "KissMyAppsAttribution"
130
+ private const val REFERRER_WAIT_MS = 10_000L
131
+ private const val SHARED_ANDROID_ID = "9774d56d682e549c"
132
+
133
+ fun sha256Hex(text: String): String =
134
+ MessageDigest.getInstance("SHA-256")
135
+ .digest(text.toByteArray(Charsets.UTF_8))
136
+ .joinToString("") { "%02x".format(it) }
137
+ }
138
+ }
@@ -0,0 +1,15 @@
1
+ package com.kissmyapps.reactnative
2
+
3
+ import com.facebook.react.ReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.uimanager.ViewManager
7
+
8
+ /** Adds KissMyAppsAttribution to the app; autolinking registers it. */
9
+ class KissMyAppsAttributionPackage : ReactPackage {
10
+ override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> =
11
+ listOf(KissMyAppsAttributionModule(reactContext))
12
+
13
+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> =
14
+ emptyList()
15
+ }
@@ -0,0 +1,10 @@
1
+ // Registers the Swift module KissMyAppsAttribution with React Native.
2
+ #import <React/RCTBridgeModule.h>
3
+
4
+ @interface RCT_EXTERN_MODULE(KissMyAppsAttribution, NSObject)
5
+
6
+ RCT_EXTERN_METHOD(getAttributionInfo:(NSDictionary *)request
7
+ resolver:(RCTPromiseResolveBlock)resolve
8
+ rejecter:(RCTPromiseRejectBlock)reject)
9
+
10
+ @end
@@ -0,0 +1,75 @@
1
+ import CommonCrypto
2
+ import Foundation
3
+ import UIKit
4
+ #if canImport(AdServices)
5
+ import AdServices
6
+ #endif
7
+
8
+ /// The optional native part of @kissmyappss/react-native on iOS: what the install call needs
9
+ /// that JavaScript cannot read. The SDK works without it, minus these fields.
10
+ ///
11
+ /// - `deviceKey`: SHA-256 hex of identifierForVendor. The identifier itself never leaves the phone.
12
+ /// - `appleAdsToken`: AAAttribution.attributionToken(), iOS 14.3 and later, first launch only.
13
+ /// - `clipboardClick`: the click ID after `kma:` on the clipboard, only when the app turned
14
+ /// clipboard handoff on (iOS asks the person before an app reads another app's copy).
15
+ ///
16
+ /// No advertising identifier, no tracking prompt.
17
+ @objc(KissMyAppsAttribution)
18
+ final class KissMyAppsAttribution: NSObject {
19
+ @objc static func requiresMainQueueSetup() -> Bool { false }
20
+
21
+ @objc(getAttributionInfo:resolver:rejecter:)
22
+ func getAttributionInfo(
23
+ _ request: NSDictionary,
24
+ resolver resolve: @escaping (Any?) -> Void,
25
+ rejecter _: @escaping (String?, String?, Error?) -> Void
26
+ ) {
27
+ let install = request["install"] as? Bool ?? false
28
+ let clipboard = request["clipboard"] as? Bool ?? false
29
+ DispatchQueue.main.async {
30
+ var info: [String: Any] = [:]
31
+ if let vendor = UIDevice.current.identifierForVendor?.uuidString {
32
+ info["deviceKey"] = KissMyAppsAttribution.sha256Hex(vendor)
33
+ }
34
+ if install, clipboard, let click = KissMyAppsAttribution.clipboardClick() {
35
+ info["clipboardClick"] = click
36
+ }
37
+ let fromMain = info
38
+ // The token comes from a system service; keep it off the main thread.
39
+ DispatchQueue.global(qos: .utility).async {
40
+ var result = fromMain
41
+ if install, let ads = KissMyAppsAttribution.appleAdsToken() {
42
+ result["appleAdsToken"] = ads
43
+ }
44
+ resolve(result)
45
+ }
46
+ }
47
+ }
48
+
49
+ private static func clipboardClick() -> String? {
50
+ let board = UIPasteboard.general
51
+ guard board.hasStrings, let text = board.string else { return nil }
52
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
53
+ guard trimmed.hasPrefix("kma:") else { return nil }
54
+ return String(trimmed.dropFirst(4))
55
+ }
56
+
57
+ private static func appleAdsToken() -> String? {
58
+ #if canImport(AdServices)
59
+ if #available(iOS 14.3, *) {
60
+ // Fails on the simulator and when Apple's service is unavailable: nothing then.
61
+ return try? AAAttribution.attributionToken()
62
+ }
63
+ #endif
64
+ return nil
65
+ }
66
+
67
+ static func sha256Hex(_ text: String) -> String {
68
+ let bytes = Array(text.utf8)
69
+ var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
70
+ _ = bytes.withUnsafeBufferPointer { buffer in
71
+ CC_SHA256(buffer.baseAddress, CC_LONG(buffer.count), &digest)
72
+ }
73
+ return digest.map { String(format: "%02x", $0) }.joined()
74
+ }
75
+ }