/
InAppBillingImplementation.cs
931 lines (764 loc) · 34.3 KB
/
InAppBillingImplementation.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Newtonsoft.Json;
using Com.Android.Vending.Billing;
using Java.Security;
using Java.Security.Spec;
using Java.Lang;
using System.Text;
using Plugin.InAppBilling.Abstractions;
using Plugin.CurrentActivity;
using Android.Runtime;
namespace Plugin.InAppBilling
{
/// <summary>
/// Implementation for Feature
/// </summary>
[Preserve(AllMembers = true)]
public class InAppBillingImplementation : BaseInAppBilling
{
const string SKU_DETAILS_LIST = "DETAILS_LIST";
const string SKU_ITEM_ID_LIST = "ITEM_ID_LIST";
const string ITEM_TYPE_INAPP = "inapp";
const string ITEM_TYPE_SUBSCRIPTION = "subs";
const string RESPONSE_CODE = "RESPONSE_CODE";
const string RESPONSE_BUY_INTENT = "BUY_INTENT";
const string RESPONSE_IAP_DATA = "INAPP_PURCHASE_DATA";
const string RESPONSE_IAP_DATA_SIGNATURE = "INAPP_DATA_SIGNATURE";
const string RESPONSE_IAP_DATA_SIGNATURE_LIST = "INAPP_DATA_SIGNATURE_LIST";
const string RESPONSE_IAP_PURCHASE_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST";
const string RESPONSE_IAP_PURCHASE_DATA_LIST = "INAPP_PURCHASE_DATA_LIST";
const string RESPONSE_IAP_CONTINUATION_TOKEN = "INAPP_CONTINUATION_TOKEN";
const int PURCHASE_REQUEST_CODE = 1001;
const int RESPONSE_CODE_RESULT_USER_CANCELED = 1;
const int RESPONSE_CODE_RESULT_SERVICE_UNAVAILABLE = 2;
const int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3;
const int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 4;
const int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5;
const int BILLING_RESPONSE_RESULT_ERROR = 6;
const int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7;
const int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8;
/// <summary>
/// Gets the context, aka the currently activity.
/// This is set from the MainApplication.cs file that was laid down by the plugin
/// </summary>
/// <value>The context.</value>
Activity Context =>
CrossCurrentActivity.Current.Activity ?? throw new NullReferenceException("Current Context/Activity is null, ensure that the MainApplication.cs file is setting the CurrentActivity in your source code so the In App Billing can use it.");
/// <summary>
/// Default Constructor for In App Billing Implemenation on Android
/// </summary>
public InAppBillingImplementation()
{
}
/// <summary>
/// Gets or sets if in testing mode. Only for UWP
/// </summary>
public override bool InTestingMode { get; set; }
/// <summary>
/// Get product information of a specific product
/// </summary>
/// <param name="productIds">Sku or Id of the product</param>
/// <param name="itemType">Type of product offering</param>
/// <returns></returns>
public async override Task<IEnumerable<InAppBillingProduct>> GetProductInfoAsync(ItemType itemType, params string[] productIds)
{
if (serviceConnection?.Service == null)
{
throw new InAppBillingPurchaseException(PurchaseError.ServiceUnavailable, "You are not connected to the Google Play App store.");
}
IEnumerable<Product> products = null;
switch (itemType)
{
case ItemType.InAppPurchase:
products = await GetProductInfoAsync(productIds, ITEM_TYPE_INAPP);
break;
case ItemType.Subscription:
products = await GetProductInfoAsync(productIds, ITEM_TYPE_SUBSCRIPTION);
break;
}
if (products == null)
return null;
return products.Select(product => new InAppBillingProduct
{
Name = product.Title,
Description = product.Description,
CurrencyCode = product.CurrencyCode,
LocalizedPrice = product.Price,
ProductId = product.ProductId,
MicrosPrice = product.MicrosPrice
});
}
Task<IEnumerable<Product>> GetProductInfoAsync(string[] productIds, string itemType)
{
var getSkuDetailsTask = Task.Factory.StartNew<IEnumerable<Product>>(() =>
{
var querySku = new Bundle();
querySku.PutStringArrayList(SKU_ITEM_ID_LIST, productIds);
Bundle skuDetails = serviceConnection.Service.GetSkuDetails(3, Context.PackageName, itemType, querySku);
if (!skuDetails.ContainsKey(SKU_DETAILS_LIST))
{
return null;
}
var products = skuDetails.GetStringArrayList(SKU_DETAILS_LIST);
if (products == null || !products.Any())
return null;
var items = new List<Product>(products.Count);
foreach (var item in products)
{
items.Add(JsonConvert.DeserializeObject<Product>(item));
}
return items;
});
return getSkuDetailsTask;
}
/// <summary>
/// Get all current purhcase for a specifiy product type.
/// </summary>
/// <param name="itemType">Type of product</param>
/// <param name="verifyPurchase">Interface to verify purchase</param>
/// <returns>The current purchases</returns>
public async override Task<IEnumerable<InAppBillingPurchase>> GetPurchasesAsync(ItemType itemType, IInAppBillingVerifyPurchase verifyPurchase = null)
{
if (serviceConnection?.Service == null)
{
throw new InAppBillingPurchaseException(PurchaseError.ServiceUnavailable, "You are not connected to the Google Play App store.");
}
List<Purchase> purchases = null;
switch (itemType)
{
case ItemType.InAppPurchase:
purchases = await GetPurchasesAsync(ITEM_TYPE_INAPP, verifyPurchase);
break;
case ItemType.Subscription:
purchases = await GetPurchasesAsync(ITEM_TYPE_SUBSCRIPTION, verifyPurchase);
break;
}
if (purchases == null)
return null;
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var results = purchases.Select(p => new InAppBillingPurchase
{
TransactionDateUtc = epoch + TimeSpan.FromMilliseconds(p.PurchaseTime),
Id = p.OrderId,
ProductId = p.ProductId,
AutoRenewing = p.AutoRenewing,
PurchaseToken = p.PurchaseToken,
State = itemType == ItemType.InAppPurchase ? p.State : p.SubscriptionState,
ConsumptionState = p.ConsumedState,
Payload = p.DeveloperPayload ?? string.Empty
});
return results;
}
Task<List<Purchase>> GetPurchasesAsync(string itemType, IInAppBillingVerifyPurchase verifyPurchase)
{
var getPurchasesTask = Task.Run(async () =>
{
string continuationToken = string.Empty;
var purchases = new List<Purchase>();
do
{
Bundle ownedItems = serviceConnection.Service.GetPurchases(3, Context.PackageName, itemType, null);
var response = GetResponseCodeFromBundle(ownedItems);
if (response != 0)
{
break;
}
if (!ValidOwnedItems(ownedItems))
{
Console.WriteLine("Invalid purchases");
return purchases;
}
var items = ownedItems.GetStringArrayList(RESPONSE_IAP_PURCHASE_ITEM_LIST);
var dataList = ownedItems.GetStringArrayList(RESPONSE_IAP_PURCHASE_DATA_LIST);
var signatures = ownedItems.GetStringArrayList(RESPONSE_IAP_DATA_SIGNATURE_LIST);
for (int i = 0; i < items.Count; i++)
{
string data = dataList[i];
string sign = signatures[i];
if (verifyPurchase == null || await verifyPurchase.VerifyPurchase(data, sign))
{
var purchase = JsonConvert.DeserializeObject<Purchase>(data);
purchases.Add(purchase);
}
}
continuationToken = ownedItems.GetString(RESPONSE_IAP_CONTINUATION_TOKEN);
} while (!string.IsNullOrWhiteSpace(continuationToken));
return purchases;
});
return getPurchasesTask;
}
/// <summary>
/// Purchase a specific product or subscription
/// </summary>
/// <param name="productId">Sku or ID of product</param>
/// <param name="itemType">Type of product being requested</param>
/// <param name="payload">Developer specific payload (can not be null)</param>
/// <param name="verifyPurchase">Interface to verify purchase</param>
/// <returns></returns>
public async override Task<InAppBillingPurchase> PurchaseAsync(string productId, ItemType itemType, string payload, IInAppBillingVerifyPurchase verifyPurchase = null)
{
if (payload == null)
throw new ArgumentNullException(nameof(payload), "Payload can not be null");
if (serviceConnection?.Service == null)
{
throw new InAppBillingPurchaseException(PurchaseError.ServiceUnavailable, "You are not connected to the Google Play App store.");
}
Purchase purchase = null;
switch (itemType)
{
case ItemType.InAppPurchase:
purchase = await PurchaseAsync(productId, ITEM_TYPE_INAPP, payload, verifyPurchase);
break;
case ItemType.Subscription:
purchase = await PurchaseAsync(productId, ITEM_TYPE_SUBSCRIPTION, payload, verifyPurchase);
break;
}
if (purchase == null)
return null;
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return new InAppBillingPurchase
{
TransactionDateUtc = epoch + TimeSpan.FromMilliseconds(purchase.PurchaseTime),
Id = purchase.OrderId,
AutoRenewing = purchase.AutoRenewing,
PurchaseToken = purchase.PurchaseToken,
State = itemType == ItemType.InAppPurchase ? purchase.State : purchase.SubscriptionState,
ConsumptionState = purchase.ConsumedState,
ProductId = purchase.ProductId,
Payload = purchase.DeveloperPayload ?? string.Empty
};
}
async Task<Purchase> PurchaseAsync(string productSku, string itemType, string payload, IInAppBillingVerifyPurchase verifyPurchase)
{
lock (purchaseLocker)
{
if (tcsPurchase != null && !tcsPurchase.Task.IsCompleted)
return null;
Bundle buyIntentBundle = serviceConnection.Service.GetBuyIntent(3, Context.PackageName, productSku, itemType, payload);
var response = GetResponseCodeFromBundle(buyIntentBundle);
switch (response)
{
case 0:
//OK to purchase
break;
case 1:
//User Cancelled, should try again
throw new InAppBillingPurchaseException(PurchaseError.UserCancelled);
case 2:
//Network connection is down
throw new InAppBillingPurchaseException(PurchaseError.ServiceUnavailable);
case 3:
//Billing Unavailable
throw new InAppBillingPurchaseException(PurchaseError.BillingUnavailable);
case 4:
//Item Unavailable
throw new InAppBillingPurchaseException(PurchaseError.ItemUnavailable);
case 5:
//Developer Error
throw new InAppBillingPurchaseException(PurchaseError.DeveloperError);
case 6:
//Generic Error
throw new InAppBillingPurchaseException(PurchaseError.GeneralError);
case 7:
//already purchased
throw new InAppBillingPurchaseException(PurchaseError.AlreadyOwned);
}
var pendingIntent = buyIntentBundle.GetParcelable(RESPONSE_BUY_INTENT) as PendingIntent;
if (pendingIntent == null)
throw new InAppBillingPurchaseException(PurchaseError.GeneralError);
tcsPurchase = new TaskCompletionSource<PurchaseResponse>();
Context.StartIntentSenderForResult(pendingIntent.IntentSender, PURCHASE_REQUEST_CODE, new Intent(), 0, 0, 0);
}
var result = await tcsPurchase.Task;
if (result == null)
return null;
var data = result.PurchaseData;
var sign = result.DataSignature;
//for some reason the data didn't come back
if (string.IsNullOrWhiteSpace(data))
{
var purchases = await GetPurchasesAsync(itemType, verifyPurchase);
var purchase = purchases.FirstOrDefault(p => p.ProductId == productSku && payload.Equals(p.DeveloperPayload));
return purchase;
}
if (verifyPurchase == null || await verifyPurchase.VerifyPurchase(data, sign))
{
var purchase = JsonConvert.DeserializeObject<Purchase>(data);
if (purchase.ProductId == productSku && payload.Equals(purchase.DeveloperPayload))
return purchase;
}
return null;
}
/// <summary>
/// Connect to billing service
/// </summary>
/// <returns>If Success</returns>
public override Task<bool> ConnectAsync()
{
serviceConnection = new InAppBillingServiceConnection(Context);
return serviceConnection.ConnectAsync();
}
/// <summary>
/// Disconnect from the billing service
/// </summary>
/// <returns>Task to disconnect</returns>
public async override Task DisconnectAsync()
{
try
{
if (serviceConnection == null)
return;
await serviceConnection.DisconnectAsync();
serviceConnection.Dispose();
serviceConnection = null;
}
catch (System.Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Unable to disconned: {ex.Message}");
}
}
//inapp:{Context.PackageName}:{productSku}
/// <summary>
/// Consume a purchase with a purchase token.
/// </summary>
/// <param name="productId">Id or Sku of product</param>
/// <param name="purchaseToken">Original Purchase Token</param>
/// <returns>If consumed successful</returns>
public override Task<InAppBillingPurchase> ConsumePurchaseAsync(string productId, string purchaseToken)
{
if (serviceConnection?.Service == null)
{
throw new InAppBillingPurchaseException(PurchaseError.ServiceUnavailable, "You are not connected to the Google Play App store.");
}
var response = serviceConnection.Service.ConsumePurchase(3, Context.PackageName, purchaseToken);
var result = ParseConsumeResult(response);
if (!result)
return null;
var purchase = new InAppBillingPurchase
{
Id = string.Empty,
PurchaseToken = purchaseToken,
State = PurchaseState.Purchased,
ConsumptionState = ConsumptionState.Consumed,
AutoRenewing = false,
Payload = string.Empty,
ProductId = productId,
TransactionDateUtc = DateTime.UtcNow
};
return Task.FromResult(purchase);
}
bool ParseConsumeResult(int response)
{
switch (response)
{
case 0:
return true;
case 1:
//User Cancelled, should try again
throw new InAppBillingPurchaseException(PurchaseError.UserCancelled);
case 2:
//Network connection is down
throw new InAppBillingPurchaseException(PurchaseError.ServiceUnavailable);
case 3:
//Billing Unavailable
throw new InAppBillingPurchaseException(PurchaseError.BillingUnavailable);
case 4:
//Item Unavailable
throw new InAppBillingPurchaseException(PurchaseError.ItemUnavailable);
case 5:
//Developer Error
throw new InAppBillingPurchaseException(PurchaseError.DeveloperError);
case 6:
//Generic Error
throw new InAppBillingPurchaseException(PurchaseError.GeneralError);
default:
return false;
}
}
/// <summary>
/// Consume a purchase
/// </summary>
/// <param name="productId">Id/Sku of the product</param>
/// <param name="payload">Developer specific payload of original purchase</param>
/// <param name="itemType">Type of product being consumed.</param>
/// <param name="verifyPurchase">Verify Purchase implementation</param>
/// <returns>If consumed successful</returns>
public async override Task<InAppBillingPurchase> ConsumePurchaseAsync(string productId, ItemType itemType, string payload, IInAppBillingVerifyPurchase verifyPurchase)
{
if (serviceConnection?.Service == null)
throw new InAppBillingPurchaseException(PurchaseError.ServiceUnavailable, "You are not connected to the Google Play App store.");
if (payload == null)
throw new ArgumentNullException(nameof(payload), "Payload can not be null");
var purchases = await GetPurchasesAsync(itemType, verifyPurchase);
var purchase = purchases.FirstOrDefault(p => p.ProductId == productId && p.Payload == payload && p.ConsumptionState == ConsumptionState.NoYetConsumed);
if(purchase == null)
{
purchase = purchases.FirstOrDefault(p => p.ProductId == productId && p.Payload == payload);
}
if (purchase == null)
{
Console.WriteLine("Unable to find a purchase with matching product id and payload");
return null;
}
var response = serviceConnection.Service.ConsumePurchase(3, Context.PackageName, purchase.PurchaseToken);
var result = ParseConsumeResult(response);
if (!result)
return null;
return purchase;
}
/// <summary>
/// Must override handle activity and pass back results here.
/// </summary>
/// <param name="requestCode"></param>
/// <param name="resultCode"></param>
/// <param name="data"></param>
public static void HandleActivityResult(int requestCode, Result resultCode, Intent data)
{
if (PURCHASE_REQUEST_CODE != requestCode)
{
return;
}
if(resultCode == Result.Canceled && tcsPurchase != null && !tcsPurchase.Task.IsCompleted)
{
tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.UserCancelled));
return;
}
if(data == null)
{
return;
}
int responseCode = data.GetIntExtra(RESPONSE_CODE, 0);
switch (responseCode)
{
case 0:
//Reponse returned OK
var purchaseData = data.GetStringExtra(RESPONSE_IAP_DATA);
var dataSignature = data.GetStringExtra(RESPONSE_IAP_DATA_SIGNATURE);
tcsPurchase?.TrySetResult(new PurchaseResponse
{
PurchaseData = purchaseData,
DataSignature = dataSignature
});
break;
case RESPONSE_CODE_RESULT_USER_CANCELED:
tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.UserCancelled));
break;
case RESPONSE_CODE_RESULT_SERVICE_UNAVAILABLE:
tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.ServiceUnavailable));
break;
case BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE:
tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.ItemUnavailable));
break;
case BILLING_RESPONSE_RESULT_DEVELOPER_ERROR:
tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.DeveloperError));
break;
case BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED:
tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.AlreadyOwned));
break;
case BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED:
tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.NotOwned));
break;
default:
tcsPurchase.SetException(new InAppBillingPurchaseException(PurchaseError.GeneralError, responseCode.ToString()));
break;
}
}
[Preserve(AllMembers = true)]
class PurchaseResponse
{
public string PurchaseData { get; set; }
public string DataSignature { get; set; }
}
InAppBillingServiceConnection serviceConnection;
static TaskCompletionSource<PurchaseResponse> tcsPurchase;
static readonly object purchaseLocker = new object();
static bool ValidOwnedItems(Bundle purchased)
{
return purchased.ContainsKey(RESPONSE_IAP_PURCHASE_ITEM_LIST)
&& purchased.ContainsKey(RESPONSE_IAP_PURCHASE_DATA_LIST)
&& purchased.ContainsKey(RESPONSE_IAP_DATA_SIGNATURE_LIST);
}
static int GetResponseCodeFromBundle(Bundle bunble)
{
object response = bunble.Get(RESPONSE_CODE);
if (response == null)
{
//Bundle with null response code, assuming OK (known issue)
return 0;
}
if (response is Number)
{
return ((Java.Lang.Number)response).IntValue();
}
return 6; // Unknown error
}
[Preserve(AllMembers = true)]
class InAppBillingServiceConnection : Java.Lang.Object, IServiceConnection
{
public InAppBillingServiceConnection(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
{
Context = Application.Context;
}
public InAppBillingServiceConnection()
{
Context = Application.Context;
}
public InAppBillingServiceConnection(Context context)
{
Context = context;
}
TaskCompletionSource<bool> tcsConnect;
public Context Context { get; private set; }
public IInAppBillingService Service { get; private set; }
public bool IsConnected { get; private set; }
public Task<bool> ConnectAsync()
{
if (IsConnected)
return Task.FromResult(true);
tcsConnect = new TaskCompletionSource<bool>();
var serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
if(serviceIntent == null)
return Task.FromResult(false);
serviceIntent.SetPackage("com.android.vending");
if (Context.PackageManager.QueryIntentServices(serviceIntent, 0).Any())
{
Context.BindService(serviceIntent, this, Bind.AutoCreate);
return tcsConnect?.Task ?? Task.FromResult(false);
}
return Task.FromResult(false);
}
/// <summary>
/// Disconnect from payment service
/// </summary>
/// <returns></returns>
public Task DisconnectAsync()
{
if (!IsConnected)
return Task.CompletedTask;
Context?.UnbindService(this);
IsConnected = false;
Service = null;
return Task.CompletedTask;
}
public void OnServiceConnected(ComponentName name, IBinder service)
{
Service = IInAppBillingServiceStub.AsInterface(service);
if (Service == null || Context == null)
{
tcsConnect?.TrySetResult(false);
return;
}
var pkgName = Context.PackageName;
if (Service.IsBillingSupported(3, pkgName, ITEM_TYPE_SUBSCRIPTION) == 0)
{
IsConnected = true;
tcsConnect?.TrySetResult(true);
return;
}
tcsConnect?.TrySetResult(false);
}
public void OnServiceDisconnected(ComponentName name)
{
}
}
[Preserve(AllMembers = true)]
class Product
{
[JsonConstructor]
public Product()
{
}
[JsonProperty(PropertyName = "title")]
public string Title { get; set; }
[JsonProperty(PropertyName = "price")]
public string Price { get; set; }
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "productId")]
public string ProductId { get; set; }
[JsonProperty(PropertyName = "price_currency_code")]
public string CurrencyCode { get; set; }
[JsonProperty(PropertyName = "price_amount_micros")]
public Int64 MicrosPrice { get; set; }
public override string ToString()
{
return string.Format("[Product: Title={0}, Price={1}, Type={2}, Description={3}, ProductId={4}]", Title, Price, Type, Description, ProductId);
}
}
[Preserve(AllMembers = true)]
class Purchase
{
[JsonConstructor]
public Purchase()
{
}
[JsonProperty(PropertyName = "autoRenewing")]
public bool AutoRenewing { get; set; }
[JsonProperty(PropertyName = "packageName")]
public string PackageName { get; set; }
[JsonProperty(PropertyName = "orderId")]
public string OrderId { get; set; }
[JsonProperty(PropertyName = "productId")]
public string ProductId { get; set; }
[JsonProperty(PropertyName = "developerPayload")]
public string DeveloperPayload { get; set; }
[JsonProperty(PropertyName = "purchaseTime")]
public Int64 PurchaseTime { get; set; }
/// <summary>
/// purchase state
/// </summary>
[JsonProperty(PropertyName = "purchaseState")]
public int PurchaseState { get; set; }
[JsonProperty(PropertyName = "purchaseToken")]
public string PurchaseToken { get; set; }
[JsonProperty(PropertyName = "consumptionState")]
public int ConsumptionState { get; set; }
/// <summary>
/// for subscriptions
/// </summary>
[JsonProperty(PropertyName = "paymentState")]
public int PaymentState { get; set; }
[JsonIgnore]
public PurchaseState State
{
get
{
if (PurchaseState == 0)
return Abstractions.PurchaseState.Purchased;
else if (PurchaseState == 1)
return Abstractions.PurchaseState.Canceled;
else if (PurchaseState == 2)
return Abstractions.PurchaseState.Refunded;
return Abstractions.PurchaseState.Unknown;
}
}
[JsonIgnore]
public ConsumptionState ConsumedState => ConsumptionState == 0 ? Abstractions.ConsumptionState.NoYetConsumed : Abstractions.ConsumptionState.Consumed;
[JsonIgnore]
public PurchaseState SubscriptionState
{
get
{
if (PaymentState == 0)
return Abstractions.PurchaseState.PaymentPending;
else if (PaymentState == 1)
return Abstractions.PurchaseState.Purchased;
else if (PaymentState == 2)
return Abstractions.PurchaseState.FreeTrial;
return Abstractions.PurchaseState.Unknown;
}
}
public override string ToString()
{
return string.Format("[Purchase: PackageName={0}, OrderId={1}, ProductId={2}, DeveloperPayload={3}, PurchaseTime={4}, PurchaseState={5}, PurchaseToken={6}]", PackageName, OrderId, ProductId, DeveloperPayload, PurchaseTime, PurchaseState, PurchaseToken);
}
}
/// <summary>
/// Utility security class to verify the purchases
/// </summary>
[Preserve(AllMembers = true)]
public static class InAppBillingSecurity
{
/// <summary>
/// Verifies the purchase.
/// </summary>
/// <returns><c>true</c>, if purchase was verified, <c>false</c> otherwise.</returns>
/// <param name="publicKey">Public key.</param>
/// <param name="signedData">Signed data.</param>
/// <param name="signature">Signature.</param>
public static bool VerifyPurchase(string publicKey, string signedData, string signature)
{
if (signedData == null)
{
Console.WriteLine("Security. data is null");
return false;
}
if (!string.IsNullOrEmpty(signature))
{
var key = InAppBillingSecurity.GeneratePublicKey(publicKey);
bool verified = InAppBillingSecurity.Verify(key, signedData, signature);
if (!verified)
{
Console.WriteLine("Security. Signature does not match data.");
return false;
}
}
return true;
}
/// <summary>
/// Generates the public key.
/// </summary>
/// <returns>The public key.</returns>
/// <param name="encodedPublicKey">Encoded public key.</param>
public static IPublicKey GeneratePublicKey(string encodedPublicKey)
{
try
{
var keyFactory = KeyFactory.GetInstance(KeyFactoryAlgorithm);
return keyFactory.GeneratePublic(new X509EncodedKeySpec(Android.Util.Base64.Decode(encodedPublicKey, 0)));
}
catch (NoSuchAlgorithmException e)
{
Console.WriteLine(e.Message);
throw new RuntimeException(e);
}
catch (Java.Lang.Exception e)
{
Console.WriteLine(e.Message);
throw new IllegalArgumentException();
}
}
/// <summary>
/// Verify the specified publicKey, signedData and signature.
/// </summary>
/// <param name="publicKey">Public key.</param>
/// <param name="signedData">Signed data.</param>
/// <param name="signature">Signature.</param>
public static bool Verify(IPublicKey publicKey, string signedData, string signature)
{
Console.WriteLine("Signature: {0}", signature);
try
{
var sign = Signature.GetInstance(SignatureAlgorithm);
sign.InitVerify(publicKey);
sign.Update(Encoding.UTF8.GetBytes(signedData));
if (!sign.Verify(Android.Util.Base64.Decode(signature, 0)))
{
Console.WriteLine("Security. Signature verification failed.");
return false;
}
return true;
}
catch (System.Exception e)
{
Console.WriteLine(e.Message);
}
return false;
}
/// <summary>
/// Simple string transform via:
/// http://stackoverflow.com/questions/11671865/how-to-protect-google-play-public-key-when-doing-inapp-billing
/// </summary>
/// <param name="key">key to transform</param>
/// <param name="i">XOR Offset</param>
/// <returns></returns>
public static string TransformString(string key, int i)
{
var chars = key.ToCharArray(); ;
for (int j = 0; j < chars.Length; j++)
chars[j] = (char)(chars[j] ^ i);
return new string(chars);
}
const string KeyFactoryAlgorithm = "RSA";
const string SignatureAlgorithm = "SHA1withRSA";
}
}
}