-
-
Notifications
You must be signed in to change notification settings - Fork 531
/
PurchasePlugin.java
1297 lines (1187 loc) · 49.7 KB
/
PurchasePlugin.java
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
/**
* The Cordova Purchase Plugin for Google Play.
*
* The plugin has methods for:
*
* - initializing the Google Play BillingClient,
* - querying product details
* - making purchases
* - consuming purchases.
* - handling purchase updates and errors.
*
* @author Jean-Christophe Hoelt - Fovea.cc
*/
package cc.fovea;
// import com.android.billingclient.api.PriceChangeConfirmationListener;
// import com.android.billingclient.api.PriceChangeFlowParams;
// import com.android.billingclient.api.ProductDetails.PricingPhases;
// import java.io.IOException;
// import java.lang.reflect.Array;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClient.BillingResponseCode;
import com.android.billingclient.api.BillingClient.FeatureType;
import com.android.billingclient.api.BillingClient.ProductType;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingFlowParams.ProductDetailsParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.ProductDetails;
import com.android.billingclient.api.ProductDetails.OneTimePurchaseOfferDetails;
import com.android.billingclient.api.ProductDetails.PricingPhase;
import com.android.billingclient.api.ProductDetails.SubscriptionOfferDetails;
import com.android.billingclient.api.ProductDetailsResponseListener;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesResponseListener;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.QueryProductDetailsParams;
import com.android.billingclient.api.QueryProductDetailsParams.Product;
import com.android.billingclient.api.QueryPurchasesParams;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Plugin implementation for Google Play.
*/
public final class PurchasePlugin
extends CordovaPlugin
implements PurchasesUpdatedListener,
ConsumeResponseListener,
AcknowledgePurchaseResponseListener {
/** Tag used for log messages. */
private final String mTag = "CdvPurchase";
/**
* Context for the last plugin call.
*
* <p>See execute(), callSuccess() and callError().</p>
*/
private CallbackContext mCallbackContext;
/** A reference to BillingClient. */
private BillingClient mBillingClient;
/** List of registered IN_APP product identifiers. */
private List<String> mInAppProductIds = new ArrayList<String>();
/**
* Register additional IN_APP product identifiers.
*
* @param list - List of product identifiers to register.
*/
private void addInAppProductIds(final List<String> list) {
for (int i = 0; i < list.size(); ++i) {
if (!mInAppProductIds.contains(list.get(i))) {
mInAppProductIds.add(list.get(i));
}
}
}
/**
* List of registered SUBS product identifiers.
*/
private List<String> mSubsProductIds = new ArrayList<String>();
/**
* Register additional SUBS product identifiers.
*
* @param list - List of product identifiers to register.
*/
private void addSubsProductIds(final List<String> list) {
for (int i = 0; i < list.size(); ++i) {
if (!mSubsProductIds.contains(list.get(i))) {
mSubsProductIds.add(list.get(i));
}
}
}
/** List of purchases reported by the Billing library. */
private final List<Purchase> mPurchases = new ArrayList<>();
/** True if billing service is connected now. */
private boolean mIsServiceConnected;
/** Value for mBillingClientResult until BillingClient is connected. */
public static final int BILLING_CLIENT_NOT_CONNECTED = -1;
/** Last response from the billing client. */
private BillingResult mBillingClientResult = BillingResult.newBuilder()
.setResponseCode(BILLING_CLIENT_NOT_CONNECTED).build();
/** Last result from the billing client.
* @return the latest BillingResult */
private BillingResult getLastResult() {
return mBillingClientResult;
}
/**
* Last response code from the billing client.
*
* @return The last response code from the billing client.
*/
private int getLastResponseCode() {
return mBillingClientResult.getResponseCode();
}
/**
* Set last result to the given code.
*
* @param responseCode The response code to set.
*/
private void resetLastResult(final int responseCode) {
mBillingClientResult = BillingResult
.newBuilder()
.setResponseCode(responseCode)
.setDebugMessage("")
.build();
}
/** Product details loaded from GooglePlay, indexed by product identifier. */
private final HashMap<String, ProductDetails> mProductDetails =
new HashMap<String, ProductDetails>();
/** List of purchase tokens being consumed. */
private Set<String> mTokensToBeConsumed = new HashSet<>();
@Override
public void initialize(
final CordovaInterface cordova,
final CordovaWebView webView) {
super.initialize(cordova, webView);
// your init code here
}
/**
* Context used to send messages to the javascript side.
*
* @see GooglePlay.Bridge
*/
private CallbackContext mListenerContext = null;
/**
* Send a message to the javascript bridge (GooglePlay.Bridge).
*
* @param type Message type / identifer.
* @param data Message arguments.
*/
private void sendToListener(final String type, final JSONObject data) {
try {
Log.d(mTag, "sendToListener() -> " + type);
Log.d(mTag, " data -> " + data.toString());
if (mListenerContext == null) {
return;
}
final JSONObject message = new JSONObject()
.put("type", type);
if (data != null) {
message.put("data", data);
}
final PluginResult result =
new PluginResult(PluginResult.Status.OK, message);
result.setKeepCallback(true);
mListenerContext.sendPluginResult(result);
} catch (JSONException e) {
Log.d(mTag, "sendToListener() -> Failed: " + e.getMessage());
}
}
@Override
public boolean execute(final String action,
final JSONArray data,
final CallbackContext callbackContext) {
if ("setListener".equals(action)) {
mListenerContext = callbackContext;
sendToListener("ready", new JSONObject());
return true;
}
this.mCallbackContext = callbackContext;
// Check if the action has a handler
Boolean isValidAction = true;
try {
// Action selector
if ("init".equals(action)) {
init();
} else if ("getAvailableProducts".equals(action)) {
final List<String> inAppSkus = parseStringArrayAtIndex(data, 0);
final List<String> subsSkus = parseStringArrayAtIndex(data, 1);
this.addInAppProductIds(inAppSkus);
this.addSubsProductIds(subsSkus);
getAvailableProducts(mInAppProductIds, mSubsProductIds);
} else if ("getPurchases".equals(action)) {
getPurchases();
} else if ("consumePurchase".equals(action)) {
final String purchaseToken = data.getString(0);
consumePurchase(purchaseToken);
} else if ("acknowledgePurchase".equals(action)) {
final String purchaseToken = data.getString(0);
acknowledgePurchase(purchaseToken);
} else if ("buy".equals(action)) {
buy(data);
} else if ("subscribe".equals(action)) {
subscribe(data);
} else if ("manageSubscriptions".equals(action)) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/account/subscriptions"));
cordova.getActivity().startActivity(browserIntent);
} else if ("manageBilling".equals(action)) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/paymentmethods"));
cordova.getActivity().startActivity(browserIntent);
} else if ("launchPriceChangeConfirmationFlow".equals(action)) {
// final String sku = data.getString(0);
// launchPriceChangeConfirmationFlow(sku);
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/account/subscriptions"));
cordova.getActivity().startActivity(browserIntent);
} else {
// No handler for the action
isValidAction = false;
}
} catch (IllegalStateException e) {
callError(Constants.ERR_UNKNOWN, e.getMessage());
} catch (JSONException e) {
callError(Constants.ERR_UNKNOWN, e.getMessage());
}
// Method not found
return isValidAction;
}
private String getPublicKey() {
int billingKeyFromParam =
cordova.getActivity().getResources().getIdentifier(
"billing_key_param",
"string",
cordova.getActivity().getPackageName());
if (billingKeyFromParam > 0) {
final String ret = cordova.getActivity().getString(billingKeyFromParam);
if (ret.length() > 0) {
return ret;
}
}
int billingKeyIdentifier =
cordova.getActivity().getResources().getIdentifier(
"billing_key",
"string",
cordova.getActivity().getPackageName());
return cordova.getActivity().getString(billingKeyIdentifier);
}
// Initialize the plugin
private void init() {
Log.d(mTag, "init()");
mBillingClient = BillingClient
.newBuilder(cordova.getActivity())
.enablePendingPurchases()
.setListener(this)
.build();
resetLastResult(BILLING_CLIENT_NOT_CONNECTED);
startServiceConnection(() -> {
if (getLastResponseCode() == BillingResponseCode.OK) {
Log.d(mTag, "init() -> Success");
callSuccess();
} else {
Log.d(mTag, "init() -> Failed: " + format(getLastResult()));
callError(Constants.ERR_SETUP,
"Setup failed. " + format(getLastResult()));
}
}, () -> {
Log.d(mTag, "init() -> Failure: " + format(getLastResult()));
callError(Constants.ERR_SETUP, "Setup failure. " + format(getLastResult()));
});
}
private void getPurchases() {
Log.d(mTag, "getPurchases()");
queryPurchases();
}
private void onQueryPurchasesFinished(
final BillingResult result,
final List<Purchase> purchases) {
try {
if (result.getResponseCode() == BillingResponseCode.OK) {
for (Purchase p : purchases) {
mPurchases.add(0, p);
}
sendToListener("setPurchases", new JSONObject()
.put("purchases", toJSON(purchases)));
callSuccess(toJSON(purchases));
} else {
callError(Constants.ERR_LOAD, "Failed to query purchases: "
+ result.getResponseCode());
}
} catch (Exception e) {
Log.e(mTag, "onQueryPurchasesFinished() -> Failed: " + e.getMessage());
callError(Constants.ERR_LOAD,
"Failed to query purchases: " + e.getMessage());
}
}
// Convert list of purchases to JSON
private JSONArray toJSON(final List<Purchase> purchaseList) throws JSONException {
// Convert the java list to json
JSONArray jsonPurchaseList = new JSONArray();
for (Purchase p : purchaseList) {
jsonPurchaseList.put(toJSON(p));
}
return jsonPurchaseList;
}
private JSONObject toJSON(final Purchase p) throws JSONException {
return new JSONObject(p.getOriginalJson())
.put("productIds", new JSONArray(p.getProducts()))
.put("orderId", p.getOrderId())
.put("getPurchaseState", p.getPurchaseState())
.put("developerPayload", p.getDeveloperPayload())
.put("acknowledged", p.isAcknowledged())
.put("autoRenewing", p.isAutoRenewing())
.put("accountId", p.getAccountIdentifiers().getObfuscatedAccountId())
.put("profileId", p.getAccountIdentifiers().getObfuscatedProfileId())
.put("signature", p.getSignature())
.put("receipt", p.getOriginalJson().toString());
}
BillingResult mInAppResult;
BillingResult mSubsResult;
/**
* Query purchases across various use cases and deliver the result in a
* formalized way through a listener.
*/
public void queryPurchases() {
Log.d(mTag, "queryPurchases()");
executeServiceRequest(() -> {
long time = System.currentTimeMillis();
List<Purchase> allPurchases = new ArrayList<Purchase>();
mInAppResult = null;
mSubsResult = null;
mBillingClient.queryPurchasesAsync(
QueryPurchasesParams.newBuilder().setProductType(ProductType.INAPP).build(),
new PurchasesResponseListener() {
public void onQueryPurchasesResponse(BillingResult billingResult, List<Purchase> purchases) {
mInAppResult = billingResult;
Log.i(mTag, "queryPurchases(INAPP) -> Elapsed time: " + (System.currentTimeMillis() - time) + "ms");
if (billingResult.getResponseCode() == BillingResponseCode.OK)
allPurchases.addAll(purchases);
if (mInAppResult != null && (mSubsResult != null || !areSubscriptionsSupported()))
onQueryPurchasesFinished(mInAppResult.getResponseCode() == BillingResponseCode.OK ? mInAppResult : mSubsResult, allPurchases);
}
}
);
if (areSubscriptionsSupported()) {
mBillingClient.queryPurchasesAsync(
QueryPurchasesParams.newBuilder().setProductType(ProductType.SUBS).build(),
new PurchasesResponseListener() {
public void onQueryPurchasesResponse(BillingResult billingResult, List<Purchase> purchases) {
mSubsResult = billingResult;
Log.i(mTag, "queryPurchases(SUBS) -> Elapsed time: " + (System.currentTimeMillis() - time) + "ms");
if (billingResult.getResponseCode() == BillingResponseCode.OK)
allPurchases.addAll(purchases);
if (mInAppResult != null && (mSubsResult != null || !areSubscriptionsSupported()))
onQueryPurchasesFinished(mInAppResult.getResponseCode() == BillingResponseCode.OK ? mInAppResult : mSubsResult, allPurchases);
}
}
);
}
else {
Log.i(mTag, "queryPurchases() -> "
+ "Subscriptions are not supported, skipped.");
}
// Log.i(mTag, "queryPurchases() -> Elapsed time: "
// + (System.currentTimeMillis() - time) + "ms");
// If there are subscriptions supported, we add subscription rows as well
// if (areSubscriptionsSupported()) {
// PurchasesResult subscriptionResult =
// mBillingClient.queryPurchases(ProductType.SUBS);
// Log.i(mTag, "queryPurchases() -> Subscriptions elapsed time: "
// + (System.currentTimeMillis() - time) + "ms");
// int purchasesListSize = -1;
// if (subscriptionResult.getPurchasesList() != null) {
// purchasesListSize = subscriptionResult.getPurchasesList().size();
// }
// Log.i(mTag, "queryPurchases() -> Subscriptions result code: "
// + subscriptionResult.getResponseCode()
// + " res: " + purchasesListSize);
// if (subscriptionResult.getResponseCode() == BillingResponseCode.OK && subscriptionResult.getPurchasesList() != null) {
// if purchases failed but subs succeed, better return a success anyway.
// (so the app has something to show)
// result = subscriptionResult.getBillingResult();
// allPurchases.addAll(subscriptionResult.getPurchasesList());
// } else {
// Log.e(mTag, "queryPurchases() -> "
// + "Error trying to query subscription purchases.");
// }
// } else if (purchasesResult.getResponseCode() == BillingResponseCode.OK) {
// Log.i(mTag, "queryPurchases() -> "
// + "Subscriptions are not supported, skipped.");
// } else {
// Log.w(mTag, "queryPurchases() -> Error response code: "
// + purchasesResult.getResponseCode());
// }
// onQueryPurchasesFinished(result, allPurchases);
});
}
/**
* Checks if subscriptions are supported for current client
* <p>Note: This method does not automatically retry for RESULT_SERVICE_DISCONNECTED.
* It is only used in unit tests and after queryPurchases execution, which already has
* a retry-mechanism implemented.
* </p>
*/
public boolean areSubscriptionsSupported() {
BillingResult result =
mBillingClient.isFeatureSupported(FeatureType.SUBSCRIPTIONS);
if (result.getResponseCode() != BillingResponseCode.OK) {
Log.w(mTag, "areSubscriptionsSupported() -> Failed: "
+ format(result));
return false;
}
return true;
}
private JSONObject productDetailsToJson(ProductDetails product) throws JSONException {
JSONObject ret = new JSONObject()
.put("productId", product.getProductId())
.put("title", product.getTitle())
.put("name", product.getName())
.put("description", product.getDescription());
if (product.getProductType().equals(ProductType.INAPP)) {
final OneTimePurchaseOfferDetails details = product.getOneTimePurchaseOfferDetails();
ret
.put("product_type", "inapp")
.put("product_format", "v11.0")
.put("formatted_price", details.getFormattedPrice())
.put("price_amount_micros", details.getPriceAmountMicros())
.put("price_currency_code", details.getPriceCurrencyCode());
}
else if (product.getProductType().equals(ProductType.SUBS)) {
// Subscription are now described in v12.0 product format.
ret
.put("product_format", "v12.0")
.put("product_type", "subs");
JSONArray offers = new JSONArray();
// let's add in the array of offers.
List<SubscriptionOfferDetails> subscriptionOfferDetailsList = product.getSubscriptionOfferDetails();
for (SubscriptionOfferDetails details: subscriptionOfferDetailsList) {
JSONObject offer = new JSONObject()
.put("base_plan_id", details.getBasePlanId())
.put("offer_id", details.getOfferId())
.put("token", details.getOfferToken())
.put("tags", new JSONArray(details.getOfferTags()));
JSONArray pricingPhases = new JSONArray();
if (details.getPricingPhases() != null) {
for (PricingPhase pricing: details.getPricingPhases().getPricingPhaseList()) {
JSONObject pricingPhase = new JSONObject()
.put("billing_cycle_count", pricing.getBillingCycleCount())
.put("billing_period", pricing.getBillingPeriod())
.put("formatted_price", pricing.getFormattedPrice())
.put("price_amount_micros", pricing.getPriceAmountMicros())
.put("price_currency_code", pricing.getPriceCurrencyCode());
if (pricing.getRecurrenceMode() == ProductDetails.RecurrenceMode.FINITE_RECURRING) {
// The billing plan payment recurs for a fixed number of billing period set in billingCycleCount.
pricingPhase.put("recurrence_mode", "FINITE_RECURRING");
}
else if (pricing.getRecurrenceMode() == ProductDetails.RecurrenceMode.INFINITE_RECURRING) {
// The billing plan payment recurs for infinite billing periods unless cancelled.
pricingPhase.put("recurrence_mode", "INFINITE_RECURRING");
}
else if (pricing.getRecurrenceMode() == ProductDetails.RecurrenceMode.NON_RECURRING) {
// The billing plan payment is a one time charge that does not repeat.
pricingPhase.put("recurrence_mode", "NON_RECURRING");
}
pricingPhases.put(pricingPhase);
}
}
else {
ret.put("product_format", "unknown");
}
offer.put("pricing_phases", pricingPhases);
offers.put(offer);
}
ret.put("offers", offers);
}
// productId: string;
// title: string;
// name: string;
// * billing_period: string;
// * billing_period_unit: string;
// description: string;
// * formatted_price: string;
// * price_amount_micros: string;
// * price_currency_code: string;
// * trial_period: string;
// * trial_period_unit: string;
// * freeTrialPeriod: string;
// * introductoryPrice: string;
// * introductoryPriceAmountMicros: string;
// * introductoryPriceCycles: string;
// * introductoryPricePeriod: string;
// * subscriptionPeriod: string;
return ret;
}
private void getAvailableProducts(List<String> inAppProductIds, List<String> subsProductIds) {
Log.d(mTag, "getAvailableProducts()");
queryAllProductDetails(inAppProductIds, subsProductIds, new ProductDetailsResponseListener() {
@Override
public void onProductDetailsResponse(
final BillingResult result,
final List<ProductDetails> productDetailsList) {
if (result.getResponseCode() != BillingResponseCode.OK) {
Log.d(mTag, "getAvailableProducts() -> Failed: " + format(result));
callError(Constants.ERR_LOAD, "Failed to load Products, code: "
+ result.getResponseCode());
return;
}
JSONArray jsonProductList = new JSONArray();
try {
for (ProductDetails product : productDetailsList) {
Log.d(mTag, "getAvailableProducts() -> productDetails: " + product.toString());
jsonProductList.put(productDetailsToJson(product));
}
Log.d(mTag, "getAvailableProducts() -> Success");
callSuccess(jsonProductList);
} catch (JSONException e) {
Log.d(mTag, "getAvailableProducts() -> Failed: " + e.getMessage());
callError(Constants.ERR_LOAD, e.getMessage());
}
}
});
}
private Purchase findPurchaseByToken(final String purchaseToken) {
for (Purchase p : mPurchases) {
if (p.getPurchaseToken().equals(purchaseToken))
return p;
}
return null;
}
private Purchase findPurchaseByProductId(final String productId) {
for (Purchase p : mPurchases) {
if (p.getSkus().contains(productId))
return p;
}
return null;
}
/** Implements PurchasesUpdatedListener.
*
* @param result Purchase result
* @param purchases Array of purchases
*/
@Override
public void onPurchasesUpdated(
final BillingResult result,
final List<Purchase> purchases) {
try {
final int code = result.getResponseCode();
if (code == BillingResponseCode.OK && purchases != null && purchases.size() > 0) {
Log.d(mTag, "onPurchasesUpdated() -> Success");
for (Purchase p : purchases) {
mPurchases.add(0, p);
}
callSuccess();
sendToListener("purchasesUpdated", new JSONObject()
.put("purchases", toJSON(purchases)));
}
else if (code == BillingResponseCode.USER_CANCELED) {
Log.w(mTag, "onPurchasesUpdated() -> "
+ "Cancelled: " + format(result));
callError(Constants.ERR_CANCELLED, codeToString(code));
}
else {
Log.w(mTag, "onPurchasesUpdated() -> "
+ "Failed: " + format(result));
callError(Constants.ERR_PURCHASE, codeToString(code));
}
} catch (JSONException e) {
Log.w(mTag, "onPurchasesUpdated() -> JSONException "
+ e.getMessage());
callError(Constants.ERR_PURCHASE, e.getMessage());
}
}
private String codeToString(int code) {
switch (code) {
case BillingResponseCode.BILLING_UNAVAILABLE:
return "BILLING_UNAVAILABLE"; // Billing API version is not supported for the type requested
case BillingResponseCode.DEVELOPER_ERROR:
return "DEVELOPER_ERROR"; // Invalid arguments provided to the API.
case BillingResponseCode.ERROR:
return "ERROR"; // Fatal error during the API action
case BillingResponseCode.FEATURE_NOT_SUPPORTED:
return "FEATURE_NOT_SUPPORTED"; // Requested feature is not supported by Play Store on the current device.
case BillingResponseCode.ITEM_ALREADY_OWNED:
return "ITEM_ALREADY_OWNED"; // Failure to purchase since item is already owned
case BillingResponseCode.ITEM_NOT_OWNED:
return "ITEM_NOT_OWNED"; // Failure to consume since item is not owned
case BillingResponseCode.ITEM_UNAVAILABLE:
return "ITEM_UNAVAILABLE"; // Requested product is not available for purchase
case BillingResponseCode.OK:
return "OK"; // Success
case BillingResponseCode.SERVICE_DISCONNECTED:
return "SERVICE_DISCONNECTED"; // Play Store service is not connected now - potentially transient state.
case BillingResponseCode.SERVICE_TIMEOUT:
return "SERVICE_TIMEOUT"; // The request has reached the maximum timeout before Google Play responds.
case BillingResponseCode.SERVICE_UNAVAILABLE:
return "SERVICE_UNAVAILABLE"; // Network connection is down
case BillingResponseCode.USER_CANCELED:
return "USER_CANCELED"; // User pressed back or canceled a dialog
default:
return "CODE_" + code;
}
}
private String codeToMessage(int code) {
switch (code) {
case BillingResponseCode.BILLING_UNAVAILABLE:
return "Billing API version is not supported for the type requested";
case BillingResponseCode.DEVELOPER_ERROR:
return "Invalid arguments provided to the API";
case BillingResponseCode.ERROR:
return "Fatal error during the API action";
case BillingResponseCode.FEATURE_NOT_SUPPORTED:
return "Requested feature is not supported by Play Store on the current device";
case BillingResponseCode.ITEM_ALREADY_OWNED:
return "Failure to purchase since item is already owned";
case BillingResponseCode.ITEM_NOT_OWNED:
return "Failure to consume since item is not owned";
case BillingResponseCode.ITEM_UNAVAILABLE:
return "Requested product is not available for purchase";
case BillingResponseCode.OK:
return "Success";
case BillingResponseCode.SERVICE_DISCONNECTED:
return "Play Store service is not connected now - potentially transient state";
case BillingResponseCode.SERVICE_TIMEOUT:
return "The request has reached the maximum timeout before Google Play responds";
case BillingResponseCode.SERVICE_UNAVAILABLE:
return "Network connection is down";
case BillingResponseCode.USER_CANCELED:
return "User pressed back or canceled a dialog";
default:
return "Unknown error code";
}
}
private BillingFlowParams parseBillingFlowParams(JSONArray data) throws JSONException {
final String productIdAndOfferIndex = data.getString(0);
final JSONObject additionalData = data.getJSONObject(1);
final String[] productIdAndOfferIndexArray = productIdAndOfferIndex.split("@", 2);
String productId = null;
String offerToken = null;
// first option to pass-in the selected offer index is to use the "productId@offerIndex" syntax.
if (productIdAndOfferIndexArray.length == 2) {
productId = productIdAndOfferIndexArray[0];
offerToken = productIdAndOfferIndexArray[1];
}
else {
productId = productIdAndOfferIndex;
}
if (offerToken == null && additionalData.has("offerToken")) {
offerToken = additionalData.getString("offerToken");
}
// NOTE: developerPayload isn't supported anymore.
// https://developer.android.com/google/play/billing/developer-payload
// NOTE: oldSku and oldPurchasedSkus have been removed in billing library v4
// Specify the SKU that the user is upgrading or downgrading from.
// String oldSku = null;
// if (additionalData.has("oldPurchasedSkus")) {
// final JSONArray list = new JSONArray(
// additionalData.getString("oldPurchasedSkus"));
// int len = list.length();
// if (len > 0)
// oldSku = list.get(0).toString();
// }
// else if (additionalData.has("oldSku")) {
// oldSku = additionalData.getString("oldSku");
// }
String oldPurchaseToken = null;
if (additionalData.has("oldPurchaseToken")) {
oldPurchaseToken = additionalData.getString("oldPurchaseToken");
}
// Specify an optional obfuscated string of developer profile name. If
// you pass this value, Google Play can use it for payment risk
// evaluation. Do not use the account ID or the user's Google ID for this
// field.
// (removed from Google Play Billing library v3)
// final String developerId = additionalData.has("developerId")
// ? additionalData.getString("developerId")
// : null;
// Specify an optional obfuscated string that is uniquely associated with
// the user's account in your app.
//
// If you pass this value, Google Play can use it to detect irregular
// activity, such as many devices making purchases on the same account in
// a short period of time. Do not use the developer ID or the user's
// Google ID for this field. In addition, this field should not contain
// the user's ID in cleartext. We recommend that you use a one-way hash
// to generate a string from the user's ID and store the hashed string in
// this field.
final String accountId = additionalData.has("accountId")
? additionalData.getString("accountId")
: null;
final String profileId = additionalData.has("profileId")
? additionalData.getString("profileId")
: null;
final ProductDetails productDetails = mProductDetails.get(productId);
if (productDetails == null) {
Log.d(mTag, "buy() -> Failed: Product not registered: " + productId);
callError(Constants.ERR_PURCHASE, "Product not registered: " + productId);
return null;
}
BillingFlowParams.Builder params = BillingFlowParams.newBuilder();
// If not passed in additionalData, use the offer token based on the selected offer index.
final List<SubscriptionOfferDetails> subscriptionOfferDetails = productDetails.getSubscriptionOfferDetails();
if (offerToken == null && subscriptionOfferDetails != null) {
offerToken = subscriptionOfferDetails.get(0).getOfferToken();
}
List<ProductDetailsParams> productDetailsParamsList = new ArrayList<ProductDetailsParams>();
if (offerToken != null) {
productDetailsParamsList.add(ProductDetailsParams.newBuilder()
.setProductDetails(productDetails)
.setOfferToken(offerToken)
.build());
Log.d(mTag, "Product details id@token: " + productIdAndOfferIndexArray + " === " + productId + "@" + offerToken + " ... " + productDetails.toString());
}
else {
productDetailsParamsList.add(ProductDetailsParams.newBuilder()
.setProductDetails(productDetails)
.build());
}
BillingFlowParams.SubscriptionUpdateParams.Builder subscriptionUpdateParams =
BillingFlowParams.SubscriptionUpdateParams.newBuilder();
Boolean hasSubscriptionUpdateParams = false;
Log.d(mTag, "buy() -> setProductDetailsParamsList");
params.setProductDetailsParamsList(productDetailsParamsList);
// params.setProductDetails(productDetails);
// NOTE: This has been removed in billing library v4, use oldPurchaseToken now.
// if (oldSku != null && oldPurchaseToken != null) {
// Log.d(mTag, "buy() -> setOldSku");
// params.setOldSku(oldSku, oldPurchaseToken);
// }
if (oldPurchaseToken != null) {
Log.d(mTag, "buy() -> setOldSkuPurchaseToken");
subscriptionUpdateParams.setOldPurchaseToken(oldPurchaseToken);
hasSubscriptionUpdateParams = true;
}
// accountId and profileId are used to detect fraud.
// see https://developer.android.com/google/play/billing/security#fraud
if (accountId != null) {
Log.d(mTag, "buy() -> setObfuscatedAccountId");
// Google renamed setAccountId to setObfuscatedAccountId.
// the plugin was already obfuscating the accountId
// as md5(applicationUsername) => we can keep the same parameter.
params.setObfuscatedAccountId(accountId);
}
// Some applications allow users to have multiple profiles within a single
// account. Use this method to send the user's profile identifier to
// Google.
if (profileId != null) {
Log.d(mTag, "buy() -> setObfuscatedProfileId");
params.setObfuscatedProfileId(profileId);
}
// Google removed setDeveloperId
// if (developerId != null) {
// Log.d(mTag, "buy() -> setDeveloperId");
// params.setDeveloperId(developerId);
// }
// See https://developer.android.com/google/play/billing/subs#change
// Note that since Billing Library this is now a ReplacementMode
// https://developer.android.com/reference/com/android/billingclient/api/BillingFlowParams.SubscriptionUpdateParams.ReplacementMode
final String replacementMode = additionalData.has("prorationMode")
? additionalData.getString("prorationMode")
: additionalData.has("replacementMode")
? additionalData.getString("replacementMode")
: null;
if (replacementMode != null) {
if ("IMMEDIATE_WITH_TIME_PRORATION".equals(replacementMode))
subscriptionUpdateParams.setSubscriptionReplacementMode(BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.WITH_TIME_PRORATION);
else if ("IMMEDIATE_AND_CHARGE_PRORATED_PRICE".equals(replacementMode))
subscriptionUpdateParams.setSubscriptionReplacementMode(BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.CHARGE_PRORATED_PRICE);
else if ("IMMEDIATE_WITHOUT_PRORATION".equals(replacementMode))
subscriptionUpdateParams.setSubscriptionReplacementMode(BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.WITHOUT_PRORATION);
else if ("DEFERRED".equals(replacementMode))
subscriptionUpdateParams.setSubscriptionReplacementMode(BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.DEFERRED);
else if ("IMMEDIATE_AND_CHARGE_FULL_PRICE".equals(replacementMode))
subscriptionUpdateParams.setSubscriptionReplacementMode(BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.CHARGE_FULL_PRICE);
}
if (hasSubscriptionUpdateParams) {
params.setSubscriptionUpdateParams(subscriptionUpdateParams.build());
}
return params.build();
}
/** Subscribe to an item. */
private void subscribe(JSONArray data) throws JSONException {
Log.d(mTag, "subscribe()");
if (!areSubscriptionsSupported()) {
callError(Constants.ERR_PURCHASE, "FEATURE_NOT_SUPPORTED");
return;
}
initiatePurchaseFlow(parseBillingFlowParams(data));
}
/** Buy an item. */
private void buy(JSONArray data) throws JSONException {
Log.d(mTag, "buy()");
initiatePurchaseFlow(parseBillingFlowParams(data));
}
/** Start a purchase or subscription replace flow. */
public void initiatePurchaseFlow(final BillingFlowParams params) {
Log.d(mTag, "initiatePurchaseFlow()");
if (params == null) {
return;
}
executeServiceRequest(() -> {
if (getLastResponseCode() != BillingResponseCode.OK) {
Log.d(mTag, "initiatePurchaseFlow() -> Failed: "
+ "Failed to execute service request. " + format(getLastResult()));
callError(Constants.ERR_COMMUNICATION,
"Failed to execute service request. " + format(getLastResult()));
return;
}
Log.d(mTag, "initiatePurchaseFlow() -> launchBillingFlow.");
cordova.setActivityResultCallback(this);
mBillingClient.launchBillingFlow(cordova.getActivity(), params);
});
}
/** Return point after the native purchase flow. */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
try{
Log.d(mTag, "onActivityResult("
+ requestCode + ","
+ resultCode + ","
+ data + ")");
// Pass on the activity result to the helper for handling
// if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
// not handled, so handle it ourselves (here's where you'd
// perform any handling of activity results not related to in-app
// billing...
Log.d(mTag, "onActivityResult() -> super.onActivityResult()");
super.onActivityResult(requestCode, resultCode, data);
// }
// else {
// Log.d(mTag, "onActivityResult handled by IABUtil.");
// }
} catch (Exception e) {
Log.e(mTag, "onActivityResult() -> Failed: " + e.getMessage());
callError(Constants.ERR_UNKNOWN, e.getMessage());
}
}
// Consume a purchase
private void consumePurchase(final String purchaseToken) throws JSONException {
Log.d(mTag, "consumePurchase(" + purchaseToken + ")");
// Find the purchaseToken from sku
// final Purchase purchase = findPurchaseByProductId(productId);
// if (purchase == null) {
// Log.w(mTag, "consumePurchase() -> No such purchase");
// callError(Constants.ERR_PURCHASE, "ITEM_NOT_OWNED");
// return;
// }
// final String purchaseToken = purchase.getPurchaseToken();
if (mTokensToBeConsumed.contains(purchaseToken)) {
Log.i(mTag, "consumePurchase() -> Consume already in progress.");
callError(Constants.ERR_PURCHASE, "ITEM_ALREADY_CONSUMED");
return;
}
mTokensToBeConsumed.add(purchaseToken);
executeServiceRequest(() -> {
final ConsumeParams params = ConsumeParams.newBuilder()
.setPurchaseToken(purchaseToken)
.build();
mBillingClient.consumeAsync(params, this);
});
}
// Acknowledge a purchase
private void acknowledgePurchase(final String purchaseToken) throws JSONException {
Log.d(mTag, "acknowledgePurchase(" + purchaseToken + ")");
// Find the purchaseToken from sku
// final Purchase purchase = findPurchaseByProductId(sku);
// if (purchase == null) {
// Log.w(mTag, "acknowledgePurchase() -> No such purchase");
// callError(Constants.ERR_PURCHASE, "ITEM_NOT_OWNED");
// return;
// }
// final String purchaseToken = purchase.getPurchaseToken();
executeServiceRequest(() -> {
final AcknowledgePurchaseParams params = AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchaseToken)
// .setDeveloperPayload(developerPayload) (removed in v3)
.build();
mBillingClient.acknowledgePurchase(params, this);
});
}
// Implements AcknowledgePurchaseResponseListener
@Override
public void onAcknowledgePurchaseResponse(BillingResult result) {
if (result.getResponseCode() == BillingResponseCode.OK) {
Log.d(mTag, "onAcknowledgePurchaseResponse() -> Success");
callSuccess();
}
else {
Log.d(mTag, "onAcknowledgePurchaseResponse() -> Failed: "
+ format(result));
callError(Constants.ERR_FINISH, format(result));
}
}
/*
Deprecated by Google (and not supported when using ProductDetails instead of SkuDetails)
We should use the "manageSubscription" deep-link instead. See
https://developer.android.com/reference/com/android/billingclient/api/PriceChangeFlowParams.Builder
public void launchPriceChangeConfirmationFlow(String skuId) {
Log.d(mTag, "launchPriceChangeConfirmationFlow(" + skuId + ")");
final ProductDetails productDetails = mProductDetails.get(skuId);