forked from pedaling/react-native-in-app-purchase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (77 loc) · 2.21 KB
/
index.js
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
import {
NativeModules,
NativeEventEmitter,
DeviceEventEmitter,
Platform,
} from "react-native";
const { RNInAppPurchase } = NativeModules;
const ERROR = {
FETCH_PRODUCTS: "FETCH_PRODUCTS",
PURCHASE: "PURCHASE",
CONNECTION: "CONNECTION",
};
const addListener = (event, listener) =>
Platform.select({
ios: new NativeEventEmitter(RNInAppPurchase),
android: DeviceEventEmitter,
}).addListener(event, listener);
const removeAllListeners = (event) =>
Platform.select({
ios: new NativeEventEmitter(RNInAppPurchase),
android: DeviceEventEmitter,
}).removeAllListeners(event);
const onFetchProducts = (listener) =>
addListener("iap:onFetchProductsSuccess", listener);
const onPurchase = (listener) => addListener("iap:onPurchaseSuccess", listener);
const onError = (listener) => {
if (Platform.OS === "android") {
addListener("iap:onConnectionFailure", (e) =>
listener(Object.assign(e, { type: ERROR.CONNECTION }))
);
}
addListener("iap:onFetchProductsFailure", (e) =>
listener(Object.assign(e, { type: ERROR.FETCH_PRODUCTS }))
);
addListener("iap:onPurchaseFailure", (e) =>
listener(Object.assign(e, { type: ERROR.PURCHASE }))
);
};
const clear = () => {
removeAllListeners("iap:onFetchProductsSuccess");
removeAllListeners("iap:onPurchaseSuccess");
removeAllListeners("iap:onFetchProductsFailure");
removeAllListeners("iap:onPurchaseFailure");
if (Platform.OS === "android") {
removeAllListeners("iap:onConnectionFailure");
}
};
const purchase = (productId, originalPurchaseToken) => {
if (Platform.OS === "android") {
RNInAppPurchase.purchase(productId, originalPurchaseToken || null);
} else {
RNInAppPurchase.purchase(productId);
}
};
const restore = () => {
if (Platform.OS === "ios") {
RNInAppPurchase.restore(null);
}
};
const finalize = (purchase, isConsumable) => {
return Platform.OS === "android"
? RNInAppPurchase.finalize(purchase, isConsumable)
: RNInAppPurchase.finalize(purchase);
};
export default {
configure: RNInAppPurchase.configure,
fetchProducts: RNInAppPurchase.fetchProducts,
flush: RNInAppPurchase.flush,
purchase,
restore,
finalize,
onFetchProducts,
onPurchase,
onError,
clear,
ERROR,
};