forked from Fovea/cordova-plugin-purchase-demo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
472 lines (409 loc) · 15.6 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
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
/*
* Copyright (c) 2014, Jean-Christophe Hoelt <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// Our application's global object
var app = {};
app.nonHostedContentUrl = "http://ge.tt/api/1/files/3JSfJhL2/0/blob?download";
app.packageName = "uk.co.workingedge.test.inapp";
//
// Constructor
// -----------
//
app.initialize = function() {
log('initialize');
// Listen to the deviceready event.
// Make sure the score of 'this' isn't lost.
document.addEventListener('deviceready', this.bind(this.onDeviceReady), false);
};
//
// Methods
// -------
//
// deviceready event handler.
//
// will just initialize the Purchase plugin
app.onDeviceReady = function() {
log('onDeviceReady');
//alert("This alert interrupts the main JS thread so you can connect a remote debugger to the WebView...");
//setTimeout(function(){
this.initStore();
//}.bind(this), 2000);
};
// initialize the purchase plugin if available
app.initStore = function() {
if (!window.store) {
log('Store not available');
return;
}
app.platform = device.platform.toLowerCase();
document.getElementsByTagName('body')[0].className = app.platform;
// Enable maximum logging level
store.verbosity = store.DEBUG;
// Enable remote receipt validation
store.validator = "https://api.fovea.cc:1982/check-purchase";
// Inform the store of your products
log('registerProducts');
store.register({
id: app.packageName + '.' + 'consumable1',
alias: 'extra life',
type: store.CONSUMABLE
});
store.register({
id: app.packageName + '.' + 'nonconsumable1',
alias: 'full version',
type: store.NON_CONSUMABLE
});
store.register({
id: app.packageName + '.' + 'subscription1',
alias: 'subscription1',
type: store.PAID_SUBSCRIPTION
});
store.register({
id: app.packageName + '.' + 'nonconsumablenonhosted1',
alias: 'non-hosted content download',
type: store.NON_CONSUMABLE
});
if(app.platform === "ios"){
store.register({
id: app.packageName + '.' + 'nonconsumablehosted1',
alias: 'hosted content download',
type: store.NON_CONSUMABLE
});
store.register({
id: app.packageName + '.' + 'nonconsumablehosted2',
alias: 'hosted content download 2',
type: store.NON_CONSUMABLE
});
}
// When any product gets updated, refresh the HTML.
store.when("product").updated(function (p) {
app.renderIAP(p);
});
store.when("subscription1").approved(function(p) {
log("verify subscription");
p.verify();
});
store.when("subscription1").verified(function(p) {
log("subscription verified");
p.finish();
});
store.when("subscription1").unverified(function(p) {
log("subscription unverified");
});
store.when("subscription1").updated(function(p) {
if (p.owned) {
document.getElementById('subscriber-info').innerHTML = 'You are a lucky subscriber!';
}
else {
document.getElementById('subscriber-info').innerHTML = 'You are not subscribed';
}
});
// Log all errors
store.error(function(error) {
log('ERROR ' + error.code + ': ' + error.message);
});
// When purchase of an extra life is approved,
// deliver it... by displaying logs in the console.
store.when("extra life").approved(function (order) {
log("You got an EXTRA LIFE!");
order.finish();
});
// When purchase of the full version is approved,
// show some logs and finish the transaction.
store.when("full version").approved(function (order) {
log('You just unlocked the FULL VERSION!');
order.finish();
});
// The play button can only be accessed when the user
// owns the full version.
store.when("full version").updated(function (product) {
document.getElementById("access-full-version-button").style.display =
product.owned ? "block" : "none";
});
/*
* iOS Apple-hosted content
*/
var getPurchaseType = function(product){
return product.transaction.original_transaction_id ? "redeemed" : "purchased";
};
// When purchase of the downloadable content is approved,
// show some logs.
store.when("hosted content download").approved(function (product) {
log("You've "+getPurchaseType(product)+" the content for " + product.id + " - it will now download to your device!");
});
// Show progress during hosted content download
store.when("hosted content download").downloading(function(product) {
log("Downloaded "+product.progress + "% of "+product.id);
var html = 'Downloading content: ' + product.progress + '%';
document.getElementById('non-consumable-hosted-content-download').innerHTML = html;
});
// When hosted content download is complete, finish the transaction
store.when("hosted content download").downloaded(function(product) {
log("Finished downloading "+product.id);
product.finish();
});
// If the product content is downloading or downloaded, display the downloaded content
store.when("hosted content download").updated(function (product) {
var displayEl = document.getElementById("non-consumable-hosted-content-download");
if(product.downloading || product.downloaded){
displayEl.style.display = "block";
}else{
displayEl.style.display = "none";
}
if(product.downloaded){
var productName = product.id.split(".").pop();
displayDownloadedContent(cordova.file.documentsDirectory + productName, displayEl);
}
});
// When purchase of the downloadable content is approved,
// show some logs.
store.when("hosted content download 2").approved(function (product) {
log("You've "+getPurchaseType(product)+" the content for " + product.id + " - it will now download to your device!");
});
// Show progress during hosted content download
store.when("hosted content download 2").downloading(function(product) {
log("Downloaded "+product.progress + "% of "+product.id);
var html = 'Downloading content: ' + product.progress + '%';
document.getElementById('non-consumable-hosted-content-download').innerHTML = html;
});
// When hosted content download is complete, finish the transaction
store.when("hosted content download 2").downloaded(function(product) {
log("Finished downloading "+product.id);
product.finish();
});
// If the product content is downloading or downloaded, display the downloaded content
store.when("hosted content download 2").updated(function (product) {
var displayEl = document.getElementById("non-consumable-hosted-content-download");
if(product.downloading || product.downloaded){
displayEl.style.display = "block";
}else{
displayEl.style.display = "none";
}
if(product.downloaded){
displayDownloadedContent(cordova.file.documentsDirectory, displayEl);
}
});
/*
* Non-hosted (self-hosted) content
*/
// When purchase of the downloadable content is approved,
// show some logs.
store.when("non-hosted content download").approved(function (product) {
log("You've "+getPurchaseType(product)+" the content for " + product.id + " - it will now download to your device!");
downloadNonHostedContent(product);
});
// Show progress during hosted content download
store.when("non-hosted content download").downloading(function(product) {
var html = 'Downloading content';
if(product.progress >= 0){
html += ': ' + product.progress + '%';
}
document.getElementById('non-consumable-non-hosted-content-download').innerHTML = html;
});
// When hosted content download is complete, finish the transaction
store.when("non-hosted content download").downloaded(function(product) {
product.finish();
});
// Show download element if the product content is downloading or downloaded
// When hosted content download is complete, display the downloaded content and finish the transaction
store.when("non-hosted content download").updated(function (product) {
var displayEl = document.getElementById("non-consumable-non-hosted-content-download");
if(product.downloading || product.downloaded){
displayEl.style.display = "block";
}else{
displayEl.style.display = "none";
}
if(product.downloaded){
var productName = product.id.split(".").pop();
displayDownloadedContent(cordova.file.dataDirectory + productName, displayEl);
}
});
// When the store is ready (i.e. all products are loaded and in their "final"
// state), we hide the "loading" indicator.
//
// Note that the "ready" function will be called immediately if the store
// is already ready.
store.ready(function() {
var el = document.getElementById("loading-indicator");
if (el)
el.style.display = 'none';
});
// When store is ready, activate the "refresh" button;
store.ready(function() {
var el = document.getElementById('refresh-button');
if (el) {
el.style.display = 'block';
el.onclick = function(ev) {
store.refresh();
};
}
});
// Alternatively, it's technically feasible to have a button that
// is always visible, but shows an alert if the full version isn't
// owned.
// ... but your app may be rejected by Apple if you do it this way.
//
// Here is the pseudo code for illustration purpose.
// myButton.onclick = function() {
// store.ready(function() {
// if (store.get("full version").owned) {
// // access the awesome feature
// }
// else {
// // display an alert
// }
// });
// };
// Refresh the store.
//
// This will contact the server to check all registered products
// validity and ownership status.
//
// It's fine to do this only at application startup, as it could be
// pretty expensive.
log('refresh');
store.refresh();
};
app.renderIAP = function(p) {
var parts = p.id.split(".");
var elId = parts[parts.length-1];
var el = document.getElementById(elId + '-purchase');
if (!el) return;
if (!p.loaded) {
el.innerHTML = '<h3>...</h3>';
}
else if (!p.valid) {
el.innerHTML = '<h3>' + p.alias + ' Invalid</h3>';
}
else if (p.valid) {
var html = "<h3>" + p.title + "</h3>" + "<p>" + p.description + "</p>";
if (p.canPurchase) {
html += "<div class='button' id='buy-" + p.id + "' productId='" + p.id + "' type='button'>" + p.price + "</div>";
}
el.innerHTML = html;
if (p.canPurchase) {
document.getElementById("buy-" + p.id).onclick = function (event) {
var pid = this.getAttribute("productId");
store.order(pid);
};
}
}
};
//
// Internal functions
// ------------------
//
function displayDownloadedContent(contentPath, displayEl){
var failedFileReadCallback = function(error){
log("Error reading downloaded content: "+JSON.stringify(error));
};
window.resolveLocalFileSystemURL(contentPath, function(dir){
dir.getFile("payload.txt", {create: false}, function (fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
if(evt.target.error){
failedFileReadCallback(evt.target.error)
}else if(evt.target.result){
displayEl.innerHTML = evt.target.result;
}else{
failedFileReadCallback("No file contents found");
}
};
reader.readAsText(file);
}, failedFileReadCallback);
}, failedFileReadCallback);
},failedFileReadCallback);
}
function downloadNonHostedContent(product){
var fileTransfer = new FileTransfer();
fileTransfer.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
var percentage = Math.floor(progressEvent.loaded / progressEvent.total * 100);
product.set({
progress: percentage,
state: store.DOWNLOADING
});
product.stateChanged();
}else{
product.set("state", store.DOWNLOADING);
}
};
product.name = product.id.split(".").pop();
var sourceURI = encodeURI(app.nonHostedContentUrl);
var targetFilePath = cordova.file.cacheDirectory + product.name;
fileTransfer.download(
sourceURI,
targetFilePath,
function(fileEntry) {
log("Download complete: " + fileEntry.toURL());
deployNonHostedContent(product, fileEntry);
},
function(error) {
if(error.source){
log("download error source " + error.source);
}
if(error.target){
log("download error target " + error.target);
}
},
true
);
}
function deployNonHostedContent(product, zipFileEntry){
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(dataDirectory){
dataDirectory.getDirectory(product.name, {create: true}, function(targetDirectory) {
zip.unzip(zipFileEntry.toURL(), targetDirectory.toURL(), function(result) {
if(result === 0){
log("Content unpacking complete: " + targetDirectory.toURL());
product.set("state", store.DOWNLOADED);
}else{
log("Error unzipping content zip");
}
});
}, function(error){
log("Error creating directory for product content: "+JSON.stringify(error));
});
},function(error){
log("Error resolving data directory location: "+JSON.stringify(error));
});
}
//
// Utilities
// ---------
//
// shortcut to the app logging function.
function log(arg) { app.log(arg); }
// log both in the console and in the HTML #log element.
app.log = function(arg) {
try {
if (typeof arg !== 'string')
arg = JSON.stringify(arg);
console.log(arg);
document.getElementById('log').innerHTML += '<div>' + arg + '</div>';
} catch (e) {}
};
// make sure fn will be called with app as 'this'
app.bind = function(fn) {
return function() {
fn.call(app, arguments);
};
};
app.initialize();