-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathiap_badger.lua
executable file
·2214 lines (1854 loc) · 90 KB
/
iap_badger.lua
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local Library = require "CoronaLibrary"
local public = Library:new{ name='iap_badger', publisherId='uk.co.happymongoose' }
--Store library
local store={}
public.store=store
local version=18
--[[
IAP badger - the trolley of the future.
Currently supports: iOS App Store / Google Play / Amazon / simulator
Changelog
---------
Version 18
* purchases on Google Store that fail because the user already owns the specified item are now converted into standard purchase events (to replicate behaviour on iOS). This can be turned on/off with the googleConvertOwnedPurchaseEvents flag during initialisation.
* On Android, warnings given if no build store has been selected in the Corona build dialog
Version 17
* corrected declaration of emptyInventoryOfNonConsumableItems
Version 16
* fixed checkProductExists bug (thanks to bogomazon)
Version 15
* bug fixes
* better handling of store on iOS if user not logged in
Version 14
* Fixed bug introduced in version 12 on Android devices that mishandled failed/cancelled events
* Better handling (and improved consistency between devices) of transaction receipts
Version 13
* Fixed bug introduced in version 12 that would make cancelled or failed restores in debug mode fail
Version 12
* added switch to ignore unknown product codes on purchase/restore - handleInvalidProductIDs
* downgraded invalid product IDs from an error that halts execution to a printed error to terminal
* added switch in catalogue to allow restore of individual consumable products (set allowRestore to true) - note that this item will now be included when running a restore cycle in debug mode
* removed some of instructional comments from the source code (out of date and better documentation available on http://happymongoose.co.uk anyway
* improved some debug output detail on verboseDebugOutput
* fixed incorrect error messages on consumption events on Google Play
Version 11
* fixed loadProducts not working correctly on simulator (when not passed a callback function)
Version 10
* fixed crash bug introduced by verboseDebugOutput when testing cancelled/failed restores on the simulator
Version 9
* added verboseDebugOutput for some functions
* added automatic build number check to see whether IAP Badger needs to run in synchronous mode for new Google IAP v3 interface
Version 8.02
* fixed minor error with usingOldGoogle
Version 8:
* updated for Google IAP update (store.init now asynchronous) - disable this by setting usingOldGoogle to true in iap.init()
* added getVersion(), consumeAllProducts() and printLoadProductsCatalogue() functions
* improved handling of loadProducts in debug mode or on the simulator, so it better simulates the delay experienced on a real device
Version 7:
* decoupled inventory handling from IAP handling
Version 6:
* loadProducts - fixed user listener not being called correctly (again)
* loadProducts - for convenience, the user listener is now called with (raw product data, loadProductsCatalogue) on device;
* ({}, loadProductsCatalogue) on simulator.
Version 5:
* fix to getLoadProductsFinished when running in debug mode
Version 4:
* removed reference to stores.availableStores.apple
Version 3:
* fixed store loading (defaulting to Apple) on non-iOS devices
Version 2:
* support added for Amazon IAP v2
* removed generateAmazonJSON() function as it is no longer required (JSON testing file can now be downloaded from Amazon's website)
* fixed null productID passed on fake cancelled/failed restore events
* changes to loadInventory and saveInventory to add ability to load and save directly from a string instead of a device file (to allow for cloud saving etc.)
* added getLoadProductsFinished() - returns true if loadProducts has received information back from the store, false if loadProducts still waiting, nil if loadProducts never called
General features:
* a unified approach to calling store and IAP whether you're on the App Store, Google Play, or wherever
* simplified calling and testing of IAP functions, just provide a list of products and some simple callbacks for when items are purchased / restored or
refunded
* simplified product maintenance (adding/removing products from the inventory)
* handles loading / saving of items that have been purchased
* put IAP badger in debug mode to test IAP functions in your app (purchase / restore) without having to contact real stores
* products can have different names across the range of stores (so an upgrade called 'COIN_UPGRADE' in iTunes Connect could be called
'coins_purchased' in Google Play)
* different product types available (consumable or non-consumable)
Inventory / security features:
* customise the filename used to save the contents of the inventory
* inventory file contents can be hashed to prevent unauthorised changes (specify a 'salt' in the init() function).
* a customisable 'salt' can be applied to the contents so no two Corona apps produce the same hash for the same inventory contents. (Empty inventories
are saved without a hash, to make it more difficult to reverse engineer the salt.)
* product names can be refactored (renamed) in the save file to disguise their true function
* quantities / values can also be disguised / obfuscated
* 'random items' can be added to the inventory, whose values change randomly with each save, to help disguise the function of other quantities
being saved at the same time.
* IAP badger can generate a Amazon test JSON file for you, to help with testing on Amazon hardware
This code is released under an MIT license, so you're free to do what you want with it -
though it would be great that if you forked or improved it, those improvements were
given back to the community :)
The MIT License (MIT)
Copyright (c) 2015/16 The Happy Mongoose Company Ltd.
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.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--Product catalogue
local catalogue=nil
--User inventory
local inventory=nil
public.inventory=inventory
local refactorTable=nil
public.refactorTable=refactorTable
--Filename for inventory
local filename=nil
public.filename=filename
--Salt used to hash contents (if required by user)
local salt=nil
--Requires crypto library
local crypto = require("crypto")
--Is the store available?
local storeAvailable=false
--Get function
local function isStoreAvailable() return storeAvailable end
public.isStoreAvailable=isStoreAvailable
--Forward references
local storeTransactionCallback
local fakeRestore
local fakeRestoreListener
local fakePurchase
local loadProducts
local restore
local purchase
--Switches (and default values)
local handleInvalidProductIDs=false
--Restore purchases timer
local restorePurchasesTimer=nil
--Transaction failed / cancelled listeners
local transactionFailedListener=nil
local transactionCancelledListener=nil
--Info about last transaction
local previouslyRestoredTransactions=nil
--Target store
local targetStore=nil
--Debug mode
local debugMode=false
--Store to debug as
local debugStore="apple"
--Verbose debug output to console?
local verboseDebugOutput=nil
--Standard response to bad hash
local badHashResponse="errorMessage"
--A convenience function - returns a user friendly name for the current app store
local storeNames = { apple="the App Store", google="Google Play", amazon="Amazon", none="a simulated app store"}
local storeName = nil
--Function to call after storeTransactionCallback (optional parameter to purchase function)
local postStoreTransactionCallbackListener=nil
local postRestoreCallbackListener=nil
local fakeRestoreTimeoutFunction=nil
local fakeRestoreTimeoutTime=nil
--For Google IAP v3 only...
--Indicates whether the store has been initialised (for handling asynchronous initialisation on Google IAP
local storeInitialized = nil
--Once the store is initialised, run a restore
local initQueue = nil
local googleLastPurchaseProductID = ""
--On Google, if a purchase fails because the user already owns the item, convert the 'fail' state to success
local googleConvertOwnedPurchaseEvents = true
--Flag to indicate if this is the first item following a restore call
local firstRestoredItem=nil
--Action type - either "purchase" or "restore". Used for faking Google purchase or restore
local actionType=nil
--List of products / prices returned by the loadProducts function. If no product catalogue is available,
--the loadProductsCatalogue will contain "false" after the loadProducts function has been called (nil beforehand)
local loadProductsCatalogue=nil
--Accessor function for getting at the catalogue
local function getLoadProductsCatalogue() return loadProductsCatalogue end
public.getLoadProductsCatalogue = getLoadProductsCatalogue
local loadProductsFinished=nil
local function getLoadProductsFinished() return loadProductsFinished end
public.getLoadProductsFinished = getLoadProductsFinished
--Returns number of items in table
local function tableCount(src)
local count = 0
if( not src ) then return count end
for k,v in pairs(src) do
count = count + 1
end
return count
end
--Debug table print function - this just prints the given table in a more human readable form
local function debugPrint ( t )
local print_r_cache={}
local function sub_print_r(t,indent)
if (print_r_cache[tostring(t)]) then
print(indent.."*"..tostring(t))
else
print_r_cache[tostring(t)]=true
if (type(t)=="table") then
for pos,val in pairs(t) do
if (type(val)=="table") then
print(indent.."["..pos.."] => "..tostring(t).." {")
sub_print_r(val,indent..string.rep(" ",string.len(pos)+8))
print(indent..string.rep(" ",string.len(pos)+6).."}")
elseif (type(val)=="string") then
print(indent.."["..pos..'] => "'..val..'"')
else
print(indent.."["..pos.."] => "..tostring(val))
end
end
else
print(indent..tostring(t))
end
end
end
if (type(t)=="table") then
print(tostring(t).." {")
sub_print_r(t," ")
print("}")
else
sub_print_r(t," ")
end
print()
end
-- ***********************************************************************************************************
--Load/Save functions, based on Rob Miracle's simple table load-save functions.
--Inventory adds a layer of protection to the load/save functions.
local json = require("json")
local DefaultLocation = system.DocumentsDirectory
local RealDefaultLocation = DefaultLocation
local ValidLocations = {
[system.DocumentsDirectory] = true,
[system.CachesDirectory] = true,
[system.TemporaryDirectory] = true
}
local function tableIsEmpty (self)
if (self==nil) then return true end
for _, _ in pairs(self) do
return false
end
return true
end
local function saveToString(t)
local contents = json.encode(t)
--If a salt was specified, add a hash to the start of the data.
--Only include a salt if a non-empty table was provided
if (salt~=nil) and (tableIsEmpty(t)==false) then
--Create hash
local hash = crypto.digest(crypto.md5, salt .. contents)
--Append to contents
contents = hash .. contents
end
return contents
end
local function saveTable(t, filename, location)
if location and (not ValidLocations[location]) then
error("Attempted to save a table to an invalid location", 2)
elseif not location then
location = DefaultLocation
end
local path = system.pathForFile( filename, location)
local file = io.open(path, "w")
if file then
local contents = saveToString(t)
file:write( contents )
io.close( file )
return true
else
return false
end
end
local function loadInventoryFromString(contents)
--If the contents start with a hash...
if (contents:sub(1,1)~="{") then
--Find the start of the contents...
local delimeter = contents:find("{")
--If no contents were found, return an empty table whatever the hash
if (delimeter==nil) then return nil end
local hash = contents:sub(1, delimeter-1)
contents = contents:sub(delimeter)
--Calculate a hash for the contents
local calculatedHash = nil
if (salt) then
calculatedHash = crypto.digest(crypto.md5, salt .. contents)
else
calculatedHash = crypto.digest(crypto.md5, contents)
end
--If the two do not match, reject the file
if (hash~=calculatedHash) then
if (badHashResponse=="emptyInventory") then
return nil
elseif (badHashResponse=="errorMessage") then
native.showAlert("Error", "File error.", {"Ok"})
return nil
elseif (badHashResponse=="error" or badHashResponse==nil) then
error("File error occurred")
return nil
else
badHashResponse()
return nil
end
end
end
return json.decode(contents);
end
local function loadTable(filename, location)
if location and (not ValidLocations[location]) then
error("Attempted to load a table from an invalid location", 2)
elseif not location then
location = DefaultLocation
end
local path = system.pathForFile( filename, location)
local contents = ""
local myTable = {}
local file = io.open( path, "r" )
if file then
-- read all contents of file into a string
local contents = file:read( "*a" )
myTable = loadInventoryFromString(contents)
io.close( file )
return myTable
end
return nil
end
local function changeDefaultSaveLocation(location)
if location and (not location) then
error("Attempted to change the default location to an invalid location", 2)
elseif not location then
location = RealDefaultLocation
end
DefaultLocation = location
return true
end
-- ***********************************************************************************************************
local function printInventory()
print (json.encode(inventory))
end
public.printInventory = printInventory
--Searches for the inventory item with the given name in the refactor table. If it does not exist, then nil is returned.
local function findNameInRefactorTable(name)
--If no refactor table is available, just return the name that was passed - there is no refactoring to be done
if (refactorTable==nil) then return nil end
--For every item in the table
for key, value in pairs(refactorTable) do
if (value.name==name) then return value end
end
return nil
end
--Searches for the inventory item with the given refactored name in the refactor table. If it does not exist, then nil is returned.
local function findRefactoredNameInRefactorTable(rName)
--If no refactor table is available, just return the name that was passed - there is no refactoring to be done
if (refactorTable==nil) then return nil end
--For every item in the table
for key, value in pairs(refactorTable) do
if (value.refactoredName==rName) then return value end
end
return nil
end
--Refactors the given property
-- rObject - object from the refactor table describing how to refactor all of the properties
-- property - the name of the property to refactor
-- value - the value to refactor
--Returns: refactoredPropertyName, refactoredPropertyValue
local function refactorProperty(rObject, propertyName, propertyValue)
--If there is no property information in the table, return the values that were given (there
--is no refactoring to be done)
if (rObject.properties==nil) then return propertyName, propertyValue end
--Loop through the properties refactoring information to find the property
for key, value in pairs(rObject.properties) do
--If this is the key specified by the user...
if (value.name==propertyName) then
--Refactor the property name (if one was given)
local refactoredName = propertyName
if (value.refactoredName~=nil) then refactoredName=value.refactoredName end
--Refactor the value (if a function is provided)
local refactoredValue = propertyValue
if (value.refactorFunction~=nil) then refactoredValue = value.refactorFunction(propertyValue) end
--Return the values
return refactoredName, refactoredValue
end
end
--There is no information describing how to refactor this property, so return the values
--that were given
return propertyName, propertyValue
end
--Defactors the given property
-- rObject - object from the refactor table describing how to refactor all of the properties
-- property - the name of the property to defactor
-- value - the value to defactor
--Returns: defactoredPropertyName, defactoredPropertyValue
local function defactorProperty(rObject, propertyName, propertyValue)
--If there is no property information in the table, return the values that were given (there
--is no refactoring to be done)
if (rObject.properties==nil) then return propertyName, propertyValue end
--Loop through the properties refactoring information to find the property
for key, value in pairs(rObject.properties) do
--If this is the key specified by the user...
if (value.refactoredName==propertyName) then
--Defactor the property name (if one was given)
local defactoredName = propertyName
if (value.name~=nil) then defactoredName=value.name end
--Defactor the value (if a function is provided)
local defactoredValue = propertyValue
if (value.defactorFunction~=nil) then defactoredValue = value.defactorFunction(propertyValue) end
--Return the values
return defactoredName, defactoredValue
end
end
--There is no information describing how to refactor this property, so return the values
--that were given
return propertyName, propertyValue
end
--Creates a recfactored inventory
local function createRefactoredInventory()
--If the refactor table is nil, return the inventory
if (refactorTable==nil) then return inventory end
--Create a new table that will be copy of the inventory table
local refactoredInventory = {}
for key, values in pairs(inventory) do
--Store the key and value
local refactoredName=key
local refactoredValues=values
--Does the inventory item exist in the refactor table>
local refactorObject = findNameInRefactorTable(key)
--If it does, then refactor
if (refactorObject~=nil) then
--Change the name of the object
if (refactorObject.refactoredName~=nil) then refactoredName = refactorObject.refactoredName end
--Iterate through the properties
for pKey, pValue in pairs(values) do
--Spare table to hold refactored values
refactoredValues={}
--Refactor
local refactoredPropertyKey, refactoredPropertyValue = refactorProperty(refactorObject, pKey, pValue)
refactoredValues[refactoredPropertyKey]=refactoredPropertyValue
end
end
--Add the refactored information into the new inventory
refactoredInventory[refactoredName] = refactoredValues
end
return refactoredInventory
end
public.createRefactoredInventory = createRefactoredInventory
--Creates a defactored inventory -- not sure if that's a real word, but there you go
local function createDefactoredInventory(inventoryIn)
--Create a new table that will be copy of the inventory table
local defactoredInventory = {}
for key, values in pairs(inventoryIn) do
--Store the key and value
local defactoredName=key
local defactoredValues=values
--Does the inventory item exist in the refactor table>
local refactorObject = findRefactoredNameInRefactorTable(key)
--If it does, then refactor
if (refactorObject~=nil) then
--Change the name of the object
defactoredName = refactorObject.name
--Iterate through the properties
for pKey, pValue in pairs(values) do
--Spare table to hold refactored values
defactoredValues={}
--Refactor
local defactoredPropertyKey, defactoredPropertyValue = defactorProperty(refactorObject, pKey, pValue)
defactoredValues[defactoredPropertyKey]=defactoredPropertyValue
end
end
--Add the refactored information into the new inventory
defactoredInventory[defactoredName] = defactoredValues
end
return defactoredInventory
end
public.createDefactoredInventory = createDefactoredInventory
--Goes through inventory, and enters random values for random-integer and random-decimal
--products
local function randomiseInventory()
for key, value in pairs(inventory) do
--Find the product in the product catalogue
local product = catalogue.inventoryItems[key]
--If the product is specified in the inventory...
if (product) then
--If the product type is random-integer...
if (product.productType=="random-integer") then
value.value=math.random(product.randomLow, product.randomHigh)
elseif (product.productType=="random-decimal") then
value.value=math.random(product.randomLow, product.randomHigh)+(1/(math.random(1,1000)))
elseif (product.productType=="random-hex") then
value.value=string.format("0x%x", math.random(product.randomLow, product.randomHigh))
end
end
end
end
--Saves the inventory contents
--asString - if nil, the inventory will be saved on the user's device; if set to true,
--will return a string representing the inventory that can be used for saving the inventory elsewhere
--(ie. on the cloud etc.)
local function saveInventory(asString)
--Ignore if no filename given
if (filename==nil) then return end
--Create random values for random products
randomiseInventory()
--Refactor the inventory
local refactoredInventory = createRefactoredInventory()
--Save contents
if (asString==nil) then
saveTable(refactoredInventory, filename)
else if (asString==true) then
return saveToString(refactoredInventory)
end
end
end
public.saveInventory = saveInventory
--Load in a previously saved inventory
--If inventoryString=nil, then the inventory will be loaded from the save file on the user's device.
--If a string is passed, the library will attempt to decode a text string containing the inventory - use
--this for loading from the cloud etc.
local function loadInventory(inventoryString)
--If no filename set, ignore
if (filename==nil) then return end
--Attempt to load inventory
local refactoredInventory=nil
if (inventoryString==nil) then
refactoredInventory = loadTable(filename)
else
refactoredInventory = loadInventoryFromString(inventoryString)
end
--If inventory does not exists, create one
if (refactoredInventory==nil) then
inventory={}
else
inventory=createDefactoredInventory(refactoredInventory)
end
end
public.loadInventory = loadInventory
--Returns true if the specified product exists
local function checkProductExists(productName)
--Does the product name exist in the product table?
if (catalogue.products[productName]==nil) then return false else return true end
end
public.checkProductExists = checkProductExists
--Returns the value of the current product inside the inventory (eg. a quantity / boolean)
--If the item is not in the inventory, this returns nil.
local function getInventoryValue(productName)
if (inventory[productName]==nil) then
if catalogue.inventoryItems[productName] and catalogue.inventoryItems[productName].reportMissingAsZero then return 0 end
return nil
end
return inventory[productName].value
end
public.getInventoryValue = getInventoryValue
--Returns true if the item is in the inventory
local function isInInventory(productName)
return inventory[productName]
end
public.isInInventory = isInInventory
--Returns the count of different itemt types in the inventory
local function inventoryItemCount()
local ctr=0
if (inventory==nil) then return 0 end
for key, value in pairs(inventory) do
ctr=ctr+1
end
return ctr
end
public.inventoryItemCount = inventoryItemCount
--Returns true if inventory is empty
local function isInventoryEmpty()
return inventoryItemCount()==0
end
public.isInventoryEmpty = isInventoryEmpty
--Empties the inventory, keeping any non-consumable items.
-- disposeAll (optional): set to true to remove non-consumables as well (default=false)
local function emptyInventory(disposeAll)
--Disposing everything is easy
if (disposeAll==true) then
inventory={}
return
end
--Loop through and dispose of everything except non-consumables
for key, value in pairs(inventory) do
if (catalogue.inventoryItems[key].productType~="non-consumable") then
inventory[key]=nil
end
end
end
public.emptyInventory=emptyInventory
--Empties the inventory, keeping any consumable items
local function emptyInventoryOfNonConsumableItems()
--Loop through and dispose of all non-consumables
for key, value in pairs(inventory) do
if (catalogue.inventoryItems[key].productType=="non-consumable") then
inventory[key]=nil
end
end
end
public.emptyInventoryOfNonConsumableItems=emptyInventoryOfNonConsumableItems
--Adds a product to the inventory
-- productName = name of the product to add
-- addValue (optional, default=1 for consumables, true for non-consuambles)
local function addToInventory(productName, addValue)
--Get the product type
local productType = catalogue.inventoryItems[productName].productType
--If non-consumable, always set product value to true
if (productType=="non-consumable") then
inventory[productName]={value=true}
return
end
--Adding a consumable so use a quantity
--Random vars also end up here, but they ignore the quantity anyway, so don't
--worry about it
--Assume a quantity of 1, if no value if passed
if (addValue==nil) then addValue=1 end
--Does the current item already exist in the inventory?
local currentValue=getInventoryValue(productName)
--The following will handle cases where the product quantity comes back as zero rather than nil
--(because user has specified things that way). Zero quantities indicate something slightly
--different to 'missing' items, so reset value to nil.
if (currentValue==0) then currentValue=nil end
--If it doesn't, create an entry for the item and quit
if (currentValue==nil) then
inventory[productName]={value=addValue}
return
end
--Add the quantity to the stores of the item that are already there
inventory[productName].value=currentValue+addValue
end
public.addToInventory = addToInventory
--Returns true if product was removed, false if not
-- productName = product to remove
-- subValue (optional) - number of items to remove, defaults to 1. Non-consumables are always removed. If attempting to remove a consumable (for
-- some reason), then set subValue to true to force removal. If this item is a consumable, use "all" to remove all of the item.
local function removeFromInventory(productName, subValue)
--Get the product type
local productType = catalogue.inventoryItems[productName].productType
--If the object is non-consumable...
if (productType=="non-consumable") then
--...and the force flag is set to true...
if (subValue==true) then
--Remove item
inventory[productName]=nil
--Item was removed - non-consumable but user forced removal
return true
end
--Item wasn't removed - it was non-consumable
error("iap badger.removeFromInventory: attempt to remove non-consumable item (" .. productName .. ") from inventory.")
return false
end
--If the object is a consumable...
if (productType=="consumable") then
--If no quantity is given, assume a quantity of 1
if (subValue==nil) then subValue=1 end
--Does the current item already exist in the inventory?
local currentQuantity=getInventoryValue(productName)
if (subValue=="all") then subValue=currentQuantity end
--If there will be an underrun, signal the error
if (currentQuantity<subValue) then
error("iap badger.removeFromInventory: attempted to removed more " .. productName .. "(s) than available in inventory (attempted to remove " .. subValue .. " from " .. currentQuantity .. " available)")
return false
end
--Remove the item
inventory[productName].value = currentQuantity-subValue
--If there are none of the item left, remove it from the inventory
if (inventory[productName].value==0) then inventory[productName]=nil end
--Item was removed
return true
end
--If got here, than removing a random item - always just completely remove from inventory
inventory[productName]=nil
return true
end
public.removeFromInventory = removeFromInventory
--Sets the value of the item in the inventory. No type checking is done - this is left to the user.
-- productName: the product to set
-- value_in: the value to set it to
local function setInventoryValue(productName, value_in)
if (inventory[productName]==nil) then
inventory[productName]={ value = value_in }
else
inventory[productName].value = value_in
end
end
public.setInventoryValue=setInventoryValue
local function copyTable(arg)
local t = {}
for key, value in pairs(arg) do
t[key] = value
end
return t
end
--Forces the debug mode
-- mode = true/false
-- store = name of store to simulator (defaults to apple)
local function setDebugMode(mode, store)
--Set debug mode
debugMode=mode
--Copy in the debug store (if one was specified, and running on the simulator). Ignore this on devices.
if (system.getInfo("environment")=="simulator") then
if (store~=nil) then debugStore=store else debugStore="apple" end
storeName = storeNames[debugStore]
end
--If running on a device, and in debug mode, then make sure user knows
if (system.getInfo("environment")~="simulator") and debugMode==true then
native.showAlert("Warning", "Running IAP Badger in debug mode on device", {"Ok"})
end
end
public.setDebugMode=setDebugMode
--Google only
--This will consume all products in the product table, regardless of whether they are consumable or not
--This function does not nothing on all other platforms
local function consumeAllPurchases()
--This only applies to Google on a device - ignore for all other configurations
if targetStore~="google" then return end
--If running on Google IAP, the store may not have been initialised at this point. If it isn't ready, queue up the restore for when it is and quit now
if storeInitialized==false then
--Tell store transaction listener to run a restore when the initialisation is finished
item = {
name="consumeAllPurchases",
params={ }
}
initQueue[#initQueue+1]=item
--Quit now
return true
end
--Iterate through the product catalogue
for key, product in pairs(catalogue.products) do
--If this product has a google product ID associated with it...
if (product.productNames.google) then
--...consume it
store.consumePurchase(product.productNames.google)
end
end
end
public.consumeAllPurchases = consumeAllPurchases
-- ************************************************************************************************************
--Returns the product name and product data from the catalogue, for the product with the given
--app store id.
local function getProductFromIdentifier(id)
--Search the product catalogue for the relevant target store - if running in the simulator,
--default to iOS.
local searchStore=targetStore
if (targetStore=="simulator") then searchStore=debugStore end
local productName=nil
local product=nil
--For every item in the product catalogue
for key, value in pairs(catalogue.products) do
--If this product has a store product names table...
if (value.productNames~=nil) then
--If this product has an entry in the correct store for the item that has been purchased...
if (value.productNames[searchStore]==id) then
--Return the product name and the product info from the catalogue
return key, value
end
end
end
return nil, nil
end
--Returns the correct app store identifier for the specified product name
local function getAppStoreID(productName)
--Search for the relevant target store - if running in the simulator,
--default to iOS.
local searchStore=targetStore
if (targetStore=="simulator") then searchStore=debugStore end
--Return the correct ID for this product
return catalogue.products[productName].productNames[searchStore]
end
local function checkPreviousTransactionsForProduct(productIdentifier, transactionIdentifier)
--If the table is empty, return false
if (previouslyRestoredTransactions==nil) then
return false
end
--Iterate over the table
for key, value in pairs(previouslyRestoredTransactions) do
--If this is the item specified...
if (value.productIdentifier==productIdentifier) and
(value.transactionIdentifier==transactionIdentifier) then
--... indicate item found
return true
end
end
--Item wasn't found
return false
end
local function executeInitQueue()
--If the queue contains something...
if initQueue~=nil then
for key, item in pairs(initQueue) do
--Load products
if item['name']=="loadProducts" then
loadProducts(item['params']['callback'])
end
--Restore
if item['name']=="restore" then
restore(item['params']['emptyFlag'], item['params']['postRestoreListener'], item['params']['timeoutFunction'], item['params']['cancelTime'])
end
--ConsumeAllPurchases
if item['name']=="consumeAllPurchases" then consumeAllPurchases() end
--Purchase
if item['name']=="purchase" then purchase(item['params']['productList'], item['params']['listener']) end
end
end
--Delete queue
initQueue = {}
end
--Transaction callback for all purchase / restore functions
local function storeTransactionCallback(event)
if (verboseDebugOutput) then
print "IAP Badger: storeTransactionCallback"
print "event contains raw data:"
debugPrint(event)
end
--If this is an init callback (Google IAP)...
if (event.name == "init") then
if (verboseDebugOutput) then print "Google Play initialisation event" end