summaryrefslogtreecommitdiffstats
path: root/src/android/src/org/qtproject/qt5/android/purchasing/QtInAppPurchase.java
blob: e7519358b885530d475adf1f7ae46b167775af16 (plain)
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
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Purchasing module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3-COMM$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

package org.qtproject.qt5.android.purchasing;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.os.Handler;

import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.Purchase.PurchaseState;
import com.android.billingclient.api.PurchasesResponseListener;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;

public class QtInAppPurchase implements PurchasesUpdatedListener
{
    private Context m_context = null;
    private String m_publicKey = null;
    private final long m_nativePointer;
    private int requestCode;

    private BillingClient billingClient;

    public static final int RESULT_OK =
            BillingClient.BillingResponseCode.OK;
    public static final int RESULT_USER_CANCELED =
            BillingClient.BillingResponseCode.USER_CANCELED;
    public static final int RESULT_BILLING_UNAVAILABLE =
            BillingClient.BillingResponseCode.BILLING_UNAVAILABLE;
    public static final int RESULT_ITEM_UNAVAILABLE =
            BillingClient.BillingResponseCode.ITEM_UNAVAILABLE;
    public static final int RESULT_DEVELOPER_ERROR =
            BillingClient.BillingResponseCode.DEVELOPER_ERROR;
    public static final int RESULT_ERROR =
            BillingClient.BillingResponseCode.ERROR;
    public static final int RESULT_ITEM_ALREADY_OWNED =
            BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED;
    public static final int RESULT_ITEM_NOT_OWNED =
            BillingClient.BillingResponseCode.ITEM_NOT_OWNED;
    // No match with any already defined response codes
    public static final int RESULT_QTPURCHASING_ERROR = 9;

    public static final String TAG = "QtInAppPurchase";
    public static final String TYPE_INAPP = BillingClient.SkuType.INAPP;
    public static final int IAP_VERSION = 3;

    // Should be in sync with QInAppTransaction::FailureReason
    public static final int FAILUREREASON_NOFAILURE    = 0;
    public static final int FAILUREREASON_USERCANCELED = 1;
    public static final int FAILUREREASON_ERROR        = 2;

    public QtInAppPurchase(Context context, long nativePointer)
    {
        m_context = context;
        m_nativePointer = nativePointer;
    }

    public void initializeConnection(){
        billingClient = BillingClient.newBuilder(m_context)
                .enablePendingPurchases()
                .setListener(this)
                .build();
        billingClient.startConnection(new BillingClientStateListener() {
            @Override
            public void onBillingSetupFinished(BillingResult billingResult) {
                if (billingResult.getResponseCode() == RESULT_OK) {
                    purchasedProductsQueried(m_nativePointer);
                }
            }

            @Override
            public void onBillingServiceDisconnected() {
                Log.w(TAG, "Billing service disconnected");
            }
        });
    }

