Search in sources :

Example 1 with InAppPurchaseData

use of com.huawei.hms.iap.entity.InAppPurchaseData in project Osmand by osmandapp.

the class SubscriptionUtils method getPurchaseResult.

/**
 * Parse PurchaseResult data from intent
 *
 * @param activity Activity
 * @param data     the intent from onActivityResult
 * @return PurchaseResultInfo
 */
public static PurchaseResultInfo getPurchaseResult(Activity activity, Intent data) {
    PurchaseResultInfo purchaseResultInfo = Iap.getIapClient(activity).parsePurchaseResultInfoFromIntent(data);
    if (null == purchaseResultInfo) {
        Log.e(TAG, "PurchaseResultInfo is null");
    } else {
        int returnCode = purchaseResultInfo.getReturnCode();
        String errMsg = purchaseResultInfo.getErrMsg();
        switch(returnCode) {
            case OrderStatusCode.ORDER_PRODUCT_OWNED:
                Log.w(TAG, "you have owned this product");
                break;
            case OrderStatusCode.ORDER_STATE_SUCCESS:
                boolean credible = CipherUtil.doCheck(purchaseResultInfo.getInAppPurchaseData(), purchaseResultInfo.getInAppDataSignature(), CipherUtil.getPublicKey());
                if (credible) {
                    try {
                        InAppPurchaseData inAppPurchaseData = new InAppPurchaseData(purchaseResultInfo.getInAppPurchaseData());
                        if (!inAppPurchaseData.isSubValid()) {
                            return getFailedPurchaseResultInfo();
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, "parse InAppPurchaseData JSONException", e);
                        return getFailedPurchaseResultInfo();
                    }
                } else {
                    Log.e(TAG, "check the data signature fail");
                    return getFailedPurchaseResultInfo();
                }
            default:
                Log.e(TAG, "returnCode: " + returnCode + " , errMsg: " + errMsg);
                break;
        }
    }
    return purchaseResultInfo;
}
Also used : InAppPurchaseData(com.huawei.hms.iap.entity.InAppPurchaseData) JSONException(org.json.JSONException) PurchaseResultInfo(com.huawei.hms.iap.entity.PurchaseResultInfo)

Example 2 with InAppPurchaseData

use of com.huawei.hms.iap.entity.InAppPurchaseData in project Osmand by osmandapp.

the class SubscriptionUtils method getPurchaseData.

/**
 * Decide whether to offer subscription service
 *
 * @param result    the OwnedPurchasesResult from IapClient.obtainOwnedPurchases
 * @param productId subscription product id
 * @return decision result
 */
@Nullable
public static InAppPurchaseData getPurchaseData(OwnedPurchasesResult result, String productId) {
    if (null == result) {
        Log.e(TAG, "OwnedPurchasesResult is null");
        return null;
    }
    List<String> dataList = result.getInAppPurchaseDataList();
    List<String> signatureList = result.getInAppSignature();
    for (int i = 0; i < dataList.size(); i++) {
        String data = dataList.get(i);
        String signature = signatureList.get(i);
        InAppPurchaseData purchaseData = getInAppPurchaseData(productId, data, signature);
        if (purchaseData != null) {
            return purchaseData;
        }
    }
    return null;
}
Also used : InAppPurchaseData(com.huawei.hms.iap.entity.InAppPurchaseData) Nullable(androidx.annotation.Nullable)

Example 3 with InAppPurchaseData

use of com.huawei.hms.iap.entity.InAppPurchaseData in project Osmand by osmandapp.

the class InAppPurchaseHelperImpl method getRequestInventoryCommand.

