-
Notifications
You must be signed in to change notification settings - Fork 2
/
App.tsx
505 lines (470 loc) · 15.3 KB
/
App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
import {
Text,
View,
Alert,
Modal,
Linking,
Platform,
TextInput,
StyleSheet,
ScrollView,
TouchableOpacity,
} from 'react-native';
import React, { useState, useEffect } from 'react';
import messaging, {
FirebaseMessagingTypes,
} from '@react-native-firebase/messaging';
import Ometria from 'react-native-ometria';
import { RESULTS, requestNotifications } from 'react-native-permissions';
import { AuthModalProps } from './models';
import { version, ometria_sdk_version } from '../../package.json';
import { Events, customOmetriaOptions, demoBasketItems } from './data';
import {
getOmetriaTokenFromStorage,
openUrl,
setOmetriaTokenToStorage,
} from './utils';
const App = () => {
// Set this as a state if you want to use the reinitialization feature, otherwise you can use a static token
const [ometriaToken, setOmetriaToken] = useState('');
const [authModal, setAuthModal] = useState(false);
const [evtsModal, setEvtsModal] = useState(false);
const [notificationContent, setNotificationContent] = useState(
'Receive or interract with a notification to see its content here.'
);
/* METHODS */
/**
* Initialize Ometria with the API Token
*
* Additionally you can pass an options object to customize the SDK behavior,
* for example you can set the notification channel name for Android or set the appGroupIdentifier for iOS
*
* @param token String
*/
const handleOmetriaInit = async (token: string) => {
try {
Ometria.initializeWithApiToken(token, customOmetriaOptions).then(
async () => {
setAuthModal(false);
Ometria.isLoggingEnabled(true);
console.log('🎉 Ometria has been initialized!');
// Request Push Notifications permission after Ometria SDK initialization
await requestNotifications(['alert', 'sound', 'badge']).then(
({ status }) => {
console.log('🔔 Push Notification permissions status:', status);
if (status === RESULTS.GRANTED) {
handlePushNotifications();
console.log('🔔 Push Notification permissions granted!');
}
}
);
},
(error) => {
throw error;
}
);
} catch (error) {
console.error('😕 Error: ', error);
}
};
/**
* Handle Push Notifications 🍏 & 🤖
* - A. Provides Ometria SDK with the FCM token
* - B. Listen for new FCM tokens and provide them to the Ometria SDK
* - C. Captures user interaction with push notifications event emmited by the developer
* - D. Handles notification that opened the app from a quit state
* - E. Handles notification that opened the app from a background state
* - F. Subscribe to foreground PN messages
*
* @returns unsubscribeFromMessages function
*/
const handlePushNotifications = () => {
// A. Provides Ometria SDK with the FCM token 🍏 & 🤖
messaging()
.getToken()
.then((pushToken: string) => {
Ometria.onNewToken(pushToken);
console.log('🔑 Firebase token:', pushToken);
});
// B. Listen for new FCM tokens and provide them to the Ometria SDK 🍏 & 🤖
messaging().onTokenRefresh((pushToken: string) =>
Ometria.onNewToken(pushToken)
);
// C. Function that handles user interaction with push notifications event 🍏 & 🤖
const onNotificationOpenedApp = async (
remoteMessage: FirebaseMessagingTypes.RemoteMessage
) => {
console.log('🔔 Notification has been interacted with and opened app.');
setNotificationContent(JSON.stringify(remoteMessage, null, 2));
// TODO: Update RNFB RemoteMessage type that changed in 18.5.0
Ometria.onNotificationOpenedApp(remoteMessage as any); // 🏹 Ometria Event Logged: onNotificationInteracted
// TODO: Update RNFB RemoteMessage type that changed in 18.5.0
const notif = await Ometria.parseNotification(remoteMessage as any);
if (notif?.deepLinkActionUrl) {
Ometria.trackDeepLinkOpenedEvent(notif.deepLinkActionUrl, 'Browser'); // 🏹 Ometria Event Logged: deepLinkOpened
openUrl(notif.deepLinkActionUrl);
}
Ometria.flush();
};
// D. Check for notification that opened the app from a quit state 🍏 & 🤖
messaging()
.getInitialNotification()
.then((remoteMessage) => {
if (remoteMessage) {
console.log('🔔 Notification opened the app from quit state');
onNotificationOpenedApp(remoteMessage);
}
});
// E. Subscribe to notification that opens the app from a background state 🍏 & 🤖
messaging().onNotificationOpenedApp((remoteMessage) => {
if (remoteMessage) {
console.log('🔔 Notification opened the app from background');
onNotificationOpenedApp(remoteMessage);
}
});
// F. Subscribe to foreground PN messages 🍏 & 🤖
const unsubscribeFromMessages = messaging().onMessage(
async (remoteMessage) => {
console.log('📭 Foreground message received:', remoteMessage);
setNotificationContent(JSON.stringify(remoteMessage, null, 2));
// TODO: Update RNFB RemoteMessage type that changed in 18.5.0
Ometria.onNotificationReceived(remoteMessage as any); // 🏹 Ometria Event Logged: onNotificationReceived
/* Keep in mind that foreground notifications are NOT shown to the user.
Instead, you could trigger a local notification or update the in-app UI to signal a new notification.
Read more at: https://rnfirebase.io/messaging/usage#foreground-state-messages
Don't forget to call onNotificationOpenedApp() if you want to handle the notification interaction event
*/
}
);
return unsubscribeFromMessages;
};
/**
* Handle Deeplinking
* @param payload {url: String}
*/
const handleDeepLinking = ({ url }: any) => {
Linking.canOpenURL(url).then((supported) => {
if (supported) {
Ometria.processUniversalLink(url).then(
(response) => {
Alert.alert('🔗 URL processed:', response);
},
(error) => {
console.log(error);
Alert.alert('🔗 Unable to process URL: ' + url);
}
);
}
});
};
/**
* Handle Login by Email or UserId
* @param method {userEmail?: String, customerId?: String}
*/
const handleLogin = (method: { userEmail?: string; userId?: string }) => {
method.userEmail &&
Ometria.trackProfileIdentifiedByEmailEvent(method.userEmail!);
method.userId &&
Ometria.trackProfileIdentifiedByCustomerIdEvent(method.userId!);
setAuthModal(false);
};
/**
* Saving Ometria API Token to Local Storage
*
* - Save token to Local Storage
* - Initialize Ometria SDK
*
* (Optional: You could use a static token instead of Local Storage)
*/
const saveNewOmetriaToken = async (
newToken: string,
initializeWithNewToken: (token: string) => Promise<void>
) => {
if (newToken === '') {
return;
}
await setOmetriaTokenToStorage(newToken);
console.log('🔐 New Token. Ometria will reinitialize');
initializeWithNewToken(newToken);
};
const handleOmetriaTokenInit = async () => {
const savedToken = await getOmetriaTokenFromStorage();
if (savedToken === '') {
// Do not initialize Ometria SDK if there is no token
setAuthModal(true);
return;
}
setOmetriaToken(savedToken);
handleOmetriaInit(savedToken);
console.log('💾 Token from LocalStorage:', savedToken);
};
// EFFECTS
/**
* Initialize with useEffect:
* 1. Ometria init handler with or without reinitialization
* 2. Deeplink handler
*/
useEffect(() => {
// This is optional if you want to use the reinitialization feature
// If not, you can call handleOmetriaInit here directly with the static token as a parameter
handleOmetriaTokenInit();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
const subscribe = Linking.addEventListener('url', handleDeepLinking);
return () => subscribe.remove();
}, []);
return (
<ScrollView style={styles.container}>
<Text style={styles.title}>Ometria React Native Demo {version}</Text>
<Text style={styles.subtitle}>
{Platform.OS === 'android' ? 'Android' : 'iOS'} SDK version{' '}
{ometria_sdk_version[Platform.OS === 'android' ? 'android' : 'ios']}
</Text>
<TouchableOpacity style={styles.btn} onPress={() => setAuthModal(true)}>
<Text style={styles.text}>Change Login Info 🔐 </Text>
</TouchableOpacity>
<TouchableOpacity style={styles.btn} onPress={() => setEvtsModal(true)}>
<Text style={styles.text}>Go to Events 📝</Text>
</TouchableOpacity>
<View>
<Text style={styles.textBold}>🔔 Notification Content: </Text>
<Text>{notificationContent}</Text>
</View>
<EventsModal isVisible={evtsModal} onClose={() => setEvtsModal(false)} />
<AuthModal
isVisible={authModal}
onClose={() => setAuthModal(false)}
onLogin={handleLogin}
/* Only for reinitialization feature */
reinitialization={{
ometriaToken,
setOmetriaToken,
saveNewOmetriaToken,
handleOmetriaInit,
}}
/>
</ScrollView>
);
};
// MODALS
/* <EventsModal />
* A component that lists events and allows you to send them
* */
const EventsModal: React.FC<{
isVisible: boolean;
onClose: () => void;
}> = ({ isVisible, onClose }) => {
const sendEvent = (eventType: string) => {
switch (eventType) {
case Events.ENABLE_LOGGING:
Ometria.isLoggingEnabled(true);
break;
case Events.DEEPLINK_OPENED_EVENT:
Ometria.trackDeepLinkOpenedEvent('/profile', 'ProfileScreen');
break;
case Events.SCREEN_VIEWED:
Ometria.trackScreenViewedEvent('OnboardingScreen', { a: '1', b: '2' });
break;
case Events.HOME_SCREEN_VIEWED:
Ometria.trackHomeScreenViewedEvent();
break;
case Events.PROFILE_IDENTIFIED_BY_EMAIL:
Ometria.trackProfileIdentifiedByEmailEvent('[email protected]');
break;
case Events.PROFILE_IDENTIFIED_BY_CUSTOMER_ID:
Ometria.trackProfileIdentifiedByCustomerIdEvent('test_customer_id');
break;
case Events.PROFILE_DEIDENTIFIED:
Ometria.trackProfileDeidentifiedEvent();
break;
case Events.PRODUCT_VIEWED:
Ometria.trackProductViewedEvent('productId-1');
break;
case Events.PRODUCT_LISTING_VIEWED:
Ometria.trackProductListingViewedEvent('product_list', {});
break;
case Events.BASKET_VIEWED:
Ometria.trackBasketViewedEvent();
break;
case Events.BASKET_UPDATED:
Ometria.trackBasketUpdatedEvent({
totalPrice: 12.0,
id: 'basket_id_eg',
currency: 'USD',
items: demoBasketItems,
link: 'link_eg',
});
break;
case Events.CHECKOUT_STARTED:
Ometria.trackCheckoutStartedEvent('orderId-1');
break;
case Events.ORDER_COMPLETED:
Ometria.trackOrderCompletedEvent('orderId-1', {
totalPrice: 12.0,
currency: 'USD',
items: demoBasketItems,
link: 'link_eg',
id: 'basket_id_eg',
});
break;
case Events.CUSTOM:
Ometria.trackCustomEvent('my_custom_type', {});
break;
case Events.FLUSH:
Ometria.flush();
break;
case Events.CLEAR:
Ometria.clear();
}
};
return (
<Modal
animationType="slide"
transparent={true}
visible={isVisible}
onRequestClose={onClose}
>
<View style={styles.container}>
<Text style={styles.title}>Events 📝</Text>
<TouchableOpacity style={styles.closeBtn} onPress={onClose}>
<Text style={styles.text}>CLOSE EVENTS</Text>
</TouchableOpacity>
<ScrollView>
{Object.values(Events).map((eventValue) => (
<TouchableOpacity
key={eventValue}
style={styles.btn}
onPress={() => sendEvent(eventValue)}
>
<Text style={styles.text}>{eventValue}</Text>
</TouchableOpacity>
))}
</ScrollView>
</View>
</Modal>
);
};
/*
* <AuthModal />
* A component to allow the user to change the login info
* It is used to change the customerId or the userEmail
* It is also used to save a new Ometria API Token if you want to use the reinitialization feature
* */
const AuthModal: React.FC<AuthModalProps> = ({
isVisible,
onClose,
onLogin,
reinitialization,
}) => {
const [userId, setUserId] = useState('');
const [userEmail, setUserEmail] = useState('');
return (
<Modal
animationType="slide"
transparent={true}
visible={isVisible}
onRequestClose={onClose}
>
<View style={styles.container}>
<Text style={styles.title}>Change Login Info 🔐</Text>
<TextInput
style={styles.input}
placeholder="Ometria API TOKEN"
placeholderTextColor="#000"
value={reinitialization.ometriaToken}
onChangeText={reinitialization.setOmetriaToken}
/>
<TouchableOpacity
style={styles.btn}
onPress={() =>
reinitialization.saveNewOmetriaToken(
reinitialization.ometriaToken,
reinitialization.handleOmetriaInit
)
}
>
<Text style={styles.text}>Save Ometria pushToken</Text>
</TouchableOpacity>
<TextInput
style={styles.input}
value={userId}
placeholder="Customer Id"
placeholderTextColor="#000"
onChangeText={setUserId}
/>
<TouchableOpacity
style={styles.btn}
onPress={() => {
onLogin({ userId });
}}
>
<Text style={styles.text}>Login with customer ID</Text>
</TouchableOpacity>
<TextInput
style={styles.input}
placeholder="Email"
value={userEmail}
placeholderTextColor="#000"
onChangeText={setUserEmail}
/>
<TouchableOpacity
style={styles.btn}
onPress={() => onLogin({ userEmail })}
>
<Text style={styles.text}>Login with customer Email</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.closeBtn} onPress={onClose}>
<Text style={styles.text}>Close settings</Text>
</TouchableOpacity>
</View>
</Modal>
);
};
export default App;
// STYLES
const styles = StyleSheet.create({
container: {
flex: 1,
paddingHorizontal: 20,
backgroundColor: 'white',
paddingTop: 50,
},
title: {
fontSize: 18,
marginTop: 20,
marginBottom: 10,
fontWeight: 'bold',
textAlign: 'center',
},
subtitle: {
fontSize: 14,
marginBottom: 20,
textAlign: 'center',
},
text: {
color: '#FFF',
},
textBold: {
fontWeight: 'bold',
paddingVertical: 4,
},
input: {
padding: 12,
color: '#000',
borderColor: '#33323A',
borderWidth: StyleSheet.hairlineWidth,
},
btn: {
padding: 12,
marginVertical: 12,
alignItems: 'center',
backgroundColor: '#1e1f4d',
},
closeBtn: {
padding: 12,
marginVertical: 12,
alignItems: 'center',
backgroundColor: 'grey',
},
});