    @Override
    public void onPurchasesUpdated(
            @NonNull BillingResult billingResult,
            @Nullable List<Purchase> list) {

        int responseCode = billingResult.getResponseCode();

        if (list == null) {
            purchaseFailed(requestCode,
                    FAILUREREASON_ERROR,
                    "Data missing from result");
            return;
        }

        if (responseCode == RESULT_USER_CANCELED) {
            purchaseFailed(requestCode, FAILUREREASON_USERCANCELED, "");
            return;
        } else if (responseCode != RESULT_OK) {
            String errorString;
            switch (responseCode) {
                case RESULT_BILLING_UNAVAILABLE: errorString = "Billing unavailable"; break;
                case RESULT_ITEM_UNAVAILABLE: errorString = "Item unavailable"; break;
                case RESULT_DEVELOPER_ERROR: errorString = "Developer error"; break;
                case RESULT_ERROR: errorString = "Fatal error occurred"; break;
                case RESULT_ITEM_ALREADY_OWNED: errorString = "Item already owned"; break;
                default: errorString = "Unknown billing error " + responseCode; break;
            };
            purchaseFailed(requestCode, FAILUREREASON_ERROR, errorString);
            return;
        }

        for (Purchase purchase : list) {
            try {
                if (m_publicKey != null && !Security.verifyPurchase(m_publicKey,
                        purchase.getOriginalJson(),
                        purchase.getSignature())) {

                    purchaseFailed(requestCode,
                            FAILUREREASON_ERROR,
                            "Signature could not be verified");
                    return;
                }
                int purchaseState = purchase.getPurchaseState();
                if (purchaseState != PurchaseState.PURCHASED) {
                    purchaseFailed(requestCode,
                            FAILUREREASON_ERROR,
                            "Unexpected purchase state in result");
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                purchaseFailed(requestCode, FAILUREREASON_ERROR, e.getMessage());
            }
            purchaseSucceeded(requestCode,
                    purchase.getSignature(),
                    purchase.getOriginalJson(),
                    purchase.getPurchaseToken(),
                    purchase.getOrderId(),
                    purchase.getPurchaseTime());
        }
    }

    private void queryPurchasedProducts()
    {
        if (billingClient == null) {
            Log.e(TAG, "queryPurchasedProducts: Client not initialized");
            return;
        }

        String continuationToken = null;
        billingClient.queryPurchasesAsync(TYPE_INAPP, new PurchasesResponseListener() {
            @Override
            public void onQueryPurchasesResponse(
                    @NonNull BillingResult billingResult,
                    @NonNull List<Purchase> list) {

                int responseCode = billingResult.getResponseCode();

                if (responseCode != RESULT_OK) {
                    Log.e(TAG, "queryPurchasedProducts: Failed to query purchase");
                    return;
                }

                for (Purchase purchase : list) {

                    String signature = purchase.getSignature();
                    if (signature == null) {
                        Log.e(TAG, "queryPurchasedProducts: No Signature in purchase");
                        continue;
                    }

                    registerPurchased(m_nativePointer,
                            purchase.getSkus().get(0),
                            signature,
                            purchase.getOriginalJson(),
                            purchase.getPurchaseToken(),
                            purchase.getOrderId(),
                            purchase.getPurchaseTime());
                }
            }
        });
    }

    public void queryDetails(final String[] productIds)
    {
        int index = 0;
        final ArrayList<String> failedProducts = new ArrayList<>();

        while (index < productIds.length) {
            List<String> productIdList = new ArrayList<>();
            for (int i = index; i < Math.min(index + 20, productIds.length); ++i) {
                productIdList.add(productIds[i]);
                failedProducts.add(productIds[i]); // Assume guilt until innocence is proven
            }
            index += productIdList.size();

            SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
            params.setSkusList(productIdList).setType(TYPE_INAPP);
            billingClient.querySkuDetailsAsync(params.build(),
                    new SkuDetailsResponseListener() {
                        @Override
                        public void onSkuDetailsResponse(
                                BillingResult billingResult,
                                List<SkuDetails> skuDetailsList) {

                            int responseCode = billingResult.getResponseCode();

                            if (responseCode != RESULT_OK) {
                                Log.e(TAG, "queryDetails: Couldn't retrieve sku details.");
                                return;
                            }
                            if (skuDetailsList == null) {
                                Log.e(TAG, "queryDetails: No details list in response.");
                                return;
                            }

                            for (SkuDetails skuDetails : skuDetailsList) {
                                try {
                                    if (skuDetails.getSku() == null ||
                                            skuDetails.getPrice() == null ||
                                            skuDetails.getTitle() == null ||
                                            skuDetails.getDescription() == null) {

                                        Log.e(TAG, "Data missing from product details.");
                                    } else {
                                        failedProducts.remove(skuDetails.getSku());
                                        String queriedProductId = skuDetails.getSku();
                                        String queriedPrice = skuDetails.getPrice();
                                        String queriedTitle = skuDetails.getTitle();
                                        String queriedDescription = skuDetails.getDescription();
                                        registerProduct(m_nativePointer,
                                                queriedProductId,
                                                queriedPrice,
                                                queriedTitle,
                                                queriedDescription);
                                    }
                                    if (skuDetailsList.size() == skuDetailsList.indexOf(skuDetails) + 1){
                                        for (String failedProduct : failedProducts)
                                            queryFailed(m_nativePointer, failedProduct);
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
        }
    }

    public void setPublicKey(String publicKey)
    {
        m_publicKey = publicKey;
    }

    public void launchBillingFlow(String identifier, int rqCode)
    {
        requestCode = rqCode;
        List<String> skuList = new ArrayList<>();
        skuList.add(identifier);
        SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
        params.setSkusList(skuList).setType(TYPE_INAPP);

        billingClient.querySkuDetailsAsync(params.build(),
                new SkuDetailsResponseListener() {
                    @Override
                    public void onSkuDetailsResponse(
                            @NonNull BillingResult billingResult,
                            @Nullable List<SkuDetails> list) {

                        int response = billingResult.getResponseCode();
                        if (response != RESULT_OK) {
                            Log.e(TAG, "Unable to launch the purchase flow. Response code: " + response);
                            String errorString;
                            switch (response) {
                                case RESULT_BILLING_UNAVAILABLE: errorString = "Billing unavailable"; break;
                                case RESULT_ITEM_UNAVAILABLE: errorString = "Item unavailable"; break;
                                case RESULT_DEVELOPER_ERROR: errorString = "Developer error"; break;
                                case RESULT_ERROR: errorString = "Fatal error occurred"; break;
                                case RESULT_ITEM_ALREADY_OWNED: errorString = "Item already owned"; break;
                                default: errorString = "Unknown billing error " + response; break;
                            };

                            purchaseFailed(requestCode, FAILUREREASON_ERROR, errorString);
                            return;
                        }else if (list == null){
                            purchaseFailed(requestCode,
                                    FAILUREREASON_ERROR,
                                    "Data missing from result");
                            return;
                        }

                        BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                                .setSkuDetails(list.get(0))
                                .build();

                        billingClient.launchBillingFlow((Activity) m_context, flowParams);
                    }
                });
    }

    public void consumePurchase(String purchaseToken)
    {
        ConsumeResponseListener listener = new ConsumeResponseListener() {
            @Override
            public void onConsumeResponse(
                    BillingResult billingResult,
                    String purchaseToken) {

                if (billingResult.getResponseCode() != RESULT_OK) {
                    Log.e(TAG, "Unable to consume purchase. Response code: " + billingResult.getResponseCode());
                    return;
                }
            }
        };
        ConsumeParams consumeParams =
                ConsumeParams.newBuilder()
                        .setPurchaseToken(purchaseToken)
                        .build();
        billingClient.consumeAsync(consumeParams, listener);
    }

    public void acknowledgePurchase(String purchaseToken)
    {
        AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
                .setPurchaseToken(purchaseToken)
                .build();

        AcknowledgePurchaseResponseListener acknowledgePurchaseResponseListener = new AcknowledgePurchaseResponseListener() {
            @Override
            public void onAcknowledgePurchaseResponse(BillingResult billingResult) {
                if (billingResult.getResponseCode() != RESULT_OK){
                    Log.e(TAG, "Unable to acknowledge purchase. Response code: " + billingResult.getResponseCode());
                    return;
                }
            }
        };
        billingClient.acknowledgePurchase(acknowledgePurchaseParams, acknowledgePurchaseResponseListener);
    }

    private void purchaseFailed(int requestCode, int failureReason, String errorString)
    {
        purchaseFailed(m_nativePointer, requestCode, failureReason, errorString);
    }

    private void purchaseSucceeded(int requestCode,
                                   String signature,
                                   String purchaseData,
                                   String purchaseToken,
                                   String orderId,
                                   long timestamp)
    {
        purchaseSucceeded(m_nativePointer, requestCode, signature, purchaseData, purchaseToken, orderId, timestamp);
    }

    private native static void queryFailed(long nativePointer, String productId);
    private native static void purchasedProductsQueried(long nativePointer);
    private native static void registerProduct(long nativePointer,
                                               String productId,
                                               String price,
                                               String title,
                                               String description);
    private native static void purchaseFailed(long nativePointer, int requestCode, int failureReason, String errorString);
    private native static void purchaseSucceeded(long nativePointer,
                                                 int requestCode,
                                                 String signature,
                                                 String data,
                                                 String purchaseToken,
                                                 String orderId,
                                                 long timestamp);
    private native static void registerPurchased(long nativePointer,
                                                 String identifier,
                                                 String signature,
                                                 String data,
                                                 String purchaseToken,
                                                 String orderId,
                                                 long timestamp);
}