@Override
protected InAppCommand getRequestInventoryCommand(boolean userRequested) {
    return new InAppCommand() {

        @Override
        protected void commandDone() {
            super.commandDone();
            inventoryRequested = false;
        }

        @Override
        public void run(InAppPurchaseHelper helper) {
            logDebug("Setup successful. Querying inventory.");
            try {
                productInfos = new ArrayList<>();
                obtainOwnedSubscriptions();
            } catch (Exception e) {
                logError("queryInventoryAsync Error", e);
                notifyDismissProgress(InAppPurchaseTaskType.REQUEST_INVENTORY);
                stop(true);
                commandDone();
            }
        }

        private void obtainOwnedSubscriptions() {
            if (uiActivity != null) {
                IapRequestHelper.obtainOwnedPurchases(getIapClient(), IapClient.PriceType.IN_APP_SUBSCRIPTION, null, new IapApiCallback<OwnedPurchasesResult>() {

                    @Override
                    public void onSuccess(OwnedPurchasesResult result) {
                        ownedSubscriptions = result;
                        obtainOwnedInApps(null);
                    }

                    @Override
                    public void onFail(Exception e) {
                        logError("obtainOwnedSubscriptions exception", e);
                        ExceptionHandle.handle((Activity) uiActivity, e);
                        commandDone();
                    }
                });
            } else {
                commandDone();
            }
        }

        private void obtainOwnedInApps(final String continuationToken) {
            if (uiActivity != null) {
                // Query users' purchased non-consumable products.
                IapRequestHelper.obtainOwnedPurchases(getIapClient(), IapClient.PriceType.IN_APP_NONCONSUMABLE, continuationToken, new IapApiCallback<OwnedPurchasesResult>() {

                    @Override
                    public void onSuccess(OwnedPurchasesResult result) {
                        ownedInApps.add(result);
                        if (result != null && !TextUtils.isEmpty(result.getContinuationToken())) {
                            obtainOwnedInApps(result.getContinuationToken());
                        } else {
                            obtainSubscriptionsInfo();
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        logError("obtainOwnedInApps exception", e);
                        ExceptionHandle.handle((Activity) uiActivity, e);
                        commandDone();
                    }
                });
            } else {
                commandDone();
            }
        }

        private void obtainSubscriptionsInfo() {
            if (uiActivity != null) {
                Set<String> productIds = new HashSet<>();
                List<InAppSubscription> subscriptions = purchases.getSubscriptions().getAllSubscriptions();
                for (InAppSubscription s : subscriptions) {
                    productIds.add(s.getSku());
                }
                productIds.addAll(ownedSubscriptions.getItemList());
                IapRequestHelper.obtainProductInfo(getIapClient(), new ArrayList<>(productIds), IapClient.PriceType.IN_APP_SUBSCRIPTION, new IapApiCallback<ProductInfoResult>() {

                    @Override
                    public void onSuccess(final ProductInfoResult result) {
                        if (result != null && result.getProductInfoList() != null) {
                            productInfos.addAll(result.getProductInfoList());
                        }
                        obtainInAppsInfo();
                    }

                    @Override
                    public void onFail(Exception e) {
                        int errorCode = ExceptionHandle.handle((Activity) uiActivity, e);
                        if (ExceptionHandle.SOLVED != errorCode) {
                            LOG.error("Unknown error");
                        }
                        commandDone();
                    }
                });
            } else {
                commandDone();
            }
        }

        private void obtainInAppsInfo() {
            if (uiActivity != null) {
                Set<String> productIds = new HashSet<>();
                for (InAppPurchase purchase : getInAppPurchases().getAllInAppPurchases(false)) {
                    productIds.add(purchase.getSku());
                }
                for (OwnedPurchasesResult result : ownedInApps) {
                    productIds.addAll(result.getItemList());
                }
                IapRequestHelper.obtainProductInfo(getIapClient(), new ArrayList<>(productIds), IapClient.PriceType.IN_APP_NONCONSUMABLE, new IapApiCallback<ProductInfoResult>() {

                    @Override
                    public void onSuccess(ProductInfoResult result) {
                        if (result != null && result.getProductInfoList() != null) {
                            productInfos.addAll(result.getProductInfoList());
                        }
                        processInventory();
                    }

                    @Override
                    public void onFail(Exception e) {
                        int errorCode = ExceptionHandle.handle((Activity) uiActivity, e);
                        if (ExceptionHandle.SOLVED != errorCode) {
                            LOG.error("Unknown error");
                        }
                        commandDone();
                    }
                });
            } else {
                commandDone();
            }
        }

        private void processInventory() {
            logDebug("Query sku details was successful.");
            /*
				 * Check for items we own. Notice that for each purchase, we check
				 * the developer payload to see if it's correct!
				 */
            List<String> allOwnedSubscriptionSkus = ownedSubscriptions.getItemList();
            for (InAppSubscription s : getSubscriptions().getAllSubscriptions()) {
                if (hasDetails(s.getSku())) {
                    InAppPurchaseData purchaseData = getPurchaseData(s.getSku());
                    ProductInfo liveUpdatesInfo = getProductInfo(s.getSku());
                    if (liveUpdatesInfo != null) {
                        fetchInAppPurchase(s, liveUpdatesInfo, purchaseData);
                    }
                    allOwnedSubscriptionSkus.remove(s.getSku());
                }
            }
            for (String sku : allOwnedSubscriptionSkus) {
                InAppPurchaseData purchaseData = getPurchaseData(sku);
                ProductInfo liveUpdatesInfo = getProductInfo(sku);
                if (liveUpdatesInfo != null) {
                    InAppSubscription s = getSubscriptions().upgradeSubscription(sku);
                    if (s == null) {
                        s = new InAppPurchaseLiveUpdatesOldSubscription(liveUpdatesInfo);
                    }
                    fetchInAppPurchase(s, liveUpdatesInfo, purchaseData);
                }
            }
            InAppPurchase fullVersion = getFullVersion();
            if (hasDetails(fullVersion.getSku())) {
                InAppPurchaseData purchaseData = getPurchaseData(fullVersion.getSku());
                ProductInfo fullPriceDetails = getProductInfo(fullVersion.getSku());
                if (fullPriceDetails != null) {
                    fetchInAppPurchase(fullVersion, fullPriceDetails, purchaseData);
                }
            }
            InAppPurchase depthContours = getDepthContours();
            if (hasDetails(depthContours.getSku())) {
                InAppPurchaseData purchaseData = getPurchaseData(depthContours.getSku());
                ProductInfo depthContoursDetails = getProductInfo(depthContours.getSku());
                if (depthContoursDetails != null) {
                    fetchInAppPurchase(depthContours, depthContoursDetails, purchaseData);
                }
            }
            InAppPurchase contourLines = getContourLines();
            if (hasDetails(contourLines.getSku())) {
                InAppPurchaseData purchaseData = getPurchaseData(contourLines.getSku());
                ProductInfo contourLinesDetails = getProductInfo(contourLines.getSku());
                if (contourLinesDetails != null) {
                    fetchInAppPurchase(contourLines, contourLinesDetails, purchaseData);
                }
            }
            if (getPurchaseData(fullVersion.getSku()) != null) {
                ctx.getSettings().FULL_VERSION_PURCHASED.set(true);
            }
            if (getPurchaseData(depthContours.getSku()) != null) {
                ctx.getSettings().DEPTH_CONTOURS_PURCHASED.set(true);
            }
            if (getPurchaseData(contourLines.getSku()) != null) {
                ctx.getSettings().CONTOUR_LINES_PURCHASED.set(true);
            }
            // Do we have the live updates?
            boolean subscribedToLiveUpdates = false;
            boolean subscribedToOsmAndPro = false;
            boolean subscribedToMaps = false;
            List<InAppPurchaseData> subscriptionPurchases = new ArrayList<>();
            for (InAppSubscription s : getSubscriptions().getAllSubscriptions()) {
                InAppPurchaseData purchaseData = getPurchaseData(s.getSku());
                if (purchaseData != null || s.getState().isActive()) {
                    if (purchaseData != null) {
                        subscriptionPurchases.add(purchaseData);
                    }
                    if (!subscribedToLiveUpdates && purchases.isLiveUpdatesSubscription(s)) {
                        subscribedToLiveUpdates = true;
                    }
                    if (!subscribedToOsmAndPro && purchases.isOsmAndProSubscription(s)) {
                        subscribedToOsmAndPro = true;
                    }
                    if (!subscribedToMaps && purchases.isMapsSubscription(s)) {
                        subscribedToMaps = true;
                    }
                }
            }
            if (!subscribedToLiveUpdates && ctx.getSettings().LIVE_UPDATES_PURCHASED.get()) {
                ctx.getSettings().LIVE_UPDATES_PURCHASED.set(false);
            } else if (subscribedToLiveUpdates) {
                ctx.getSettings().LIVE_UPDATES_PURCHASED.set(true);
            }
            if (!subscribedToOsmAndPro && ctx.getSettings().OSMAND_PRO_PURCHASED.get()) {
                ctx.getSettings().OSMAND_PRO_PURCHASED.set(false);
            } else if (subscribedToOsmAndPro) {
                ctx.getSettings().OSMAND_PRO_PURCHASED.set(true);
            }
            if (!subscribedToMaps && ctx.getSettings().OSMAND_MAPS_PURCHASED.get()) {
                ctx.getSettings().OSMAND_MAPS_PURCHASED.set(false);
            } else if (subscribedToMaps) {
                ctx.getSettings().OSMAND_MAPS_PURCHASED.set(true);
            }
            if (!subscribedToLiveUpdates && !subscribedToOsmAndPro && !subscribedToMaps) {
                onSubscriptionExpired();
            }
            lastValidationCheckTime = System.currentTimeMillis();
            logDebug("User " + (subscribedToLiveUpdates ? "HAS" : "DOES NOT HAVE") + " live updates purchased.");
            logDebug("User " + (subscribedToOsmAndPro ? "HAS" : "DOES NOT HAVE") + " OsmAnd Pro purchased.");
            logDebug("User " + (subscribedToMaps ? "HAS" : "DOES NOT HAVE") + " Maps purchased.");
            OsmandSettings settings = ctx.getSettings();
            settings.INAPPS_READ.set(true);
            List<InAppPurchaseData> tokensToSend = new ArrayList<>();
            if (subscriptionPurchases.size() > 0) {
                List<String> tokensSent = Arrays.asList(settings.BILLING_PURCHASE_TOKENS_SENT.get().split(";"));
                for (InAppPurchaseData purchase : subscriptionPurchases) {
                    if ((Algorithms.isEmpty(settings.BILLING_USER_ID.get()) || Algorithms.isEmpty(settings.BILLING_USER_TOKEN.get())) && !Algorithms.isEmpty(purchase.getDeveloperPayload())) {
                        String payload = purchase.getDeveloperPayload();
                        if (!Algorithms.isEmpty(payload)) {
                            String[] arr = payload.split(" ");
                            if (arr.length > 0) {
                                settings.BILLING_USER_ID.set(arr[0]);
                            }
                            if (arr.length > 1) {
                                token = arr[1];
                                settings.BILLING_USER_TOKEN.set(token);
                            }
                        }
                    }
                    if (!tokensSent.contains(purchase.getProductId())) {
                        tokensToSend.add(purchase);
                    }
                }
            }
            List<PurchaseInfo> purchaseInfoList = new ArrayList<>();
            for (InAppPurchaseData purchase : tokensToSend) {
                purchaseInfoList.add(getPurchaseInfo(purchase));
            }
            onSkuDetailsResponseDone(purchaseInfoList, userRequested);
        }

        private void onSubscriptionExpired() {
            if (!isDepthContoursPurchased(ctx)) {
                ctx.getSettings().getCustomRenderBooleanProperty("depthContours").set(false);
            }
        }
    };
}
Also used : InAppPurchaseData(com.huawei.hms.iap.entity.InAppPurchaseData) InAppPurchaseLiveUpdatesOldSubscription(net.osmand.plus.inapp.InAppPurchasesImpl.InAppPurchaseLiveUpdatesOldSubscription) ProductInfoResult(com.huawei.hms.iap.entity.ProductInfoResult) ArrayList(java.util.ArrayList) Activity(android.app.Activity) InAppSubscription(net.osmand.plus.inapp.InAppPurchases.InAppSubscription) HashSet(java.util.HashSet) ProductInfo(com.huawei.hms.iap.entity.ProductInfo) InAppPurchase(net.osmand.plus.inapp.InAppPurchases.InAppPurchase) ParseException(java.text.ParseException) OsmandSettings(net.osmand.plus.settings.backend.OsmandSettings) PurchaseInfo(net.osmand.plus.inapp.InAppPurchases.PurchaseInfo) OwnedPurchasesResult(com.huawei.hms.iap.entity.OwnedPurchasesResult)

Example 4 with InAppPurchaseData

use of com.huawei.hms.iap.entity.InAppPurchaseData in project Osmand by osmandapp.

the class InAppPurchaseHelperImpl method onActivityResult.

@Override
public boolean onActivityResult(@NonNull Activity activity, int requestCode, int resultCode, Intent data) {
    if (requestCode == Constants.REQ_CODE_BUY_SUB) {
        boolean succeed = false;
        if (resultCode == Activity.RESULT_OK) {
            PurchaseResultInfo result = SubscriptionUtils.getPurchaseResult(activity, data);
            if (result != null) {
                switch(result.getReturnCode()) {
                    case OrderStatusCode.ORDER_STATE_CANCEL:
                        logDebug("Purchase cancelled");
                        break;
                    case OrderStatusCode.ORDER_STATE_FAILED:
                        inventoryRequestPending = true;
                        logDebug("Purchase failed");
                        break;
                    case OrderStatusCode.ORDER_PRODUCT_OWNED:
                        inventoryRequestPending = true;
                        logDebug("Product already owned");
                        break;
                    case OrderStatusCode.ORDER_STATE_SUCCESS:
                        inventoryRequestPending = true;
                        InAppPurchaseData purchaseData = SubscriptionUtils.getInAppPurchaseData(null, result.getInAppPurchaseData(), result.getInAppDataSignature());
                        if (purchaseData != null) {
                            onPurchaseFinished(purchaseData);
                            succeed = true;
                        } else {
                            logDebug("Purchase failed");
                        }
                        break;
                    default:
                        break;
                }
            } else {
                logDebug("Purchase failed");
            }
        } else {
            logDebug("Purchase cancelled");
        }
        if (!succeed) {
            stop(true);
        }
        return true;
    } else if (requestCode == Constants.REQ_CODE_BUY_INAPP) {
        boolean succeed = false;
        if (data == null) {
            logDebug("data is null");
        } else {
            PurchaseResultInfo buyResultInfo = Iap.getIapClient(activity).parsePurchaseResultInfoFromIntent(data);
            switch(buyResultInfo.getReturnCode()) {
                case OrderStatusCode.ORDER_STATE_CANCEL:
                    logDebug("Order has been canceled");
                    break;
                case OrderStatusCode.ORDER_STATE_FAILED:
                    inventoryRequestPending = true;
                    logDebug("Order has been failed");
                    break;
                case OrderStatusCode.ORDER_PRODUCT_OWNED:
                    inventoryRequestPending = true;
                    logDebug("Product already owned");
                    break;
                case OrderStatusCode.ORDER_STATE_SUCCESS:
                    InAppPurchaseData purchaseData = InAppUtils.getInAppPurchaseData(null, buyResultInfo.getInAppPurchaseData(), buyResultInfo.getInAppDataSignature());
                    if (purchaseData != null) {
                        onPurchaseFinished(purchaseData);
                        succeed = true;
                    } else {
                        logDebug("Purchase failed");
                    }
                    break;
                default:
                    break;
            }
        }
        if (!succeed) {
            stop(true);
        }
        return true;
    }
    return false;
}
Also used : InAppPurchaseData(com.huawei.hms.iap.entity.InAppPurchaseData) PurchaseResultInfo(com.huawei.hms.iap.entity.PurchaseResultInfo)

Aggregations

InAppPurchaseData (com.huawei.hms.iap.entity.InAppPurchaseData)4 PurchaseResultInfo (com.huawei.hms.iap.entity.PurchaseResultInfo)2 Activity (android.app.Activity)1 Nullable (androidx.annotation.Nullable)1 OwnedPurchasesResult (com.huawei.hms.iap.entity.OwnedPurchasesResult)1 ProductInfo (com.huawei.hms.iap.entity.ProductInfo)1 ProductInfoResult (com.huawei.hms.iap.entity.ProductInfoResult)1 ParseException (java.text.ParseException)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 InAppPurchase (net.osmand.plus.inapp.InAppPurchases.InAppPurchase)1 InAppSubscription (net.osmand.plus.inapp.InAppPurchases.InAppSubscription)1 PurchaseInfo (net.osmand.plus.inapp.InAppPurchases.PurchaseInfo)1 InAppPurchaseLiveUpdatesOldSubscription (net.osmand.plus.inapp.InAppPurchasesImpl.InAppPurchaseLiveUpdatesOldSubscription)1 OsmandSettings (net.osmand.plus.settings.backend.OsmandSettings)1 JSONException (org.json.JSONException)1