forked from j3k0/cordova-plugin-purchase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInAppPurchase.js
347 lines (310 loc) · 11.9 KB
/
InAppPurchase.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
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
/**
* A plugin to enable iOS In-App Purchases.
*
* Copyright (c) Matt Kane 2011
* Copyright (c) Guillaume Charhon 2012
* Copyright (c) Jean-Christophe Hoelt 2013
*/
var exec = function (methodName, options, success, error) {
cordova.exec(success, error, "InAppPurchase", methodName, options);
};
var protectCall = function (callback, context) {
try {
var args = Array.prototype.slice.call(arguments, 2);
callback.apply(this, args);
}
catch (err) {
log('exception in ' + context + ': "' + err + '"');
}
};
var InAppPurchase = function () {
this.options = {};
};
var noop = function () {};
var log = noop;
// Error codes
// (keep synchronized with InAppPurchase.m)
var ERROR_CODES_BASE = 4983497;
InAppPurchase.prototype.ERR_SETUP = ERROR_CODES_BASE + 1;
InAppPurchase.prototype.ERR_LOAD = ERROR_CODES_BASE + 2;
InAppPurchase.prototype.ERR_PURCHASE = ERROR_CODES_BASE + 3;
InAppPurchase.prototype.ERR_LOAD_RECEIPTS = ERROR_CODES_BASE + 4;
InAppPurchase.prototype.ERR_CLIENT_INVALID = ERROR_CODES_BASE + 5;
InAppPurchase.prototype.ERR_PAYMENT_CANCELLED = ERROR_CODES_BASE + 6;
InAppPurchase.prototype.ERR_PAYMENT_INVALID = ERROR_CODES_BASE + 7;
InAppPurchase.prototype.ERR_PAYMENT_NOT_ALLOWED = ERROR_CODES_BASE + 8;
InAppPurchase.prototype.ERR_UNKNOWN = ERROR_CODES_BASE + 10;
InAppPurchase.prototype.init = function (options) {
this.options = {
error: options.error || noop,
ready: options.ready || noop,
purchase: options.purchase || noop,
purchaseEnqueued: options.purchaseEnqueued || noop,
finish: options.finish || noop,
restore: options.restore || noop,
restoreFailed: options.restoreFailed || noop,
restoreCompleted: options.restoreCompleted || noop
};
this.receiptForTransaction = {};
this.receiptForProduct = {};
if (window.localStorage && window.localStorage.sk_receiptForTransaction)
this.receiptForTransaction = JSON.parse(window.localStorage.sk_receiptForTransaction);
if (window.localStorage && window.localStorage.sk_receiptForProduct)
this.receiptForProduct = JSON.parse(window.localStorage.sk_receiptForProduct);
if (options.debug) {
exec('debug', [], noop, noop);
log = function (msg) {
console.log("InAppPurchase[js]: " + msg);
};
}
if (options.noAutoFinish) {
exec('noAutoFinish', [], noop, noop);
}
var that = this;
var setupOk = function () {
log('setup ok');
protectCall(that.options.ready, 'options.ready');
// Is there a reason why we wouldn't like to do this automatically?
// YES! it does ask the user for his password.
// that.restore();
};
var setupFailed = function () {
log('setup failed');
protectCall(options.error, 'options.error', InAppPurchase.prototype.ERR_SETUP, 'Setup failed');
};
exec('setup', [], setupOk, setupFailed);
};
/**
* Makes an in-app purchase.
*
* @param {String} productId The product identifier. e.g. "com.example.MyApp.myproduct"
* @param {int} quantity
*/
InAppPurchase.prototype.purchase = function (productId, quantity) {
quantity = (quantity|0) || 1;
var options = this.options;
// Many people forget to load information about their products from apple's servers before allowing
// users to purchase them... leading them to spam us with useless issues and comments.
// Let's chase them down!
if ((!InAppPurchase._productIds) || (InAppPurchase._productIds.indexOf(productId) < 0)) {
var msg = 'Purchasing ' + productId + ' failed. Ensure the product was loaded first with storekit.load(...)!';
log(msg);
if (typeof options.error === 'function') {
protectCall(options.error, 'options.error', InAppPurchase.prototype.ERR_PURCHASE, 'Trying to purchase a unknown product.', productId, quantity);
}
return;
}
var purchaseOk = function () {
log('Purchased ' + productId);
if (typeof options.purchaseEnqueued === 'function') {
protectCall(options.purchaseEnqueued, 'options.purchaseEnqueued', productId, quantity);
}
};
var purchaseFailed = function () {
var msg = 'Purchasing ' + productId + ' failed';
log(msg);
if (typeof options.error === 'function') {
protectCall(options.error, 'options.error', InAppPurchase.prototype.ERR_PURCHASE, msg, productId, quantity);
}
};
return exec('purchase', [productId, quantity], purchaseOk, purchaseFailed);
};
/**
* Asks the payment queue to restore previously completed purchases.
* The restored transactions are passed to the onRestored callback, so make sure you define a handler for that first.
*
*/
InAppPurchase.prototype.restore = function() {
this.needRestoreNotification = true;
return exec('restoreCompletedTransactions', []);
};
/**
* Retrieves localized product data, including price (as localized
* string), name, description of multiple products.
*
* @param {Array} productIds
* An array of product identifier strings.
*
* @param {Function} callback
* Called once with the result of the products request. Signature:
*
* function(validProducts, invalidProductIds)
*
* where validProducts receives an array of objects of the form:
*
* {
* id: "<productId>",
* title: "<localised title>",
* description: "<localised escription>",
* price: "<localised price>"
* }
*
* and invalidProductIds receives an array of product identifier
* strings which were rejected by the app store.
*/
InAppPurchase.prototype.load = function (productIds, callback) {
var options = this.options;
if (typeof productIds === "string") {
productIds = [productIds];
}
if (!productIds) {
// Empty array, nothing to do.
protectCall(callback, 'load.callback', [], []);
}
else if (!productIds.length) {
// Empty array, nothing to do.
protectCall(callback, 'load.callback', [], []);
}
else {
if (typeof productIds[0] !== 'string') {
var msg = 'invalid productIds given to store.load: ' + JSON.stringify(productIds);
log(msg);
protectCall(options.error, 'options.error', InAppPurchase.prototype.ERR_LOAD, msg);
return;
}
log('load ' + JSON.stringify(productIds));
var loadOk = function (array) {
var valid = array[0];
var invalid = array[1];
log('load ok: { valid:' + JSON.stringify(valid) + ' invalid:' + JSON.stringify(invalid) + ' }');
protectCall(callback, 'load.callback', valid, invalid);
};
var loadFailed = function (errMessage) {
log('load failed: ' + errMessage);
protectCall(options.error, 'options.error', InAppPurchase.prototype.ERR_LOAD, 'Failed to load product data: ' + errMessage);
};
InAppPurchase._productIds = productIds;
exec('load', [productIds], loadOk, loadFailed);
}
};
/**
* Finish an unfinished transaction.
*
* @param {String} transactionId
* Identifier of the transaction to finish.
*
* You have to call this method manually when using the noAutoFinish option.
*/
InAppPurchase.prototype.finish = function (transactionId) {
exec('finishTransaction', [transactionId], noop, noop);
};
/* This is called from native.*/
InAppPurchase.prototype.updatedTransactionCallback = function (state, errorCode, errorText, transactionIdentifier, productId, transactionReceipt) {
if (transactionReceipt) {
this.receiptForProduct[productId] = transactionReceipt;
this.receiptForTransaction[transactionIdentifier] = transactionReceipt;
if (window.localStorage) {
window.localStorage.sk_receiptForProduct = JSON.stringify(this.receiptForProduct);
window.localStorage.sk_receiptForTransaction = JSON.stringify(this.receiptForTransaction);
}
}
switch(state) {
case "PaymentTransactionStatePurchased":
protectCall(this.options.purchase, 'options.purchase', transactionIdentifier, productId);
return;
case "PaymentTransactionStateFailed":
protectCall(this.options.error, 'options.error', errorCode, errorText);
return;
case "PaymentTransactionStateRestored":
protectCall(this.options.restore, 'options.restore', transactionIdentifier, productId);
return;
case "PaymentTransactionStateFinished":
protectCall(this.options.finish, 'options.finish', transactionIdentifier, productId);
return;
}
};
InAppPurchase.prototype.restoreCompletedTransactionsFinished = function () {
if (this.needRestoreNotification)
delete this.needRestoreNotification;
else
return;
protectCall(this.options.restoreCompleted, 'options.restoreCompleted');
};
InAppPurchase.prototype.restoreCompletedTransactionsFailed = function (errorCode) {
if (this.needRestoreNotification)
delete this.needRestoreNotification;
else
return;
protectCall(this.options.restoreFailed, 'options.restoreFailed', errorCode);
};
InAppPurchase.prototype.loadReceipts = function (callback) {
var that = this;
that.appStoreReceipt = null;
var loaded = function (base64) {
that.appStoreReceipt = base64;
callCallback();
};
var error = function (errMessage) {
log('load failed: ' + errMessage);
protectCall(options.error, 'options.error', InAppPurchase.prototype.ERR_LOAD_RECEIPTS, 'Failed to load receipt: ' + errMessage);
};
var callCallback = function () {
if (callback) {
protectCall(callback, 'loadReceipts.callback', {
appStoreReceipt: that.appStoreReceipt,
forTransaction: function (transactionId) {
return that.receiptForTransaction[transactionId] || null;
},
forProduct: function (productId) {
return that.receiptForProduct[productId] || null;
}
});
}
};
exec('appStoreReceipt', [], loaded, error);
};
/*
InAppPurchase.prototype.verifyReceipt = function (success, error) {
var receiptOk = function () {
log("Receipt validation success");
if (success)
protectCall(success, 'verifyReceipt.success', reason);
};
var receiptError = function (reason) {
log("Receipt validation failed: " + reason);
if (error)
protectCall(error, 'verifyReceipt.error', reason);
};
exec('verifyReceipt', [], receiptOk, receiptError);
};
*/
/*
* This queue stuff is here because we may be sent events before listeners have been registered. This is because if we have
* incomplete transactions when we quit, the app will try to run these when we resume. If we don't register to receive these
* right away then they may be missed. As soon as a callback has been registered then it will be sent any events waiting
* in the queue.
*/
InAppPurchase.prototype.runQueue = function () {
if(!this.eventQueue.length || (!this.onPurchased && !this.onFailed && !this.onRestored)) {
return;
}
var args;
/* We can't work directly on the queue, because we're pushing new elements onto it */
var queue = this.eventQueue.slice();
this.eventQueue = [];
args = queue.shift();
while (args) {
this.updatedTransactionCallback.apply(this, args);
args = queue.shift();
}
if (!this.eventQueue.length) {
this.unWatchQueue();
}
};
InAppPurchase.prototype.watchQueue = function () {
if (this.timer) {
return;
}
this.timer = window.setInterval(function () {
window.storekit.runQueue();
}, 10000);
};
InAppPurchase.prototype.unWatchQueue = function () {
if (this.timer) {
window.clearInterval(this.timer);
this.timer = null;
}
};
InAppPurchase.prototype.eventQueue = [];
InAppPurchase.prototype.timer = null;
module.exports = new InAppPurchase();