Skip to content

Commit 50f6193

Browse files
authored
Merge pull request #7 from logicwind/dev
Added auth-token in createTracker
2 parents 39a587d + d77315b commit 50f6193

File tree

8 files changed

+76
-14
lines changed

8 files changed

+76
-14
lines changed

README.md

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,10 +55,16 @@ trackMediaEvent
5555

5656
### createTracker()
5757

58-
The createTracker function is used to instantiate a tracker object for Matomo analytics within a React Native application .It will take `matomo-url` and `siteId` parameter.
58+
The createTracker function is used to instantiate a tracker object for Matomo analytics within a React Native application .It requires the parameters `matomo-url` and `siteId`, with the optional parameter `auth_token`.
59+
60+
<!-- If you want to create matomo auth_token refere this link https://matomo.org/faq/general/faq_114/ -->
61+
5962
#### note
6063
for matomo-url madatory to add `/matomo.php` end of url.
6164

65+
- **Generate Auth Token**
66+
[Generate auth token guide here](https://matomo.org/faq/general/faq_114/)
67+
6268
#### Examples
6369

6470
```js
@@ -68,6 +74,14 @@ for matomo-url madatory to add `/matomo.php` end of url.
6874
```
6975

7076

77+
#### Examples with Auth Token
78+
79+
```js
80+
81+
createTracker("https://your-matomo-url/matomo.php","siteId","auth_token")
82+
83+
```
84+
7185
### startSession()
7286

7387
The MatomoTracker starts a new session whenever the application starts. If you want to start a new session manually, you can use the startSession() function.
@@ -288,7 +302,7 @@ trackMediaEvent({siteId:"siteid",mediaId:"unique id",mediaTitle:"video media pla
288302

289303
| Method | Required Parameter | Android | ios | Android TV | Apple TV |
290304
|--------------------------------------|-----------------------------------------------------------|:-------:|:---:|:----------:|:--------:|
291-
| [createTracker](#createtracker) | uri: String, siteId: Number |||||
305+
| [createTracker](#createtracker) | uri: String, siteId: Number, token: String |||||
292306
| [startSession](#startsession) | - |||||
293307
| [trackScreen](#trackscreen) | screenName: String, title: String |||||
294308
| [trackEvent](#trackevent) | category:String, action:String, name:String, value:Number |||||
@@ -310,6 +324,28 @@ trackMediaEvent({siteId:"siteid",mediaId:"unique id",mediaTitle:"video media pla
310324
311325
See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. -->
312326

327+
## Troubleshooting
328+
329+
<details>
330+
<summary>How do I fix the tracking failure “Request was not authenticated but should have</summary>
331+
<br>You see a failed tracking request with this error message when you use specific tracking parameters as part of the <a href="https://developer.matomo.org/api-reference/tracking-api">HTTP tracking API</a> without authenticating the request correctly</br>
332+
<br>When such an error occurred, you need to make sure to set a token_auth of a user with at least write permission. If you have set a token, check the set token to make sure it is still the same and no copy/paste error has happened.</br>
333+
334+
<br>To generate a token_auth follow these steps:</br>
335+
336+
* Log in to Matomo
337+
* Go to the Matomo Admin through the top menu
338+
* Click on Personal -> Security
339+
* At the bottom of the page click on “Create new token”
340+
* Confirm your account password
341+
* Enter the purpose for this token
342+
* Choose if the token should only be valid for secure requests (Matomo 5 and newer)
343+
344+
Click on “Create new token”
345+
You will now see the newly created token. Save it somewhere safe as you won’t be able to see it anymore once you leave that screen. For example, save it in a password manager. If you lose it, you will need to generate a new token.
346+
347+
</details>
348+
313349
## License
314350

315351
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE) file for details

android/src/main/java/com/logicwind/reactnativematomotracker/ReactNativeMatomoTrackerModule.kt

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,17 @@ package com.logicwind.reactnativematomotracker
22

33
import android.app.Application
44
import android.content.ContentValues.TAG
5+
import android.os.Build
56
import android.util.Log
7+
import androidx.core.content.pm.PackageInfoCompat
68
import com.facebook.react.bridge.ReactApplicationContext
79
import com.facebook.react.bridge.ReactContextBaseJavaModule
810
import com.facebook.react.bridge.ReactMethod
11+
import okhttp3.MediaType.Companion.toMediaType
912
import okhttp3.OkHttpClient
1013
import okhttp3.Request
14+
import okhttp3.RequestBody.Companion.toRequestBody
1115
import org.matomo.sdk.Matomo
12-
import org.matomo.sdk.TrackMe
1316
import org.matomo.sdk.Tracker
1417
import org.matomo.sdk.TrackerBuilder
1518
import org.matomo.sdk.extra.TrackHelper
@@ -25,6 +28,7 @@ class ReactNativeMatomoTrackerModule(reactContext: ReactApplicationContext) :
2528

2629
private var tracker: Tracker? = null
2730
private val client = OkHttpClient()
31+
private var authToken: String? = null
2832

2933
override fun getName(): String {
3034
return NAME
@@ -37,8 +41,11 @@ class ReactNativeMatomoTrackerModule(reactContext: ReactApplicationContext) :
3741

3842
tracker = TrackerBuilder.createDefault(uri, siteId)
3943
.build(mMatomoTracker)
44+
4045
Log.e(TAG, "initialized successfully! ${tracker}")
4146

47+
48+
4249
} catch (e: Exception) {
4350
Log.e(TAG, "An error occurred: ${e.message}")
4451
}
@@ -52,7 +59,8 @@ class ReactNativeMatomoTrackerModule(reactContext: ReactApplicationContext) :
5259
}
5360

5461
@ReactMethod
55-
fun createTracker(uri:String,siteId:Int) {
62+
fun createTracker(uri:String,siteId:Int,token:String) {
63+
authToken = token;
5664
setTracker(uri,siteId)
5765
}
5866

@@ -175,6 +183,7 @@ class ReactNativeMatomoTrackerModule(reactContext: ReactApplicationContext) :
175183
}
176184
}
177185

186+
178187
@ReactMethod
179188
fun trackMedia(
180189
siteId: String,
@@ -244,8 +253,17 @@ class ReactNativeMatomoTrackerModule(reactContext: ReactApplicationContext) :
244253
}
245254
try {
246255
val urlString = "$baseUrl?$query"
256+
val jsonBody = """
257+
{
258+
"auth_token": "$authToken",
259+
}
260+
""".trimIndent()
261+
262+
val requestBody = jsonBody.toRequestBody("application/json; charset=utf-8".toMediaType())
263+
247264
val request = Request.Builder()
248265
.url(urlString)
266+
.post(requestBody)
249267
.build()
250268

251269
client.newCall(request).execute().use { response ->

example/ios/Podfile.lock

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ PODS:
77
- hermes-engine (0.74.1):
88
- hermes-engine/Pre-built (= 0.74.1)
99
- hermes-engine/Pre-built (0.74.1)
10-
- logicwind-react-native-matomo-tracker (0.3.0):
10+
- logicwind-react-native-matomo-tracker (0.3.2):
1111
- DoubleConversion
1212
- glog
1313
- hermes-engine
@@ -1376,7 +1376,7 @@ SPEC CHECKSUMS:
13761376
fmt: 4c2741a687cc09f0634a2e2c72a838b99f1ff120
13771377
glog: c5d68082e772fa1c511173d6b30a9de2c05a69a2
13781378
hermes-engine: 16b8530de1b383cdada1476cf52d1b52f0692cbc
1379-
logicwind-react-native-matomo-tracker: a370c4497348c4d31730b3d09d474be3d813ef81
1379+
logicwind-react-native-matomo-tracker: 3875a57609e26fb4af6b2998adc3db7421d5acf6
13801380
MatomoTracker: 1f3772a41c27393067d0126071afe6ae1c7f739e
13811381
RCT-Folly: 02617c592a293bd6d418e0a88ff4ee1f88329b47
13821382
RCTDeprecation: efb313d8126259e9294dc4ee0002f44a6f676aba

example/src/App.tsx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ export default function App() {
3535

3636
React.useEffect(() => {
3737
createTracker("https://your-matomo-url/matomo.php", 1) //Replace 1 with your matomo site id
38-
3938
}, []);
4039

4140
return (

ios/ReactNativeMatomoTracker.mm

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
@interface RCT_EXTERN_MODULE(ReactNativeMatomoTracker, NSObject)
44

55

6-
RCT_EXTERN_METHOD(createTracker:(NSString *)uri withSiteId:(NSString *)siteId)
6+
RCT_EXTERN_METHOD(createTracker:(NSString *)uri withSiteId:(NSString *)siteId withToken:(NSString *)token)
77

88
RCT_EXTERN_METHOD(trackScreen:(NSString *)screenName withTitle:(NSString *)title)
99

ios/ReactNativeMatomoTracker.swift

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ class ReactNativeMatomoTracker: NSObject {
66

77
var matomoTracker: MatomoTracker?
88
var baseURL = "";
9+
var authToken = "";
910
var _id = "";
1011
override init() {
1112
super.init()
@@ -16,8 +17,9 @@ class ReactNativeMatomoTracker: NSObject {
1617

1718
}
1819

19-
@objc(createTracker:withSiteId:)
20-
func createTracker(uri:String,siteId:String) {
20+
@objc(createTracker:withSiteId:withToken:)
21+
func createTracker(uri:String,siteId:String,token:String) {
22+
authToken = token
2123
let queue = UserDefaultsQueue(UserDefaults.standard, autoSave: true)
2224
baseURL = uri
2325

@@ -200,7 +202,14 @@ class ReactNativeMatomoTracker: NSObject {
200202
let urlString = "\(baseUrl)?\(query)"
201203

202204
if let url = URL(string: urlString) {
203-
let task = URLSession.shared.dataTask(with: url) { data, response, error in
205+
var request = URLRequest(url: url)
206+
let device = Device.makeCurrentDevice();
207+
let application = Application.makeCurrentApplication()
208+
let userAgent = "Darwin/\(device.darwinVersion ?? "Unknown-Version") (\(device.platform); \(device.operatingSystem) \(device.osVersion)), MatomoTrackerSDK/\(MatomoTracker.sdkVersion)\(application.bundleName ?? "Unknown-App")/\(application.bundleShortVersion ?? "Unknown-Version")";
209+
request.httpMethod = "POST"
210+
request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
211+
request.setValue("\(authToken)", forHTTPHeaderField: "token_auth")
212+
let task = URLSession.shared.dataTask(with: request) { data, response, error in
204213
if let httpResponse = response as? HTTPURLResponse {
205214
let statusCode = httpResponse.statusCode
206215
}

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@logicwind/react-native-matomo-tracker",
3-
"version": "0.3.2",
3+
"version": "0.3.3",
44
"description": "React-native plugin for matomo analytics",
55
"main": "lib/commonjs/index",
66
"module": "lib/module/index",

src/index.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ const ReactNativeMatomoTracker = NativeModules.ReactNativeMatomoTracker
1717
}
1818
);
1919

20-
export function createTracker(uri: String, siteId: Number): Promise<number> {
21-
return ReactNativeMatomoTracker.createTracker(uri, Platform.OS=="ios"?siteId.toString() :siteId);
20+
export function createTracker(uri: String, siteId: Number,token:String=""): Promise<number> {
21+
return ReactNativeMatomoTracker.createTracker(uri, Platform.OS=="ios"?siteId.toString() :siteId,token);
2222
}
2323

2424
export function trackScreen(screenName: String, title: String): Promise<number> {

0 commit comments

Comments
 (0)