-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathiap-manager.js
More file actions
215 lines (182 loc) · 6.02 KB
/
iap-manager.js
File metadata and controls
215 lines (182 loc) · 6.02 KB
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
import IAP from 'ti.iap';
const InAppPurchaseProduct = {
MY_SUBSCRIPTION_PRODUCT_ID: 'com.company.app.subscription-product',
MY_CONSUMABLE_PRODUDCT_ID: 'com.company.app.consumable-product'
};
let purchaseResolver;
let purchaseRejecter;
let selectedProduct;
let isBillingInitialized = false;
export default class InAppPurchaseManager {
static prepare() {
if (OS_ANDROID) {
IAP.addEventListener('connectionUpdate', InAppPurchaseManager._onConnectionUpdate);
IAP.addEventListener('purchaseUpdate', InAppPurchaseManager._onPurchaseUpdated);
IAP.initialize();
}
}
static shutdown() {
if (!OS_ANDROID) { return; }
IAP.disconnect();
isBillingInitialized = false;
}
static get isReady() {
return isBillingInitialized;
}
static async getProductInfos() {
return new Promise(async (resolve, reject) => {
if (OS_ANDROID) {
try {
const inAppPurchases = await InAppPurchaseManager.getAndroidProducts(IAP.SKU_TYPE_INAPP);
const subscriptions = await InAppPurchaseManager.getAndroidProducts(IAP.SKU_TYPE_SUBS);
resolve([...inAppPurchases, ...subscriptions]);
} catch (error) {
reject(error);
}
} else {
IAP.retrieveProductsInfo({
identifiers: Object.values(InAppPurchaseProduct),
callback: function (event) {
if (!event.success && !event.retrievedProducts) {
reject(event);
} else {
resolve(event.retrievedProducts);
}
}
});
}
});
}
static async getAndroidProducts(productType) {
return new Promise((resolve, reject) => {
IAP.retrieveProductsInfo({
productType,
productIdList: Object.values(InAppPurchaseProduct),
callback: event => {
if (!event.success) {
reject();
} else {
resolve(InAppPurchaseManager.mappedAndroidProductList(event.productList));
}
}
});
})
}
static async presentCodeRedemptionSheet(code) {
if (OS_ANDROID) {
// Not supported natively so far
} else {
const { index} = await Utils.showAlert({ title: 'The code has been copied to your clipboard!' });
if (index === -1) { return; }
Ti.UI.Clipboard.setText(code);
IAP.presentCodeRedemptionSheet();
}
}
static async purchase(product) {
Ti.API.warn(`** Purchasing in app product (${product.identifier}) **`);
return new Promise((resolve, reject) => {
if (OS_ANDROID) {
if (!isBillingInitialized) {
alert('Google Pay is not ready so far!');
return;
}
purchaseResolver = resolve;
purchaseRejecter = reject;
selectedProduct = product;
IAP.purchase({
identifier: product.identifier,
// Optional: pass subscription update parameters
// oldPurchaseToken: '',
// subscriptionReplacementMode: IAP.REPLACEMENT_MODE_CHARGE_FULL_PRICE,
// originalExternalTransactionId: ''
});
} else {
IAP.purchase({
identifier: product.identifier,
applicationUsername: Alloy.Models.user.get('identifier'),
quantity: 1,
atomically: true,
callback: event => {
if (!event.success) {
reject(event);
return;
}
Ti.API.warn('** Purchase successful for *' + product.identifier + ', validating purchase on server … *');
console.warn(JSON.stringify(event, null, 4));
console.warn('TODO: Post subscription to server to validate it there');
}
});
}
});
}
// ---- Android-only events ----
static _onConnectionUpdate(event) {
isBillingInitialized = event.success;
}
static _onPurchaseUpdated(event) {
console.warn('** Purchase updated!');
console.warn(JSON.stringify(event, null, 4));
function submitSubscription() {
console.warn('TODO: Post subscription to server to validate it there');
}
if (!event.success) {
purchaseRejecter && purchaseRejecter(event);
purchaseRejecter = undefined;
selectedProduct = undefined;
return;
}
if (event.purchaseList.length === 0) {
purchaseRejecter && purchaseRejecter(event);
purchaseRejecter = undefined;
selectedProduct = undefined;
return;
}
const purchaseDetails = event.purchaseList[event.purchaseList.length - 1];
// Android needs to acknowledge purchases (!)
if (purchaseDetails.purchaseState === IAP.PURCHASE_STATE_PURCHASED) {
if (!purchaseDetails.isAcknowledged) {
Ti.API.warn('** Acknowledging ' + purchaseDetails.productId + '…');
// A bit hacky way to use a different signature based on the product
// TODO: Pass a flag IN_APP / SUBS to identify the correct method internally
const method = [ InAppPurchaseProduct.MY_SUBSCRIPTION_PRODUCT_ID ].includes(purchaseDetails.productId) ? 'acknowledgeNonConsumableProduct' : 'acknowledgeConsumableProduct';
IAP[method]({
purchaseToken: purchaseDetails.purchaseToken,
callback: purchaseResult => {
Ti.API.warn('** Acknowledgement done for *' + purchaseDetails.productId + '* : ' + purchaseResult.success);
// For some very rare cases, the "success" flag can be false, but the token may still be valid
const success = purchaseResult.success || !!purchaseResult.purchaseToken;
if (success) {
Ti.API.warn('** Purchase successful for *' + purchaseDetails.productId + ', validating purchase on server … *');
submitSubscription();
} else {
purchaseRejecter && purchaseRejecter(event);
purchaseRejecter = undefined;
selectedProduct = undefined;
}
}
});
} else {
submitSubscription();
Ti.API.warn('** Purchase acknowledged & successful for *' + purchaseDetails.productId + '*');
}
} else if (purchaseDetails.purchaseState === IAP.PURCHASE_STATE_PENDING) {
Ti.API.warn('** Purchase still pending! *');
Utils.showAlert({
title: L('purchase_pending'),
message: L('purchase_pending_message'),
buttonNames: [ L('alrighty') ]
});
}
}
static mappedAndroidProductList(productList) {
return productList.map(product => {
return {
localizedTitle: product.title,
identifier: product.productId,
localizedPrice: product.originalPrice,
price: product.priceAmountMicros / 1000000,
priceCurrencyCode: product.priceCurrencyCode
}
});
}
}