mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 01:06:50 +00:00
Implement claimOneTimePurchase in IAP processors
This commit is contained in:
1 parent
674d03ef0c
commit
894cd8e0a3
8 files changed
+561
-109
No files matched your search
+88
-30
@@ -8,9 +8,11 @@ import com.apple.itunes.storekit.client.APIError;
|
||||
import com.apple.itunes.storekit.client.APIException;
|
||||
import com.apple.itunes.storekit.client.AppStoreServerAPIClient;
|
||||
import com.apple.itunes.storekit.model.Environment;
|
||||
import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload;
|
||||
import com.apple.itunes.storekit.model.LastTransactionsItem;
|
||||
import com.apple.itunes.storekit.model.Status;
|
||||
import com.apple.itunes.storekit.model.StatusResponse;
|
||||
import com.apple.itunes.storekit.model.TransactionInfoResponse;
|
||||
import com.apple.itunes.storekit.verification.SignedDataVerifier;
|
||||
import com.apple.itunes.storekit.verification.VerificationException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
@@ -36,7 +38,7 @@ import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
/// Client for interacting with the storekit server APIs.
|
||||
///
|
||||
/// This handles fetching information about a subscription from a transaction id, and then can be used to verify
|
||||
/// individual transactions from that subscription with [#verify]. Transactions generated with both production and
|
||||
/// individual transactions from that subscription with [#verifySubscription]. Transactions generated with both production and
|
||||
/// sandbox environments can be used.
|
||||
public class AppleAppStoreClient {
|
||||
|
||||
@@ -106,8 +108,8 @@ public class AppleAppStoreClient {
|
||||
}
|
||||
|
||||
|
||||
/// Verify signature and decode transaction payloads
|
||||
public AppleAppStoreDecodedTransaction verify(final Environment environment, final LastTransactionsItem tx) {
|
||||
/// Verify signature and decode transaction payload for a recurring subscription
|
||||
AppleAppStoreDecodedTransaction verifySubscription(final Environment environment, final LastTransactionsItem tx) {
|
||||
final SignedDataVerifier signedDataVerifier = switch (environment) {
|
||||
case PRODUCTION -> productionSignedDataVerifier;
|
||||
case SANDBOX -> sandboxSignedDataVerifier;
|
||||
@@ -125,53 +127,109 @@ public class AppleAppStoreClient {
|
||||
|
||||
public StatusResponse getAllSubscriptions(final String originalTransactionId, final Tags errorTags)
|
||||
throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
try {
|
||||
return lookupByTransactionId(originalTransactionId, errorTags,
|
||||
(env, txId) -> client(env).getAllSubscriptionStatuses(txId, EMPTY_STATUSES));
|
||||
} catch (APIException e) {
|
||||
switch (e.getApiError()) {
|
||||
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND, ACCOUNT_NOT_FOUND -> throw new SubscriptionNotFoundException();
|
||||
case RATE_LIMIT_EXCEEDED -> throw new RateLimitExceededException(null);
|
||||
case INVALID_ORIGINAL_TRANSACTION_ID -> throw new SubscriptionInvalidArgumentsException(e.getApiErrorMessage());
|
||||
case null, default -> throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Lookup the transaction for a particular transactionId
|
||||
Optional<JWSTransactionDecodedPayload> lookupTransaction(final String transactionId, final Tags errorTags)
|
||||
throws RateLimitExceededException {
|
||||
try {
|
||||
return Optional.of(lookupByTransactionId(transactionId, errorTags, (environment, txId) -> {
|
||||
try {
|
||||
final TransactionInfoResponse transactionInfo = client(environment).getTransactionInfo(txId);
|
||||
return verifier(environment).verifyAndDecodeTransaction(transactionInfo.getSignedTransactionInfo());
|
||||
} catch (VerificationException e) {
|
||||
throw new IOException("Failed to verify payload from App Store Server", e);
|
||||
}
|
||||
}));
|
||||
} catch (APIException e) {
|
||||
return switch (e.getApiError()) {
|
||||
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND, ACCOUNT_NOT_FOUND, INVALID_TRANSACTION_ID, INVALID_ORIGINAL_TRANSACTION_ID -> Optional.empty();
|
||||
case RATE_LIMIT_EXCEEDED -> throw new RateLimitExceededException(null);
|
||||
case null, default -> throw new UncheckedIOException(new IOException(e));
|
||||
};
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
interface TransactionFinder<T> {
|
||||
/// Perform some lookup operation on `transactionId`
|
||||
T lookup(final Environment environment, final String transactionId) throws IOException, APIException;
|
||||
}
|
||||
|
||||
/// Lookup something via transaction-id.
|
||||
///
|
||||
/// This performs the specified lookup operation in the production environment first, and then falls back to the
|
||||
/// sandbox environment if it's not found.
|
||||
///
|
||||
/// @param transactionId The transactionId to look up
|
||||
/// @param errorTags Context for the operation to include on error metrics
|
||||
/// @param lookupFunction [TransactionFinder] that performs the lookup operation
|
||||
/// @return The result of the lookup operation
|
||||
@VisibleForTesting
|
||||
<T> T lookupByTransactionId(
|
||||
final String transactionId, final Tags errorTags, final TransactionFinder<T> lookupFunction)
|
||||
throws APIException, IOException {
|
||||
try {
|
||||
return lookupByTransactionIdInEnvironment(defaultEnvironment, transactionId, errorTags, lookupFunction);
|
||||
} catch (final APIException e) {
|
||||
// Transactions created in the sandbox environment aren't visible in production, so fall back to sandbox if the
|
||||
// transaction isn't found. See: https://developer.apple.com/documentation/AppStoreServerAPI#Test-using-the-sandbox-environment
|
||||
if (defaultEnvironment == Environment.PRODUCTION && e.getApiError() == APIError.TRANSACTION_ID_NOT_FOUND) {
|
||||
return lookupByTransactionIdInEnvironment(Environment.SANDBOX, transactionId, errorTags, lookupFunction);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T lookupByTransactionIdInEnvironment(final Environment env, final String transactionId, final Tags errorTags, final TransactionFinder<T> lookupFunction) throws APIException, IOException {
|
||||
try {
|
||||
return retry.executeCallable(() -> {
|
||||
try {
|
||||
return getAllSubscriptionsHelper(defaultEnvironment, originalTransactionId);
|
||||
return lookupFunction.lookup(env, transactionId);
|
||||
} catch (final APIException e) {
|
||||
final APIError apiError = e.getApiError();
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, errorTags.and("reason", apiError != null ? apiError.name() : "http_" + e.getHttpStatusCode())).increment();
|
||||
throw switch (e.getApiError()) {
|
||||
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND, ACCOUNT_NOT_FOUND -> new SubscriptionNotFoundException();
|
||||
case RATE_LIMIT_EXCEEDED -> new RateLimitExceededException(null);
|
||||
case INVALID_ORIGINAL_TRANSACTION_ID -> new SubscriptionInvalidArgumentsException(e.getApiErrorMessage());
|
||||
case null, default -> throw e;
|
||||
};
|
||||
throw e;
|
||||
} catch (final IOException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", "io_error").increment();
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
} catch (SubscriptionNotFoundException | SubscriptionInvalidArgumentsException | RateLimitExceededException e) {
|
||||
} catch (IOException | APIException e) {
|
||||
throw e;
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
} catch (APIException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private StatusResponse getAllSubscriptionsHelper(final Environment env, final String originalTransactionId)
|
||||
throws APIException, IOException {
|
||||
final AppStoreServerAPIClient client = switch (env) {
|
||||
private AppStoreServerAPIClient client(final Environment environment) {
|
||||
return switch (environment) {
|
||||
case SANDBOX -> sandboxApiClient;
|
||||
case PRODUCTION -> productionApiClient;
|
||||
default -> throw new IllegalArgumentException("Unknown environment: " + env);
|
||||
default -> throw new IllegalStateException("unexpected environment");
|
||||
};
|
||||
}
|
||||
|
||||
private SignedDataVerifier verifier(final Environment environment) {
|
||||
return switch (environment) {
|
||||
case SANDBOX -> sandboxSignedDataVerifier;
|
||||
case PRODUCTION -> productionSignedDataVerifier;
|
||||
default -> throw new IllegalStateException("unexpected environment");
|
||||
};
|
||||
try {
|
||||
return client.getAllSubscriptionStatuses(originalTransactionId, EMPTY_STATUSES);
|
||||
} catch (APIException e) {
|
||||
// First attempts to look up the transaction on the production environment, falling back to the sandbox env if
|
||||
// the transaction is not found.
|
||||
// See: https://developer.apple.com/documentation/AppStoreServerAPI#Test-using-the-sandbox-environment
|
||||
if (env == Environment.PRODUCTION && e.getApiError() == APIError.TRANSACTION_ID_NOT_FOUND) {
|
||||
return getAllSubscriptionsHelper(Environment.SANDBOX, originalTransactionId);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<InputStream> decodeRootCerts(final List<String> rootCerts) {
|
||||
|
||||
+43
-12
@@ -6,9 +6,11 @@
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import com.apple.itunes.storekit.model.AutoRenewStatus;
|
||||
import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload;
|
||||
import com.apple.itunes.storekit.model.Status;
|
||||
import com.apple.itunes.storekit.model.StatusResponse;
|
||||
import com.apple.itunes.storekit.model.SubscriptionGroupIdentifierItem;
|
||||
import com.apple.itunes.storekit.model.Type;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
@@ -21,6 +23,8 @@ import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
@@ -33,7 +37,7 @@ import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
* subscription's <a
|
||||
* href="https://developer.apple.com/documentation/appstoreserverapi/originaltransactionid">originalTransactionId</a>.
|
||||
*/
|
||||
public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTimePaymentProcessor {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AppleAppStoreManager.class);
|
||||
|
||||
@@ -74,7 +78,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
}
|
||||
return getLevel(tx);
|
||||
return getLevel(tx.transaction());
|
||||
}
|
||||
|
||||
|
||||
@@ -94,7 +98,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
public void cancelAllActiveSubscriptions(String originalTransactionId)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
try {
|
||||
final AppleAppStoreDecodedTransaction tx = lookup(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "cancel"));
|
||||
final AppleAppStoreDecodedTransaction tx = lookupSubscription(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "cancel"));
|
||||
if (tx.signedTransaction().getStatus() != Status.EXPIRED &&
|
||||
tx.signedTransaction().getStatus() != Status.REVOKED &&
|
||||
tx.renewalInfo().getAutoRenewStatus() != AutoRenewStatus.OFF) {
|
||||
@@ -109,7 +113,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
@Override
|
||||
public SubscriptionInformation getSubscriptionInformation(final String originalTransactionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
final AppleAppStoreDecodedTransaction tx = lookup(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "info"));
|
||||
final AppleAppStoreDecodedTransaction tx = lookupSubscription(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "info"));
|
||||
final SubscriptionStatus status = switch (tx.signedTransaction().getStatus()) {
|
||||
case ACTIVE -> SubscriptionStatus.ACTIVE;
|
||||
case BILLING_RETRY -> SubscriptionStatus.PAST_DUE;
|
||||
@@ -119,7 +123,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
|
||||
return new SubscriptionInformation(
|
||||
getSubscriptionPrice(tx),
|
||||
getLevel(tx),
|
||||
getLevel(tx.transaction()),
|
||||
Instant.ofEpochMilli(tx.transaction().getOriginalPurchaseDate()),
|
||||
Instant.ofEpochMilli(tx.transaction().getExpiresDate()),
|
||||
isSubscriptionActive(tx),
|
||||
@@ -135,7 +139,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(String originalTransactionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
final AppleAppStoreDecodedTransaction tx = lookup(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "receipt"));
|
||||
final AppleAppStoreDecodedTransaction tx = lookupSubscription(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "receipt"));
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
}
|
||||
@@ -146,11 +150,38 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
final String itemId = tx.transaction().getWebOrderLineItemId();
|
||||
final PaymentTime paymentTime = PaymentTime.periodEnds(Instant.ofEpochMilli(tx.transaction().getExpiresDate()));
|
||||
|
||||
return new ReceiptItem(itemId, paymentTime, getLevel(tx));
|
||||
return new ReceiptItem(itemId, paymentTime, getLevel(tx.transaction()));
|
||||
|
||||
}
|
||||
|
||||
private AppleAppStoreDecodedTransaction lookup(final String originalTransactionId, final Tags tags)
|
||||
@Override
|
||||
public Optional<PaymentDetails> claimOneTimePurchase(final String transactionId)
|
||||
throws RateLimitExceededException, SubscriptionInvalidArgumentsException {
|
||||
|
||||
final Optional<JWSTransactionDecodedPayload> maybeTransaction =
|
||||
appleAppStoreClient.lookupTransaction(transactionId, Tags.of(LOOKUP_TYPE_TAG, "one_time"));
|
||||
if (maybeTransaction.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
final JWSTransactionDecodedPayload transaction = maybeTransaction.get();
|
||||
|
||||
if (transaction.getType() != Type.CONSUMABLE) {
|
||||
throw new SubscriptionInvalidArgumentsException("transaction is not a consumable one-time purchase");
|
||||
}
|
||||
|
||||
final PaymentStatus paymentStatus = transaction.getRevocationDate() == null
|
||||
? PaymentStatus.SUCCEEDED
|
||||
: PaymentStatus.FAILED;
|
||||
|
||||
return Optional.of(new PaymentDetails(
|
||||
Objects.requireNonNull(transaction.getTransactionId()),
|
||||
getLevel(transaction),
|
||||
paymentStatus,
|
||||
transaction.getPurchaseDate() != null ? Instant.ofEpochMilli(transaction.getPurchaseDate()) : null,
|
||||
null));
|
||||
}
|
||||
|
||||
private AppleAppStoreDecodedTransaction lookupSubscription(final String originalTransactionId, final Tags tags)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
try {
|
||||
return lookupAndValidateTransaction(originalTransactionId, tags);
|
||||
@@ -168,7 +199,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
.orElseThrow(() -> new SubscriptionInvalidArgumentsException("transaction did not contain a backup subscription", null));
|
||||
|
||||
final List<AppleAppStoreDecodedTransaction> txs = item.getLastTransactions().stream()
|
||||
.map(txItem -> appleAppStoreClient.verify(statuses.getEnvironment(), txItem))
|
||||
.map(txItem -> appleAppStoreClient.verifySubscription(statuses.getEnvironment(), txItem))
|
||||
.filter(tx -> tx.signedTransaction().getOriginalTransactionId().equals(originalTransactionId))
|
||||
.filter(decoded -> productIdToLevel.containsKey(decoded.transaction().getProductId()))
|
||||
.toList();
|
||||
@@ -194,11 +225,11 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(tx.transaction().getCurrency(), amount));
|
||||
}
|
||||
|
||||
private long getLevel(final AppleAppStoreDecodedTransaction tx) {
|
||||
final Long level = productIdToLevel.get(tx.transaction().getProductId());
|
||||
private long getLevel(final JWSTransactionDecodedPayload tx) {
|
||||
final Long level = productIdToLevel.get(tx.getProductId());
|
||||
if (level == null) {
|
||||
throw new UncheckedIOException(new IOException(
|
||||
"Transaction for unknown productId " + tx.transaction().getProductId()));
|
||||
"Transaction for unknown productId " + tx.getProductId()));
|
||||
}
|
||||
return level;
|
||||
}
|
||||
|
||||
+121
-1
@@ -14,6 +14,10 @@ import com.google.api.services.androidpublisher.AndroidPublisherRequest;
|
||||
import com.google.api.services.androidpublisher.AndroidPublisherScopes;
|
||||
import com.google.api.services.androidpublisher.model.AutoRenewingPlan;
|
||||
import com.google.api.services.androidpublisher.model.Money;
|
||||
import com.google.api.services.androidpublisher.model.ProductLineItem;
|
||||
import com.google.api.services.androidpublisher.model.ProductOfferDetails;
|
||||
import com.google.api.services.androidpublisher.model.ProductPurchaseV2;
|
||||
import com.google.api.services.androidpublisher.model.PurchaseStateContext;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchaseLineItem;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchaseV2;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchasesAcknowledgeRequest;
|
||||
@@ -55,7 +59,7 @@ import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
* <li> querying the current status of a token's underlying subscription </li>
|
||||
* </ul>
|
||||
*/
|
||||
public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, OneTimePaymentProcessor {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(GooglePlayBillingManager.class);
|
||||
|
||||
@@ -308,6 +312,67 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
}
|
||||
|
||||
|
||||
/// @implNote Play consumable purchases must be consumed (or they will eventually be refunded). Retrieving the
|
||||
/// PaymentInfo for a purchase also consumes the token. This does not mean subsequent attempts to generate a receipt
|
||||
/// will fail, it just means we've told the play store that the purchase is complete. If the client fails after the
|
||||
/// acknowledgement, they can just retry with no issue.
|
||||
@Override
|
||||
public Optional<PaymentDetails> claimOneTimePurchase(final String purchaseToken)
|
||||
throws IOException, RateLimitExceededException, SubscriptionInvalidArgumentsException {
|
||||
try {
|
||||
final ProductPurchaseV2 productPurchaseV2 = executeTokenOperation(
|
||||
publisher -> publisher.purchases().productsv2().getproductpurchasev2(packageName, purchaseToken));
|
||||
|
||||
final PaymentStatus paymentStatus = Optional
|
||||
.ofNullable(productPurchaseV2.getPurchaseStateContext())
|
||||
.map(PurchaseStateContext::getPurchaseState)
|
||||
.flatMap(PurchaseState::fromString)
|
||||
.map(purchaseState -> switch (purchaseState) {
|
||||
case PENDING -> PaymentStatus.PROCESSING;
|
||||
case CANCELLED -> PaymentStatus.FAILED;
|
||||
case PURCHASED -> PaymentStatus.SUCCEEDED;
|
||||
case PURCHASE_STATE_UNSPECIFIED -> PaymentStatus.UNKNOWN;
|
||||
})
|
||||
.orElse(PaymentStatus.UNKNOWN);
|
||||
|
||||
final ProductLineItem lineItem = getLineItem(productPurchaseV2);
|
||||
final String productId = lineItem.getProductId();
|
||||
final long level = productIdToLevel(productId);
|
||||
|
||||
Instant purchaseTime = null;
|
||||
if (paymentStatus == PaymentStatus.SUCCEEDED) {
|
||||
purchaseTime = parseTimestamp(productPurchaseV2.getPurchaseCompletionTime())
|
||||
.orElseThrow(() -> new IOException("Invalid purchase time"));
|
||||
|
||||
final ConsumptionState consumptionState = Optional
|
||||
.ofNullable(lineItem.getProductOfferDetails())
|
||||
.map(ProductOfferDetails::getConsumptionState)
|
||||
.flatMap(ConsumptionState::fromString)
|
||||
.orElseThrow(() -> new IllegalStateException("Purchase did not contain a consumption state: " + lineItem.getProductOfferDetails()));
|
||||
|
||||
if (consumptionState == ConsumptionState.YET_TO_BE_CONSUMED) {
|
||||
// Mark this token as consumed
|
||||
executeTokenOperation(publisher ->
|
||||
publisher.purchases().products().consume(packageName, productId, purchaseToken));
|
||||
}
|
||||
}
|
||||
return Optional.of(new PaymentDetails(purchaseToken, level, paymentStatus, purchaseTime, null));
|
||||
} catch (SubscriptionNotFoundException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private ProductLineItem getLineItem(final ProductPurchaseV2 purchase) throws SubscriptionInvalidArgumentsException {
|
||||
final List<ProductLineItem> lineItems = purchase.getProductLineItem();
|
||||
if (lineItems == null || lineItems.isEmpty()) {
|
||||
throw new SubscriptionInvalidArgumentsException("purchase has no line items");
|
||||
}
|
||||
if (lineItems.size() > 1) {
|
||||
logger.warn("{} line items found for purchase {}, expected 1", lineItems.size(), purchase.getOrderId());
|
||||
}
|
||||
return lineItems.getFirst();
|
||||
}
|
||||
|
||||
interface ApiCall<T> {
|
||||
|
||||
AndroidPublisherRequest<T> req(AndroidPublisher publisher) throws IOException;
|
||||
@@ -440,6 +505,61 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
// https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.productsv2#PurchaseStateContext
|
||||
@VisibleForTesting
|
||||
enum PurchaseState {
|
||||
PURCHASE_STATE_UNSPECIFIED("PURCHASE_STATE_UNSPECIFIED"),
|
||||
PURCHASED("PURCHASED"),
|
||||
CANCELLED("CANCELLED"),
|
||||
PENDING("PENDING");
|
||||
|
||||
private static final Map<String, PurchaseState> VALUES = Arrays
|
||||
.stream(PurchaseState.values())
|
||||
.collect(Collectors.toMap(ss -> ss.s, ss -> ss));
|
||||
|
||||
private final String s;
|
||||
|
||||
PurchaseState(final String s) {
|
||||
this.s = s;
|
||||
}
|
||||
|
||||
private static Optional<PurchaseState> fromString(String s) {
|
||||
return Optional.ofNullable(PurchaseState.VALUES.getOrDefault(s, null));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
String apiString() {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
// https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.productsv2#ConsumptionState
|
||||
@VisibleForTesting
|
||||
enum ConsumptionState {
|
||||
UNSPECIFIED("CONSUMPTION_STATE_UNSPECIFIED"),
|
||||
YET_TO_BE_CONSUMED("CONSUMPTION_STATE_YET_TO_BE_CONSUMED"),
|
||||
CONSUMED("CONSUMPTION_STATE_CONSUMED");
|
||||
|
||||
private static final Map<String, ConsumptionState> VALUES = Arrays
|
||||
.stream(ConsumptionState.values())
|
||||
.collect(Collectors.toMap(ss -> ss.s, ss -> ss));
|
||||
|
||||
private final String s;
|
||||
|
||||
ConsumptionState(final String s) {
|
||||
this.s = s;
|
||||
}
|
||||
|
||||
private static Optional<ConsumptionState> fromString(String s) {
|
||||
return Optional.ofNullable(ConsumptionState.VALUES.getOrDefault(s, null));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
String apiString() {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
// https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.subscriptionsv2#AcknowledgementState
|
||||
@VisibleForTesting
|
||||
enum AcknowledgementState {
|
||||
|
||||
+2
-1
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
@@ -14,5 +15,5 @@ public interface OneTimePaymentProcessor {
|
||||
///
|
||||
/// @param paymentIdentifier A string that identifies the payment in the payment processor
|
||||
/// @return Details about the purchase, or empty if there was no corresponding payment
|
||||
Optional<PaymentDetails> claimOneTimePurchase(final String paymentIdentifier) throws IOException;
|
||||
Optional<PaymentDetails> claimOneTimePurchase(final String paymentIdentifier) throws IOException, RateLimitExceededException, SubscriptionInvalidArgumentsException;
|
||||
}
|
||||
+1
-1
@@ -20,5 +20,5 @@ import javax.annotation.Nullable;
|
||||
public record PaymentDetails(String id,
|
||||
@Nullable Long level,
|
||||
PaymentStatus status,
|
||||
Instant created,
|
||||
@Nullable Instant created,
|
||||
@Nullable ChargeFailure chargeFailure) {}
|
||||
+165
-63
@@ -5,11 +5,9 @@
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatException;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -23,15 +21,21 @@ import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload;
|
||||
import com.apple.itunes.storekit.model.LastTransactionsItem;
|
||||
import com.apple.itunes.storekit.model.Status;
|
||||
import com.apple.itunes.storekit.model.StatusResponse;
|
||||
import com.apple.itunes.storekit.model.TransactionInfoResponse;
|
||||
import com.apple.itunes.storekit.verification.SignedDataVerifier;
|
||||
import com.apple.itunes.storekit.verification.VerificationException;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
|
||||
class AppleAppStoreClientTest {
|
||||
@@ -54,90 +58,139 @@ class AppleAppStoreClientTest {
|
||||
sandboxSignedDataVerifier, sandboxClient, null);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = APIError.class, mode = EnumSource.Mode.EXCLUDE, names = "TRANSACTION_ID_NOT_FOUND")
|
||||
public void noFallbackOnOtherErrors(APIError error) throws APIException, IOException {
|
||||
@Test
|
||||
public void getAllSubscriptions()
|
||||
throws APIException, IOException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException {
|
||||
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenThrow(new APIException(404, error, "test"));
|
||||
.thenReturn(new StatusResponse().environment(Environment.PRODUCTION));
|
||||
assertThat(apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty()).getEnvironment())
|
||||
.isEqualTo(Environment.PRODUCTION);
|
||||
}
|
||||
|
||||
assertThatException().isThrownBy(() -> apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty()));
|
||||
verifyNoInteractions(sandboxClient);
|
||||
@Test
|
||||
public void getAllSubscriptionsFallback()
|
||||
throws APIException, IOException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException {
|
||||
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenThrow(new APIException(404, APIError.TRANSACTION_ID_NOT_FOUND, "test"));
|
||||
when(sandboxClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenReturn(new StatusResponse().environment(Environment.SANDBOX));
|
||||
|
||||
assertThat(apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty()).getEnvironment()).isEqualTo(Environment.SANDBOX);
|
||||
}
|
||||
|
||||
public static Stream<Arguments> getAllSubscriptionsErrors() {
|
||||
return Stream.of(
|
||||
Arguments.of(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND, "test"), SubscriptionNotFoundException.class),
|
||||
Arguments.of(new APIException(404, APIError.ACCOUNT_NOT_FOUND, "test"), SubscriptionNotFoundException.class),
|
||||
Arguments.of(new APIException(429, APIError.RATE_LIMIT_EXCEEDED, "test"), RateLimitExceededException.class),
|
||||
Arguments.of(new APIException(429, APIError.INVALID_ORIGINAL_TRANSACTION_ID, "test"), SubscriptionInvalidArgumentsException.class));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(mode = EnumSource.Mode.INCLUDE, names = {"TRANSACTION_ID_NOT_FOUND", "ORIGINAL_TRANSACTION_ID_NOT_FOUND", "ACCOUNT_NOT_FOUND"})
|
||||
public void notFound(APIError error) throws APIException, IOException {
|
||||
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenThrow(new APIException(404, error, "test"));
|
||||
when(sandboxClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenThrow(new APIException(404, error, "test"));
|
||||
|
||||
assertThatExceptionOfType(SubscriptionNotFoundException.class)
|
||||
@MethodSource
|
||||
public void getAllSubscriptionsErrors(final APIException error, final Class<? extends Exception> expected)
|
||||
throws APIException, IOException {
|
||||
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{})).thenThrow(error);
|
||||
assertThatExceptionOfType(expected)
|
||||
.isThrownBy(() -> apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lookupTransaction()
|
||||
throws APIException, IOException, RateLimitExceededException, VerificationException {
|
||||
final JWSTransactionDecodedPayload expected = new JWSTransactionDecodedPayload();
|
||||
when(productionClient.getTransactionInfo(ORIGINAL_TX_ID))
|
||||
.thenReturn(new TransactionInfoResponse().signedTransactionInfo("signed"));
|
||||
when(productionSignedDataVerifier.verifyAndDecodeTransaction("signed")).thenReturn(expected);
|
||||
assertThat(apiWrapper.lookupTransaction(ORIGINAL_TX_ID, Tags.empty())).hasValue(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lookupTransactionFallback()
|
||||
throws APIException, IOException, RateLimitExceededException, VerificationException {
|
||||
final JWSTransactionDecodedPayload expected = new JWSTransactionDecodedPayload();
|
||||
when(productionClient.getTransactionInfo(ORIGINAL_TX_ID))
|
||||
.thenThrow(new APIException(404, APIError.TRANSACTION_ID_NOT_FOUND, "test"));
|
||||
|
||||
when(sandboxClient.getTransactionInfo(ORIGINAL_TX_ID))
|
||||
.thenReturn(new TransactionInfoResponse().signedTransactionInfo("signed"));
|
||||
when(sandboxSignedDataVerifier.verifyAndDecodeTransaction("signed")).thenReturn(expected);
|
||||
assertThat(apiWrapper.lookupTransaction(ORIGINAL_TX_ID, Tags.empty())).hasValue(expected);
|
||||
|
||||
verifyNoInteractions(productionSignedDataVerifier);
|
||||
}
|
||||
|
||||
public static Stream<Arguments> lookupTransactionErrors() {
|
||||
return Stream.of(
|
||||
Arguments.of(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND, "test"), null),
|
||||
Arguments.of(new APIException(404, APIError.ACCOUNT_NOT_FOUND, "test"), null),
|
||||
Arguments.of(new APIException(400, APIError.INVALID_TRANSACTION_ID, "test"), null),
|
||||
Arguments.of(new APIException(409, APIError.INVALID_ORIGINAL_TRANSACTION_ID, "test"), null),
|
||||
Arguments.of(new APIException(429, APIError.RATE_LIMIT_EXCEEDED, "test"), RateLimitExceededException.class));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void lookupTransactionErrors(final APIException error, final Class<? extends Exception> expected)
|
||||
throws APIException, IOException, RateLimitExceededException {
|
||||
when(productionClient.getTransactionInfo(ORIGINAL_TX_ID)).thenThrow(error);
|
||||
if (expected == null) {
|
||||
assertThat(apiWrapper.lookupTransaction(ORIGINAL_TX_ID, Tags.empty())).isEmpty();
|
||||
} else {
|
||||
assertThatExceptionOfType(expected)
|
||||
.isThrownBy(() -> apiWrapper.lookupTransaction(ORIGINAL_TX_ID, Tags.empty()));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = APIError.class, mode = EnumSource.Mode.EXCLUDE, names = "TRANSACTION_ID_NOT_FOUND")
|
||||
public void noFallbackOnOtherErrors(APIError error) {
|
||||
final ConfigurableFinder throwingFinder = new ConfigurableFinder(always(new APIException(404, error, "test")));
|
||||
assertThatExceptionOfType(APIException.class).isThrownBy(() ->
|
||||
apiWrapper.lookupByTransactionId(ORIGINAL_TX_ID, Tags.empty(), throwingFinder));
|
||||
assertThat(throwingFinder.attempts).allMatch(Environment.PRODUCTION::equals);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fallbackOnNoTransactionFound()
|
||||
throws APIException, IOException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException {
|
||||
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenThrow(new APIException(404, APIError.TRANSACTION_ID_NOT_FOUND, "test"));
|
||||
throws APIException, IOException {
|
||||
final ConfigurableFinder finder =
|
||||
new ConfigurableFinder(times(1, new APIException(404, APIError.TRANSACTION_ID_NOT_FOUND, "test")));
|
||||
|
||||
when(sandboxClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenReturn(new StatusResponse().environment(Environment.SANDBOX));
|
||||
|
||||
final StatusResponse allSubscriptions = apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty());
|
||||
|
||||
assertThat(allSubscriptions.getEnvironment()).isEqualTo(Environment.SANDBOX);
|
||||
verify(productionClient).getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{});
|
||||
verify(sandboxClient).getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{});
|
||||
assertThat(apiWrapper.lookupByTransactionId(ORIGINAL_TX_ID, Tags.empty(), finder)).isEqualTo(Environment.SANDBOX);
|
||||
assertThat(finder.attempts).containsExactly(Environment.PRODUCTION, Environment.SANDBOX);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void retryEventuallyWorks()
|
||||
throws APIException, IOException, VerificationException, RateLimitExceededException, SubscriptionException {
|
||||
throws APIException, IOException {
|
||||
// Should retry up to 3 times
|
||||
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenThrow(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test"))
|
||||
.thenThrow(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test"))
|
||||
.thenReturn(new StatusResponse().environment(Environment.PRODUCTION));
|
||||
final StatusResponse statusResponse = apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty());
|
||||
assertThat(statusResponse.getEnvironment()).isEqualTo(Environment.PRODUCTION);
|
||||
verifyNoInteractions(sandboxClient);
|
||||
final ConfigurableFinder finder = new ConfigurableFinder(
|
||||
times(2, new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test")));
|
||||
|
||||
assertThat(apiWrapper.lookupByTransactionId(ORIGINAL_TX_ID, Tags.empty(), finder)).isEqualTo(Environment.PRODUCTION);
|
||||
assertThat(finder.attempts).containsExactly(Environment.PRODUCTION, Environment.PRODUCTION, Environment.PRODUCTION);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void retryEventuallyGivesUp() throws APIException, IOException, VerificationException {
|
||||
public void retryEventuallyGivesUp() {
|
||||
// Should retry up to 3 times
|
||||
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenThrow(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test"));
|
||||
assertThatException()
|
||||
.isThrownBy(() -> apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty()))
|
||||
.isInstanceOf(UncheckedIOException.class)
|
||||
.withRootCauseInstanceOf(APIException.class);
|
||||
|
||||
verify(productionClient, times(3)).getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{});
|
||||
verifyNoInteractions(sandboxClient);
|
||||
final ConfigurableFinder finder =
|
||||
new ConfigurableFinder(always(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test")));
|
||||
assertThatExceptionOfType(APIException.class)
|
||||
.isThrownBy(() -> apiWrapper.lookupByTransactionId(ORIGINAL_TX_ID, Tags.empty(), finder));
|
||||
assertThat(finder.attempts).containsExactly(Environment.PRODUCTION, Environment.PRODUCTION, Environment.PRODUCTION);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sandboxDoesRetries()
|
||||
throws APIException, IOException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException {
|
||||
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenThrow(new APIException(404, APIError.TRANSACTION_ID_NOT_FOUND, "test"));
|
||||
throws APIException, IOException {
|
||||
final ConfigurableFinder finder = new ConfigurableFinder(
|
||||
times(1, new APIException(404, APIError.TRANSACTION_ID_NOT_FOUND, "test")),
|
||||
times(2, new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test")));
|
||||
|
||||
when(sandboxClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenThrow(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test"))
|
||||
.thenThrow(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test"))
|
||||
.thenReturn(new StatusResponse().environment(Environment.SANDBOX));
|
||||
|
||||
final StatusResponse statusResponse = apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty());
|
||||
assertThat(statusResponse.getEnvironment()).isEqualTo(Environment.SANDBOX);
|
||||
|
||||
verify(productionClient, times(3))
|
||||
.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{});
|
||||
verify(sandboxClient, times(3))
|
||||
.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{});
|
||||
assertThat(apiWrapper.lookupByTransactionId(ORIGINAL_TX_ID, Tags.empty(), finder)).isEqualTo(Environment.SANDBOX);
|
||||
assertThat(finder.attempts).containsExactly(Environment.PRODUCTION, Environment.SANDBOX, Environment.SANDBOX, Environment.SANDBOX);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -157,7 +210,7 @@ class AppleAppStoreClientTest {
|
||||
when(expectedVerifier.verifyAndDecodeRenewalInfo(SIGNED_RENEWAL_INFO))
|
||||
.thenReturn(new JWSRenewalInfoDecodedPayload());
|
||||
|
||||
apiWrapper.verify(environment, new LastTransactionsItem()
|
||||
apiWrapper.verifySubscription(environment, new LastTransactionsItem()
|
||||
.originalTransactionId(ORIGINAL_TX_ID)
|
||||
.status(Status.ACTIVE)
|
||||
.signedRenewalInfo(SIGNED_RENEWAL_INFO)
|
||||
@@ -167,4 +220,53 @@ class AppleAppStoreClientTest {
|
||||
verify(expectedVerifier).verifyAndDecodeRenewalInfo(SIGNED_RENEWAL_INFO);
|
||||
verifyNoInteractions(unexpectedVerifier);
|
||||
}
|
||||
|
||||
/// Indicates how many times to throw an exception on calls to [ConfigurableFinder#lookup]
|
||||
private static class ExceptionConfig {
|
||||
int numTimes;
|
||||
final APIException exception;
|
||||
|
||||
ExceptionConfig(final int numTimes, final APIException exception) {
|
||||
this.numTimes = numTimes;
|
||||
this.exception = exception;
|
||||
}
|
||||
}
|
||||
|
||||
/// [ExceptionConfig] that indicates `exception` should be thrown on every call
|
||||
private static ExceptionConfig always(final APIException exception) {
|
||||
return new ExceptionConfig(-1, exception);
|
||||
}
|
||||
|
||||
/// [ExceptionConfig] that indicates `exception` should be thrown `numTimes`
|
||||
private static ExceptionConfig times(int numTimes, final APIException exception) {
|
||||
return new ExceptionConfig(numTimes, exception);
|
||||
}
|
||||
|
||||
/// TransactionFinder with configurable exception behavior
|
||||
private static class ConfigurableFinder implements AppleAppStoreClient.TransactionFinder<Environment> {
|
||||
|
||||
private final ArrayDeque<ExceptionConfig> configs;
|
||||
private final List<Environment> attempts = new ArrayList<>();
|
||||
|
||||
ConfigurableFinder(ExceptionConfig... configs) {
|
||||
this.configs = new ArrayDeque<>(List.of(configs));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Environment lookup(final Environment environment, final String transactionId) throws APIException {
|
||||
attempts.add(environment);
|
||||
|
||||
if (configs.isEmpty()) {
|
||||
return environment;
|
||||
}
|
||||
final ExceptionConfig first = configs.getFirst();
|
||||
if (first.numTimes == 1) {
|
||||
configs.removeFirst();
|
||||
}
|
||||
first.numTimes -= 1;
|
||||
throw first.exception;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+35
@@ -16,12 +16,15 @@ import com.apple.itunes.storekit.client.APIException;
|
||||
import com.apple.itunes.storekit.client.AppStoreServerAPIClient;
|
||||
import com.apple.itunes.storekit.model.AutoRenewStatus;
|
||||
import com.apple.itunes.storekit.model.Environment;
|
||||
import com.apple.itunes.storekit.model.InAppOwnershipType;
|
||||
import com.apple.itunes.storekit.model.JWSRenewalInfoDecodedPayload;
|
||||
import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload;
|
||||
import com.apple.itunes.storekit.model.LastTransactionsItem;
|
||||
import com.apple.itunes.storekit.model.Status;
|
||||
import com.apple.itunes.storekit.model.StatusResponse;
|
||||
import com.apple.itunes.storekit.model.SubscriptionGroupIdentifierItem;
|
||||
import com.apple.itunes.storekit.model.TransactionInfoResponse;
|
||||
import com.apple.itunes.storekit.model.Type;
|
||||
import com.apple.itunes.storekit.verification.SignedDataVerifier;
|
||||
import com.apple.itunes.storekit.verification.VerificationException;
|
||||
import java.io.IOException;
|
||||
@@ -40,6 +43,7 @@ class AppleAppStoreManagerTest {
|
||||
|
||||
private final static long LEVEL = 123L;
|
||||
private final static String ORIGINAL_TX_ID = "originalTxIdTest";
|
||||
private final static String TRANSACTION_ID = "txIdTest";
|
||||
private final static String SUBSCRIPTION_GROUP_ID = "subscriptionGroupIdTest";
|
||||
private final static String SIGNED_RENEWAL_INFO = "signedRenewalInfoTest";
|
||||
private final static String SIGNED_TX_INFO = "signedRenewalInfoTest";
|
||||
@@ -190,6 +194,37 @@ class AppleAppStoreManagerTest {
|
||||
assertDoesNotThrow(() -> appleAppStoreManager.cancelAllActiveSubscriptions(ORIGINAL_TX_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPaymentDetails()
|
||||
throws APIException, IOException, VerificationException, SubscriptionException, RateLimitExceededException {
|
||||
when(apiClient.getTransactionInfo(TRANSACTION_ID))
|
||||
.thenReturn(new TransactionInfoResponse().signedTransactionInfo(SIGNED_TX_INFO));
|
||||
final JWSTransactionDecodedPayload payload = new JWSTransactionDecodedPayload()
|
||||
.transactionId(TRANSACTION_ID)
|
||||
.productId(PRODUCT_ID)
|
||||
.type(Type.CONSUMABLE)
|
||||
.inAppOwnershipType(InAppOwnershipType.PURCHASED)
|
||||
.purchaseDate(Instant.EPOCH.plus(Duration.ofDays(1)).toEpochMilli());
|
||||
when(signedDataVerifier.verifyAndDecodeTransaction(SIGNED_TX_INFO)).thenReturn(payload);
|
||||
|
||||
{
|
||||
// PURCHASED payment
|
||||
final PaymentDetails paymentDetails = appleAppStoreManager.claimOneTimePurchase(TRANSACTION_ID).orElseThrow();
|
||||
assertThat(paymentDetails.id()).isEqualTo(TRANSACTION_ID);
|
||||
assertThat(paymentDetails.level()).isEqualTo(LEVEL);
|
||||
assertThat(paymentDetails.created()).isEqualTo(Instant.EPOCH.plus(Duration.ofDays(1)));
|
||||
assertThat(paymentDetails.chargeFailure()).isNull();
|
||||
assertThat(paymentDetails.status()).isEqualTo(PaymentStatus.SUCCEEDED);
|
||||
}
|
||||
|
||||
{
|
||||
// REVOKED payment
|
||||
payload.setRevocationDate(Instant.EPOCH.plus(Duration.ofDays(2)).toEpochMilli());
|
||||
final PaymentDetails paymentDetails = appleAppStoreManager.claimOneTimePurchase(TRANSACTION_ID).orElseThrow();
|
||||
assertThat(paymentDetails.status()).isEqualTo(PaymentStatus.FAILED);
|
||||
}
|
||||
}
|
||||
|
||||
private void mockSubscription(final Status status, final AutoRenewStatus autoRenewStatus)
|
||||
throws APIException, IOException, VerificationException {
|
||||
when(apiClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
|
||||
+106
-1
@@ -22,6 +22,10 @@ import com.google.api.services.androidpublisher.AndroidPublisher;
|
||||
import com.google.api.services.androidpublisher.model.AutoRenewingPlan;
|
||||
import com.google.api.services.androidpublisher.model.Money;
|
||||
import com.google.api.services.androidpublisher.model.OfferDetails;
|
||||
import com.google.api.services.androidpublisher.model.ProductLineItem;
|
||||
import com.google.api.services.androidpublisher.model.ProductOfferDetails;
|
||||
import com.google.api.services.androidpublisher.model.ProductPurchaseV2;
|
||||
import com.google.api.services.androidpublisher.model.PurchaseStateContext;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchaseLineItem;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchaseV2;
|
||||
import java.io.IOException;
|
||||
@@ -31,12 +35,14 @@ import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.MutableClock;
|
||||
@@ -60,13 +66,21 @@ class GooglePlayBillingManagerTest {
|
||||
private final AndroidPublisher.Purchases.Subscriptions.Cancel cancel =
|
||||
mock(AndroidPublisher.Purchases.Subscriptions.Cancel.class);
|
||||
|
||||
// Returned in response to a purchases.productsv2.getproductpurchasev2
|
||||
private final AndroidPublisher.Purchases.Productsv2.Getproductpurchasev2 getProductPurchase =
|
||||
mock(AndroidPublisher.Purchases.Productsv2.Getproductpurchasev2.class);
|
||||
|
||||
// Returned in response to a purchases.products.consume
|
||||
private final AndroidPublisher.Purchases.Products.Consume consume =
|
||||
mock(AndroidPublisher.Purchases.Products.Consume.class);
|
||||
|
||||
private final MutableClock clock = MockUtils.mutableClock(0L);
|
||||
|
||||
private GooglePlayBillingManager googlePlayBillingManager;
|
||||
|
||||
@BeforeEach
|
||||
public void setup() throws IOException {
|
||||
reset(subscriptionsv2Get);
|
||||
reset(subscriptionsv2Get, getProductPurchase, consume);
|
||||
clock.setTimeMillis(0L);
|
||||
|
||||
AndroidPublisher androidPublisher = mock(AndroidPublisher.class);
|
||||
@@ -87,6 +101,14 @@ class GooglePlayBillingManagerTest {
|
||||
when(subscriptions.cancel(PACKAGE_NAME, PRODUCT_ID, PURCHASE_TOKEN))
|
||||
.thenReturn(cancel);
|
||||
|
||||
AndroidPublisher.Purchases.Productsv2 productsv2 = mock(AndroidPublisher.Purchases.Productsv2.class);
|
||||
when(purchases.productsv2()).thenReturn(productsv2);
|
||||
when(productsv2.getproductpurchasev2(PACKAGE_NAME, PURCHASE_TOKEN)).thenReturn(getProductPurchase);
|
||||
|
||||
AndroidPublisher.Purchases.Products products = mock(AndroidPublisher.Purchases.Products.class);
|
||||
when(purchases.products()).thenReturn(products);
|
||||
when(products.consume(PACKAGE_NAME, PRODUCT_ID, PURCHASE_TOKEN)).thenReturn(consume);
|
||||
|
||||
googlePlayBillingManager = new GooglePlayBillingManager(
|
||||
androidPublisher, clock, PACKAGE_NAME, Map.of(PRODUCT_ID, 201L));
|
||||
}
|
||||
@@ -251,6 +273,89 @@ class GooglePlayBillingManagerTest {
|
||||
|
||||
}
|
||||
|
||||
private static ProductPurchaseV2 productPurchase(
|
||||
final String purchaseState,
|
||||
@Nullable final String consumptionState,
|
||||
final Instant purchaseCompletionTime,
|
||||
final String productId) {
|
||||
|
||||
final ProductLineItem lineItem = new ProductLineItem().setProductId(productId);
|
||||
if (consumptionState != null) {
|
||||
lineItem.setProductOfferDetails(new ProductOfferDetails().setConsumptionState(consumptionState));
|
||||
}
|
||||
|
||||
return new ProductPurchaseV2()
|
||||
.setOrderId(ORDER_ID)
|
||||
.setPurchaseStateContext(new PurchaseStateContext().setPurchaseState(purchaseState))
|
||||
.setPurchaseCompletionTime(purchaseCompletionTime.toString())
|
||||
.setProductLineItem(List.of(lineItem));
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
public void getPaymentDetails(
|
||||
@CartesianTest.Enum final GooglePlayBillingManager.PurchaseState purchaseState,
|
||||
@CartesianTest.Enum final GooglePlayBillingManager.ConsumptionState consumptionState)
|
||||
throws IOException, RateLimitExceededException, SubscriptionException {
|
||||
when(getProductPurchase.execute()).thenReturn(productPurchase(
|
||||
purchaseState.apiString(),
|
||||
consumptionState.apiString(),
|
||||
Instant.EPOCH.plus(Duration.ofDays(3)),
|
||||
PRODUCT_ID));
|
||||
|
||||
final PaymentStatus expected = switch (purchaseState) {
|
||||
case PURCHASED -> PaymentStatus.SUCCEEDED;
|
||||
case PENDING -> PaymentStatus.PROCESSING;
|
||||
case CANCELLED -> PaymentStatus.FAILED;
|
||||
case PURCHASE_STATE_UNSPECIFIED -> PaymentStatus.UNKNOWN;
|
||||
};
|
||||
|
||||
assertThat(googlePlayBillingManager.claimOneTimePurchase(PURCHASE_TOKEN)).hasValueSatisfying(details -> {
|
||||
assertThat(details.status()).isEqualTo(expected);
|
||||
assertThat(details.id()).isEqualTo(PURCHASE_TOKEN);
|
||||
assertThat(details.level()).isEqualTo(201L);
|
||||
});
|
||||
|
||||
final boolean expectConsume = purchaseState == GooglePlayBillingManager.PurchaseState.PURCHASED &&
|
||||
consumptionState == GooglePlayBillingManager.ConsumptionState.YET_TO_BE_CONSUMED;
|
||||
|
||||
verify(consume, times(expectConsume ? 1 : 0)).execute();
|
||||
}
|
||||
|
||||
public static Stream<Arguments> getPaymentDetailsErrors() {
|
||||
return Stream.of(
|
||||
Arguments.of(404, null),
|
||||
Arguments.of(410, null),
|
||||
Arguments.of(400, IOException.class),
|
||||
Arguments.of(429, RateLimitExceededException.class)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void getPaymentDetailsErrors(final int httpStatus, final @Nullable Class<? extends Exception> expectedException)
|
||||
throws IOException, SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
final HttpResponseException mockException = mock(HttpResponseException.class);
|
||||
when(mockException.getStatusCode()).thenReturn(httpStatus);
|
||||
when(getProductPurchase.execute()).thenThrow(mockException);
|
||||
|
||||
if (expectedException == null) {
|
||||
assertThat(googlePlayBillingManager.claimOneTimePurchase(PURCHASE_TOKEN)).isEmpty();
|
||||
} else {
|
||||
assertThatException()
|
||||
.isThrownBy(() -> googlePlayBillingManager.claimOneTimePurchase(PURCHASE_TOKEN))
|
||||
// Verify the exception or its leaf cause is an instanceof expected. withRootCauseInstanceOf almost does what we
|
||||
// want, but fails if the outermost exception does not have a cause
|
||||
.matches(e -> {
|
||||
Throwable cause = e;
|
||||
while (cause.getCause() != null) {
|
||||
cause = cause.getCause();
|
||||
}
|
||||
return expectedException.isInstance(cause);
|
||||
});
|
||||
}
|
||||
verifyNoInteractions(consume);
|
||||
}
|
||||
|
||||
public static Stream<Arguments> tokenErrors() {
|
||||
return Stream.of(
|
||||
Arguments.of(404, SubscriptionNotFoundException.class),
|
||||
|
||||
Reference in new issue
Block a user