@kissmyappss/react-native 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 KissMyApps
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,336 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://kissmyapps.dev">
3
+ <img src="https://raw.githubusercontent.com/onorhime/kissmyapps-mobile/main/.github/assets/kissmyapps.png" width="88" height="88" alt="KissMyApps">
4
+ </a>
5
+ </p>
2
6
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
7
+ <h1 align="center">KissMyApps for React Native</h1>
8
+
9
+ <p align="center">
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
+ </p>
13
+
14
+ <p align="center">
15
+ <a href="https://www.npmjs.com/package/@kissmyappss/react-native"><img src="https://img.shields.io/npm/v/@kissmyappss/react-native?color=ff80bf&labelColor=222222" alt="npm"></a>
16
+ <img src="https://img.shields.io/badge/React%20Native-0.70%2B-ff80bf?logo=react&logoColor=white&labelColor=222222" alt="React Native 0.70+">
17
+ <img src="https://img.shields.io/badge/Expo-ready-ff80bf?logo=expo&logoColor=white&labelColor=222222" alt="Expo">
18
+ <img src="https://img.shields.io/badge/TypeScript-included-ff80bf?logo=typescript&logoColor=white&labelColor=222222" alt="TypeScript">
19
+ <img src="https://img.shields.io/badge/license-MIT-ff80bf?labelColor=222222" alt="MIT licence">
20
+ </p>
21
+
22
+ ---
23
+
24
+ ## Why this SDK
25
+
26
+ - **Start it and you are done.** Installs, updates, opens, time in the app and sessions are
27
+ recorded on their own; React Navigation screens take one line.
28
+ - **Nothing is lost offline.** Events wait in storage, survive a restart and go out with
29
+ backoff once there is a connection.
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.
36
+ - **Respectful by default.** A random ID per install, no advertising ID, no fingerprinting,
37
+ and an opt-out that is remembered across launches.
38
+ - **One dashboard for every platform.** It sends the same events as the
39
+ [iOS and Android SDKs](https://github.com/onorhime/kissmyapps-mobile) and the web script.
40
+
41
+ ## Install
42
+
43
+ ```sh
44
+ npm install @kissmyappss/react-native @react-native-async-storage/async-storage
45
+ ```
46
+
47
+ With Expo, `npx expo install @kissmyappss/react-native @react-native-async-storage/async-storage`.
48
+
49
+ You need React Native 0.70 or later, and a **client key** from your project in the
50
+ KissMyApps console under **Settings → API keys**. Keys starting `kma_pk_live_` count as
51
+ production; keys starting `kma_pk_test_` are kept apart as development.
52
+
53
+ ## Quick start
54
+
55
+ Start the SDK once, as early as possible, for example at the top of `App.tsx`:
56
+
57
+ ```tsx
58
+ import AsyncStorage from '@react-native-async-storage/async-storage'
59
+ import { KissMyApps } from '@kissmyappss/react-native'
60
+
61
+ KissMyApps.init({
62
+ key: 'kma_pk_live_…',
63
+ storage: AsyncStorage,
64
+ appVersion: '2.4.0', // for example DeviceInfo.getVersion()
65
+ build: '120', // and DeviceInfo.getBuildNumber()
66
+ })
67
+ ```
68
+
69
+ <details>
70
+ <summary>Version and build with Expo</summary>
71
+
72
+ ```tsx
73
+ import * as Application from 'expo-application'
74
+
75
+ KissMyApps.init({
76
+ key: 'kma_pk_live_…',
77
+ storage: AsyncStorage,
78
+ appVersion: Application.nativeApplicationVersion ?? undefined,
79
+ build: Application.nativeBuildVersion ?? undefined,
80
+ })
81
+ ```
82
+
83
+ </details>
84
+
85
+ Storage is what lets the SDK recognise a returning person and keep events through a restart.
86
+ Without it the SDK still works, but every launch counts as a new install (and installs are
87
+ not matched to links).
88
+
89
+ ## Track what matters
90
+
91
+ ### Screens
92
+
93
+ With React Navigation, pass the helper to the container and every screen is recorded under
94
+ its route name:
95
+
96
+ ```tsx
97
+ import { NavigationContainer, useNavigationContainerRef } from '@react-navigation/native'
98
+ import { trackNavigation } from '@kissmyappss/react-native'
99
+
100
+ export function App() {
101
+ const navigation = useNavigationContainerRef()
102
+ return (
103
+ <NavigationContainer ref={navigation} {...trackNavigation(navigation)}>
104
+ {/* your navigators */}
105
+ </NavigationContainer>
106
+ )
107
+ }
108
+ ```
109
+
110
+ Without React Navigation, call `KissMyApps.screen('Lesson')` when a screen appears.
111
+
112
+ ### Events and people
113
+
114
+ ```ts
115
+ KissMyApps.track('lesson_completed', { lesson: 3, score: 0.92 })
116
+
117
+ KissMyApps.identify('user-42', { email: 'amaka@example.com', plan: 'annual' })
118
+ KissMyApps.setTraits({ plan: 'monthly' })
119
+ KissMyApps.reset() // on sign out: what follows belongs to a new, anonymous person
120
+
121
+ KissMyApps.optOut() // stops sending, remembered across launches
122
+ KissMyApps.optIn()
123
+ await KissMyApps.flush()
124
+ ```
125
+
126
+ Event names use letters, numbers and `_ . : -`, start with a letter and are up to 80
127
+ characters; other names are ignored. Calls made before `init` are kept and run once it is
128
+ called.
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
+
167
+ ### Everything at a glance
168
+
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.
290
+
291
+ ## What gets recorded
292
+
293
+ | Event | When | Properties |
294
+ | ------------------ | ------------------------------------------ | -------------------------------------------------------- |
295
+ | `session_started` | A new session begins | – |
296
+ | `app_installed` | The first launch after install | `version`, `build` |
297
+ | `app_updated` | The first launch of a new version or build | `version`, `build`, `previous_version`, `previous_build` |
298
+ | `app_opened` | The app comes to the foreground | `from_background` |
299
+ | `app_backgrounded` | The app leaves the foreground | `seconds_in_foreground` |
300
+ | `screen_viewed` | A screen appears | `name`, `previous`, plus your own |
301
+
302
+ Every request also carries iOS or Android and the OS version, phone or tablet, the device
303
+ model on Android (iPhone or iPad on iOS), screen size, language, time zone, app version and
304
+ the SDK version. Country, region and city are worked out by the KissMyApps server from the
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).
308
+
309
+ A session ends after 30 minutes in the background or without events. Events are sent every
310
+ 10 seconds, at once when 30 are waiting, and when the app goes to the background. While
311
+ offline they wait in storage (up to 1,000, oldest dropped first) and are retried with
312
+ backoff, including on the next launch.
313
+
314
+ ## Options
315
+
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. |
331
+
332
+ ## License
333
+
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
+ }