gomarketme-react-native 1.0.5 → 1.0.6

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/README.md ADDED
@@ -0,0 +1,53 @@
1
+ <div align="center">
2
+ <img src="https://static.gomarketme.net/assets/gmm-icon.png" alt="GoMarketMe"/>
3
+ <br>
4
+ <h1>gomarketme-react-native</h1>
5
+ <p>Affiliate Marketing for React Native-Based iOS and Android Apps.</p>
6
+ </div>
7
+
8
+ ## Installation
9
+
10
+ ### Using npm
11
+
12
+ ```bash
13
+ npm install gomarketme-react-native
14
+ ```
15
+
16
+ ### Using yarn
17
+
18
+ ```bash
19
+ yarn add gomarketme-react-native
20
+ ```
21
+
22
+ ### Using pnpm
23
+
24
+ ```bash
25
+ pnpm add gomarketme-react-native
26
+ ```
27
+
28
+
29
+ ## Usage
30
+
31
+ To initialize GoMarketMe, import the `gomarketme` package and create a new instance of `GoMarketMe`:
32
+
33
+ ```tsx
34
+ import GoMarketMe from 'gomarketme-react-native';
35
+
36
+ const App: React.FC = () => {
37
+ const apiKey = 'YOUR_API_KEY_HERE';
38
+
39
+ useEffect(() => {
40
+ const initializeGoMarketMe = async () => {
41
+ await GoMarketMe.initialize(apiKey);
42
+ };
43
+
44
+ initializeGoMarketMe();
45
+ }, []);
46
+ };
47
+ ```
48
+
49
+ Make sure to replace API_KEY with your actual GoMarketMe API key. You can find it on the product onboarding page and under Profile > API Key.
50
+
51
+ ## Support
52
+
53
+ If you encounter any problems or issues, please contact us at [integrations@gomarketme.co](mailto:integrations@gomarketme.co) or visit [https://gomarketme.co](https://gomarketme.co).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gomarketme-react-native",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
4
4
  "description": "Affiliate Marketing for React Native-Based iOS and Android Apps.",
5
5
  "main": "index.js",
6
6
  "homepage": "https://gomarketme.co",
package/src/index.ts CHANGED
@@ -1,16 +1,256 @@
1
- // src/index.ts
2
- import { NativeModules } from 'react-native';
1
+ import { Platform, Dimensions, PixelRatio } from 'react-native';
2
+ import DeviceInfo from 'react-native-device-info';
3
+ import * as RNLocalize from 'react-native-localize';
4
+ import AsyncStorage from '@react-native-async-storage/async-storage';
5
+ import InAppPurchase, { Purchase, Product } from 'react-native-iap';
6
+ import axios from 'axios';
3
7
 
4
- const { MySDK } = NativeModules;
8
+ class GoMarketMe {
9
+ private static instance: GoMarketMe;
10
+ private sdkInitializedKey = 'GOMARKETME_SDK_INITIALIZED';
11
+ private affiliateCampaignCode = '';
12
+ private deviceId = '';
13
+ private sdkInitializationUrl = 'https://api.gomarketme.net/v1/sdk-initialization';
14
+ private systemInfoUrl = 'https://api.gomarketme.net/v1/mobile/system-info';
15
+ private eventUrl = 'https://api.gomarketme.net/v1/event';
5
16
 
6
- interface MySDKInterface {
7
- someMethod(param: string): Promise<string>;
8
- }
17
+ private constructor() {}
18
+
19
+ public static getInstance(): GoMarketMe {
20
+ if (!GoMarketMe.instance) {
21
+ GoMarketMe.instance = new GoMarketMe();
22
+ }
23
+ return GoMarketMe.instance;
24
+ }
25
+
26
+ public async initialize(apiKey: string): Promise<void> {
27
+ try {
28
+ const isSDKInitialized = await this.isSDKInitialized();
29
+ if (!isSDKInitialized) {
30
+ await this.postSDKInitialization(apiKey);
31
+ }
32
+ const systemInfo = await this.getSystemInfo();
33
+ await this.postSystemInfo(systemInfo, apiKey);
34
+ await this.addListener(apiKey);
35
+ } catch (e) {
36
+ console.error('Error initializing GoMarketMe:', e);
37
+ }
38
+ }
39
+
40
+ private async addListener(apiKey: string): Promise<void> {
41
+ InAppPurchase.purchaseUpdatedListener(async (purchase: Purchase) => {
42
+ if (this.affiliateCampaignCode != '') {
43
+ const productIds = await this.fetchPurchases([purchase], apiKey);
44
+ await this.fetchPurchaseProducts(productIds, apiKey);
45
+ }
46
+ });
47
+ }
48
+
49
+ private async getSystemInfo(): Promise<any> {
50
+ const deviceData = Platform.select({
51
+ ios: await this.readIosDeviceInfo(),
52
+ android: await this.readAndroidDeviceInfo(),
53
+ });
54
+
55
+ const devicePixelRatio = PixelRatio.get();
56
+
57
+ const windowData = {
58
+ devicePixelRatio: devicePixelRatio,
59
+ width: Dimensions.get('window').width * devicePixelRatio,
60
+ height: Dimensions.get('window').height * devicePixelRatio,
61
+ };
62
+
63
+ return {
64
+ device_info: deviceData,
65
+ window_info: windowData,
66
+ time_zone_code: this.getTimeZoneCode(),
67
+ language_code: this.getLanguageCode(),
68
+ };
69
+ }
70
+
71
+ private async postSDKInitialization(apiKey: string): Promise<void> {
72
+ try {
73
+ const response = await axios.post(this.sdkInitializationUrl, {}, {
74
+ headers: {
75
+ 'Content-Type': 'application/json',
76
+ 'x-api-key': apiKey,
77
+ },
78
+ });
79
+ if (response.status === 200) {
80
+ await this.markSDKAsInitialized();
81
+ } else {
82
+ console.error('Failed to mark SDK as Initialized. Status code:', response.status);
83
+ }
84
+ } catch (e) {
85
+ console.error('Error sending SDK information to server:', e);
86
+ }
87
+ }
88
+
89
+ private async postSystemInfo(systemInfo: any, apiKey: string): Promise<void> {
90
+ try {
91
+ const response = await axios.post(this.systemInfoUrl, systemInfo, {
92
+ headers: {
93
+ 'Content-Type': 'application/json',
94
+ 'x-api-key': apiKey,
95
+ },
96
+ });
97
+ if (response.status === 200) {
98
+ const responseData = response.data;
99
+ if (responseData.affiliate_campaign_code) {
100
+ this.affiliateCampaignCode = responseData.affiliate_campaign_code;
101
+ }
102
+ if (responseData.device_id) {
103
+ this.deviceId = responseData.device_id;
104
+ }
105
+ } else {
106
+ console.error('Failed to send system info. Status code:', response.status);
107
+ }
108
+ } catch (e) {
109
+ console.error('Error sending system info to server:', e);
110
+ }
111
+ }
112
+
113
+ private async readAndroidDeviceInfo(): Promise<any> {
114
+ return {
115
+ deviceId: await DeviceInfo.getAndroidId(),
116
+ _deviceId: await DeviceInfo.getDeviceId(),
117
+ systemName: await DeviceInfo.getSystemName(),
118
+ systemVersion: await DeviceInfo.getSystemVersion(),
119
+ brand: await DeviceInfo.getBrand(),
120
+ model: await DeviceInfo.getModel(),
121
+ manufacturer: await DeviceInfo.getManufacturer(),
122
+ isEmulator: await DeviceInfo.isEmulator(),
123
+ uniqueId: await DeviceInfo.getUniqueId(),
124
+ };
125
+ }
9
126
 
10
- const MySDKWrapper: MySDKInterface = {
11
- someMethod: async (param) => {
12
- return MySDK.someMethod(param);
13
- },
14
- };
127
+ private async readIosDeviceInfo(): Promise<any> {
128
+ var info = {
129
+ deviceId: await DeviceInfo.getUniqueId(),
130
+ _deviceId: await DeviceInfo.getDeviceId(),
131
+ systemName: await DeviceInfo.getSystemName(),
132
+ systemVersion: await DeviceInfo.getSystemVersion(),
133
+ brand: await DeviceInfo.getBrand(),
134
+ model: await DeviceInfo.getModel(),
135
+ manufacturer: await DeviceInfo.getManufacturer(),
136
+ isEmulator: await DeviceInfo.isEmulator(),
137
+ uniqueId: await DeviceInfo.getUniqueId(),
138
+ };
139
+ }
140
+
141
+ private getTimeZoneCode(): string {
142
+ // Convert the time zone to GMT format (e.g., "GMT+2")
143
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
144
+ const date = new Date();
145
+ const timezoneOffset = date.getTimezoneOffset(); // in minutes
146
+ const absOffset = Math.abs(timezoneOffset);
147
+ const hours = Math.floor(absOffset / 60);
148
+ const minutes = absOffset % 60;
149
+ const sign = timezoneOffset > 0 ? '-' : '+';
150
+ return `GMT${sign}${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`; // Return GMT format
151
+ }
152
+
153
+ private getLanguageCode(): string {
154
+ const locales = RNLocalize.getLocales();
155
+ return locales.length > 0 ? locales[0].languageTag : 'en-US';
156
+ }
157
+
158
+ private async fetchPurchases(purchaseDetailsList: Purchase[], apiKey: string): Promise<string[]> {
159
+ const productIds: string[] = [];
160
+ for (const purchase of purchaseDetailsList) {
161
+ if (purchase.transactionReceipt) {
162
+ await this.sendEventToServer(JSON.stringify(this.serializePurchaseDetails(purchase)), 'purchase', apiKey);
163
+ if (purchase.productId && !productIds.includes(purchase.productId)) {
164
+ productIds.push(purchase.productId);
165
+ }
166
+ }
167
+ }
168
+ return productIds;
169
+ }
170
+
171
+ private async fetchPurchaseProducts(productIds: string[], apiKey: string): Promise<void> {
172
+ try {
173
+ const products = await InAppPurchase.getProducts({skus: productIds});
174
+ if (products.length > 0) {
175
+ for (const product of products) {
176
+ await this.sendEventToServer(JSON.stringify(this.serializeProductDetails(product)), 'product', apiKey);
177
+ }
178
+ } else {
179
+ await this.sendEventToServer(JSON.stringify({ notFoundIDs: productIds.join(',') }), 'product', apiKey);
180
+ }
181
+ } catch (e) {
182
+ console.error('Error fetching products:', e);
183
+ }
184
+ }
185
+
186
+ private async sendEventToServer(body: string, eventType: string, apiKey: string): Promise<void> {
187
+ try {
188
+ const response = await axios.post(this.eventUrl, body, {
189
+ headers: {
190
+ 'Content-Type': 'application/json',
191
+ 'x-affiliate-campaign-code': this.affiliateCampaignCode,
192
+ 'x-device-id': this.deviceId,
193
+ 'x-event-type': eventType,
194
+ 'x-product-type': Platform.OS,
195
+ 'x-source-name': Platform.OS === 'android' ? 'google_play' : 'app_store',
196
+ 'x-api-key': apiKey,
197
+ },
198
+ });
199
+ if (response.status === 200) {
200
+ console.log(`${eventType} sent successfully`);
201
+ } else {
202
+ console.error(`Failed to send ${eventType}. Status code:`, response.status);
203
+ }
204
+ } catch (e) {
205
+ console.error(`Error sending ${eventType} to server:`, e);
206
+ }
207
+ }
208
+
209
+ private serializePurchaseDetails(purchase: Purchase): any {
210
+ return {
211
+ productID: purchase.productId,
212
+ purchaseID: purchase.transactionId || '',
213
+ transactionDate: purchase.transactionDate || '',
214
+ status: Platform.select({
215
+ ios: (purchase as any).transactionStateIOS, // Removed non-existent properties
216
+ android: (purchase as any).purchaseStateAndroid,
217
+ }),
218
+ verificationData: {
219
+ localVerificationData: purchase.transactionReceipt,
220
+ },
221
+ };
222
+ }
223
+
224
+ private serializeProductDetails(product: Product): any {
225
+ return {
226
+ productID: product.productId,
227
+ productTitle: product.title,
228
+ productDescription: product.description,
229
+ productPrice: product.price,
230
+ productRawPrice: product.price,
231
+ productCurrencyCode: product.currency,
232
+ };
233
+ }
234
+
235
+ private async markSDKAsInitialized(): Promise<boolean> {
236
+ try {
237
+ await AsyncStorage.setItem(this.sdkInitializedKey, 'true');
238
+ return true;
239
+ } catch (e) {
240
+ console.error('Failed to save SDK initialization:', e);
241
+ return false;
242
+ }
243
+ }
244
+
245
+ private async isSDKInitialized(): Promise<boolean> {
246
+ try {
247
+ const value = await AsyncStorage.getItem(this.sdkInitializedKey);
248
+ return value === 'true';
249
+ } catch (e) {
250
+ console.error('Failed to load SDK initialization:', e);
251
+ return false;
252
+ }
253
+ }
254
+ }
15
255
 
16
- export default MySDKWrapper;
256
+ export default GoMarketMe.getInstance();
package/dist/index.js DELETED
@@ -1,49 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- // src/index.ts
40
- var react_native_1 = require("react-native");
41
- var MySDK = react_native_1.NativeModules.MySDK;
42
- var MySDKWrapper = {
43
- someMethod: function (param) { return __awaiter(void 0, void 0, void 0, function () {
44
- return __generator(this, function (_a) {
45
- return [2 /*return*/, MySDK.someMethod(param)];
46
- });
47
- }); },
48
- };
49
- exports.default = MySDKWrapper;