From 69fb42ef82874f24d62c361c49c8e0a3ec07f6bd Mon Sep 17 00:00:00 2001 From: Ravi Khadiwala Date: Fri, 25 Sep 2026 10:51:24 -0500 Subject: [PATCH] Use exceptions instead of status when getting PaymentDetails --- .../textsecuregcm/WhisperServerService.java | 22 +-- .../AppleAppStoreConfiguration.java | 3 +- .../configuration/BadgesConfiguration.java | 2 +- .../configuration/BraintreeConfiguration.java | 2 +- .../GooglePlayBillingConfiguration.java | 3 +- .../IssuedReceiptsTableConfiguration.java | 2 +- .../configuration/StripeConfiguration.java | 2 +- .../SubscriptionPriceConfiguration.java | 2 +- .../controllers/DonationController.java | 4 +- .../controllers/LoginPurchaseController.java | 22 +-- .../OneTimeDonationController.java | 57 ++++--- .../controllers/RegistrationController.java | 4 +- .../controllers/SubscriptionController.java | 76 ++++----- .../grpc/DonationsGrpcService.java | 4 +- .../grpc/LoginPurchaseGrpcService.java | 33 ++-- .../grpc/OneTimeDonationUtil.java | 14 +- .../grpc/OneTimeDonationsGrpcService.java | 66 ++++---- .../grpc/ProductConfigurationGrpcService.java | 10 +- .../grpc/SubscriptionsGrpcService.java | 104 ++++++------ .../textsecuregcm/grpc/SubscriptionsUtil.java | 22 ++- ...pper.java => PurchaseExceptionMapper.java} | 49 +++--- .../AppleAppStoreClient.java | 8 +- .../AppleAppStoreDecodedTransaction.java | 2 +- .../AppleAppStoreManager.java | 58 ++++--- .../BankMandateTranslator.java | 2 +- .../BankTransferType.java | 2 +- .../BraintreeGraphqlClient.java | 2 +- .../BraintreeManager.java | 46 +++--- .../BraintreePlanMetadata.java | 2 +- .../ChargeFailure.java | 2 +- .../CurrencyConfiguration.java | 2 +- ...omerAwareSubscriptionPaymentProcessor.java | 30 ++-- .../GooglePlayBillingManager.java | 102 ++++++------ .../LevelConfiguration.java | 2 +- .../LoginPurchaseManager.java | 30 ++-- .../purchases/OneTimePaymentProcessor.java | 22 +++ .../PayPalDonationsTranslator.java | 2 +- .../purchases/PaymentDetails.java | 16 ++ .../PaymentMethod.java | 2 +- .../PaymentProvider.java | 2 +- .../PaymentStatus.java | 4 +- .../ProcessorCustomer.java | 2 +- .../PurchaseException.java} | 8 +- .../purchases/PurchaseForbiddenException.java | 12 ++ .../PurchaseInvalidAmountException.java} | 6 +- .../PurchaseInvalidArgumentsException.java | 16 ++ ...urchaseInvalidIdempotencyKeyException.java | 12 ++ .../PurchaseInvalidLevelException.java | 12 ++ .../purchases/PurchaseNotFoundException.java | 16 ++ .../PurchasePaymentRequiredException.java | 43 +++++ ...urchasePaymentRequiresActionException.java | 16 ++ .../PurchaseProcessorConflictException.java | 16 ++ .../PurchaseProcessorException.java} | 6 +- ...rchaseReceiptAlreadyRedeemedException.java | 16 ++ ...eiptRequestedForOpenPaymentException.java} | 6 +- .../ReceiptCredentialPresentationFactory.java | 2 +- .../ReceiptLevel.java | 2 +- .../StripeManager.java | 90 ++++++----- ...criberIdCreationNotPermittedException.java | 4 +- .../SubscriptionCurrencyUtil.java | 2 +- .../SubscriptionInformation.java | 2 +- .../SubscriptionPaymentProcessor.java | 18 +-- .../SubscriptionPrice.java | 2 +- .../SubscriptionStatus.java | 2 +- .../storage/IssuedReceiptsManager.java | 2 +- .../storage/OneTimeDonationsManager.java | 2 +- .../storage/SubscriberCredentials.java | 16 +- .../storage/SubscriptionManager.java | 136 ++++++++-------- .../textsecuregcm/storage/Subscriptions.java | 4 +- .../OneTimePaymentProcessor.java | 18 --- .../subscriptions/PaymentDetails.java | 24 --- ...ChargeFailurePaymentRequiredException.java | 27 ---- .../SubscriptionForbiddenException.java | 12 -- ...SubscriptionInvalidArgumentsException.java | 16 -- ...riptionInvalidIdempotencyKeyException.java | 12 -- .../SubscriptionInvalidLevelException.java | 12 -- .../SubscriptionNotFoundException.java | 16 -- .../SubscriptionPaymentRequiredException.java | 16 -- ...riptionPaymentRequiresActionException.java | 16 -- ...ubscriptionProcessorConflictException.java | 16 -- ...iptionReceiptAlreadyRedeemedException.java | 16 -- .../ClearIssuedReceiptRedemptionsCommand.java | 5 +- .../workers/CommandDependencies.java | 6 +- .../AbstractV1SubscriptionControllerTest.java | 6 +- .../controllers/DonationControllerTest.java | 4 +- .../LoginPurchaseControllerTest.java | 37 +++-- .../OneTimeDonationControllerTest.java | 54 +++---- .../controllers/ProfileControllerTest.java | 2 +- .../RegistrationControllerTest.java | 2 +- .../SubscriptionControllerTest.java | 71 ++++----- .../grpc/DonationsGrpcServiceTest.java | 4 +- .../grpc/LoginPurchaseGrpcServiceTest.java | 29 ++-- .../grpc/OneTimeDonationsGrpcServiceTest.java | 48 +++--- .../ProductConfigurationGrpcServiceTest.java | 14 +- .../grpc/ProfileGrpcServiceTest.java | 2 +- .../grpc/SubscriptionsGrpcServiceTest.java | 149 +++++++++--------- .../AppleAppStoreClientTest.java | 12 +- .../AppleAppStoreManagerTest.java | 28 ++-- .../BraintreeGraphqlClientTest.java | 2 +- .../BraintreeManagerTest.java | 2 +- .../GooglePlayBillingManagerTest.java | 74 +++++---- .../LoginPurchaseManagerTest.java | 50 +----- .../PayPalDonationsTranslatorTest.java | 2 +- .../ProcessorCustomerTest.java | 2 +- .../StripeManagerTest.java | 4 +- .../SubscriptionCurrencyUtilTest.java | 2 +- .../storage/IssuedReceiptsManagerTest.java | 2 +- .../storage/OnetimeDonationsManagerTest.java | 2 +- .../storage/SubscriptionManagerTest.java | 10 +- .../storage/SubscriptionsTest.java | 4 +- 110 files changed, 1024 insertions(+), 1118 deletions(-) rename service/src/main/java/org/whispersystems/textsecuregcm/mappers/{SubscriptionExceptionMapper.java => PurchaseExceptionMapper.java} (52%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/AppleAppStoreClient.java (97%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/AppleAppStoreDecodedTransaction.java (91%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/AppleAppStoreManager.java (79%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/BankMandateTranslator.java (95%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/BankTransferType.java (70%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/BraintreeGraphqlClient.java (99%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/BraintreeManager.java (94%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/BraintreePlanMetadata.java (72%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/ChargeFailure.java (98%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/CurrencyConfiguration.java (94%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/CustomerAwareSubscriptionPaymentProcessor.java (68%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/GooglePlayBillingManager.java (87%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/LevelConfiguration.java (86%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/LoginPurchaseManager.java (72%) create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/purchases/OneTimePaymentProcessor.java rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/PayPalDonationsTranslator.java (95%) create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/purchases/PaymentDetails.java rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/PaymentMethod.java (95%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/PaymentProvider.java (97%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/PaymentStatus.java (62%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/ProcessorCustomer.java (90%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions/SubscriptionException.java => purchases/PurchaseException.java} (67%) create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseForbiddenException.java rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions/SubscriptionInvalidAmountException.java => purchases/PurchaseInvalidAmountException.java} (52%) create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidArgumentsException.java create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidIdempotencyKeyException.java create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidLevelException.java create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseNotFoundException.java create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchasePaymentRequiredException.java create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchasePaymentRequiresActionException.java create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseProcessorConflictException.java rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions/SubscriptionProcessorException.java => purchases/PurchaseProcessorException.java} (63%) create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseReceiptAlreadyRedeemedException.java rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions/SubscriptionReceiptRequestedForOpenPaymentException.java => purchases/PurchaseReceiptRequestedForOpenPaymentException.java} (53%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/ReceiptCredentialPresentationFactory.java (83%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/ReceiptLevel.java (95%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/StripeManager.java (90%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/SubscriberIdCreationNotPermittedException.java (54%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/SubscriptionCurrencyUtil.java (98%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/SubscriptionInformation.java (90%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/SubscriptionPaymentProcessor.java (69%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/SubscriptionPrice.java (84%) rename service/src/main/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/SubscriptionStatus.java (97%) delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/OneTimePaymentProcessor.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentDetails.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionChargeFailurePaymentRequiredException.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionForbiddenException.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidArgumentsException.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidIdempotencyKeyException.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidLevelException.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionNotFoundException.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPaymentRequiredException.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPaymentRequiresActionException.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionProcessorConflictException.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionReceiptAlreadyRedeemedException.java rename service/src/test/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/AppleAppStoreClientTest.java (95%) rename service/src/test/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/AppleAppStoreManagerTest.java (89%) rename service/src/test/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/BraintreeGraphqlClientTest.java (98%) rename service/src/test/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/BraintreeManagerTest.java (96%) rename service/src/test/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/GooglePlayBillingManagerTest.java (88%) rename service/src/test/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/LoginPurchaseManagerTest.java (61%) rename service/src/test/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/PayPalDonationsTranslatorTest.java (94%) rename service/src/test/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/ProcessorCustomerTest.java (87%) rename service/src/test/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/StripeManagerTest.java (96%) rename service/src/test/java/org/whispersystems/textsecuregcm/{subscriptions => purchases}/SubscriptionCurrencyUtilTest.java (98%) diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index b2615ef00..48cb8ef07 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -219,7 +219,7 @@ import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper import org.whispersystems.textsecuregcm.mappers.RegistrationLockFailureExceptionMapper; import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper; import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper; -import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper; +import org.whispersystems.textsecuregcm.mappers.PurchaseExceptionMapper; import org.whispersystems.textsecuregcm.metrics.BackupMetrics; import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager; import org.whispersystems.textsecuregcm.metrics.MessageMetrics; @@ -300,15 +300,15 @@ import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDataba import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore; import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDBWarmup; import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher; -import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient; -import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager; -import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator; -import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; -import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager; -import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager; -import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.StripeManager; +import org.whispersystems.textsecuregcm.purchases.AppleAppStoreClient; +import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager; +import org.whispersystems.textsecuregcm.purchases.BankMandateTranslator; +import org.whispersystems.textsecuregcm.purchases.BraintreeManager; +import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager; +import org.whispersystems.textsecuregcm.purchases.LoginPurchaseManager; +import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.StripeManager; import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider; import org.whispersystems.textsecuregcm.telephony.hlrlookup.HlrLookupCarrierDataProvider; import org.whispersystems.textsecuregcm.util.BufferingInterceptor; @@ -1403,7 +1403,7 @@ public class WhisperServerService extends Application processorIds, @NotNull @DecimalMin("0.01") BigDecimal amount) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DonationController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DonationController.java index 35b17fc5f..8433beb39 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DonationController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DonationController.java @@ -40,8 +40,8 @@ import org.whispersystems.textsecuregcm.storage.AccountBadge; import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.ReceiptCredentialPresentationFactory; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; @Path("/v1/donation") @Tag(name = "Donations") diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/LoginPurchaseController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/LoginPurchaseController.java index e50360f0c..e31f44f19 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/LoginPurchaseController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/LoginPurchaseController.java @@ -29,15 +29,15 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse; import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice; import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; -import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper; +import org.whispersystems.textsecuregcm.mappers.PurchaseExceptionMapper; import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; -import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException; +import org.whispersystems.textsecuregcm.purchases.LoginPurchaseManager; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException; +import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException; @Path("/v1/login-purchase") @io.swagger.v3.oas.annotations.tags.Tag(name = "LoginPurchase") @@ -91,7 +91,7 @@ public class LoginPurchaseController { @ApiResponse(responseCode = "402", description = "The purchase did not complete successfully. The body may include ChargeFailure details.", content = @Content(schema = @Schema( nullable = true, - implementation = SubscriptionExceptionMapper.ChargeFailureResponse.class))) + implementation = PurchaseExceptionMapper.ChargeFailureResponse.class))) @ApiResponse(responseCode = "403", description = "The request was made on an authenticated channel") @ApiResponse(responseCode = "404", description = "The payment provider has no purchase with the provided purchaseIdentifier") @ApiResponse(responseCode = "409", description = "The purchase was already redeemed for a receipt credential, but with a different receipt credential request") @@ -102,7 +102,7 @@ public class LoginPurchaseController { public Response createLoginReceiptCredential( @Auth final Optional authenticatedAccount, @NotNull @Valid final CreateLoginReceiptCredentialRequest request) - throws IOException, SubscriptionPaymentRequiredException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException, SubscriptionReceiptAlreadyRedeemedException { + throws IOException, PurchasePaymentRequiredException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, RateLimitExceededException, PurchaseReceiptAlreadyRedeemedException { if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) { throw new BadRequestException("login purchases are not enabled"); @@ -125,7 +125,7 @@ public class LoginPurchaseController { return Response.ok( new CreateLoginReceiptCredentialResponse(receiptCredentialResponse.serialize())) .build(); - } catch (SubscriptionReceiptRequestedForOpenPaymentException e) { + } catch (PurchaseReceiptRequestedForOpenPaymentException e) { return Response.noContent().build(); } catch (VerificationFailedException e) { throw new BadRequestException("receipt credential request failed verification", e); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java index 4105ec3b4..c705409cd 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java @@ -62,21 +62,23 @@ import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil; import org.whispersystems.textsecuregcm.limits.RateLimitedByIp; import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; +import org.whispersystems.textsecuregcm.purchases.BraintreeManager; +import org.whispersystems.textsecuregcm.purchases.ChargeFailure; +import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator; +import org.whispersystems.textsecuregcm.purchases.PaymentDetails; +import org.whispersystems.textsecuregcm.purchases.PaymentMethod; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException; +import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException; +import org.whispersystems.textsecuregcm.purchases.StripeManager; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager; import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager; import org.whispersystems.textsecuregcm.storage.WriteConflictException; -import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; -import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; -import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; -import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator; -import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails; -import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus; -import org.whispersystems.textsecuregcm.subscriptions.StripeManager; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; import org.whispersystems.textsecuregcm.util.ExactlySize; import org.whispersystems.textsecuregcm.util.HeaderUtils; @@ -179,7 +181,7 @@ public class OneTimeDonationController { @HeaderParam(HeaderUtils.DONATION_PERMIT) final Optional donationPermitHeader, @NotNull @Valid final CreateBoostRequest request, - @HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionInvalidAmountException { + @HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws PurchaseInvalidAmountException { if (authenticatedAccount.isPresent()) { throw new ForbiddenException("must not use authenticated connection for one-time donation operations"); @@ -299,7 +301,7 @@ public class OneTimeDonationController { public ConfirmPayPalBoostResponse confirmPayPalBoost( @Auth final Optional authenticatedAccount, @NotNull @Valid final ConfirmPayPalBoostRequest request, - @HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionProcessorException, IOException { + @HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws PurchaseProcessorException, IOException { if (authenticatedAccount.isPresent()) { throw new ForbiddenException("must not use authenticated connection for one-time donation operations"); @@ -347,27 +349,23 @@ public class OneTimeDonationController { throw new ForbiddenException("must not use authenticated connection for one-time donation operations"); } - final Optional maybePaymentDetails = (switch (request.processor) { - case STRIPE -> stripeManager.claimOneTimePurchase(request.paymentIntentId); - case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.paymentIntentId); - case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations"); - case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations"); - }); - - if (maybePaymentDetails.isEmpty()) { + final PaymentDetails paymentDetails; + try { + paymentDetails = (switch (request.processor) { + case STRIPE -> stripeManager.claimOneTimePurchase(request.paymentIntentId); + case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.paymentIntentId); + case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations"); + case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations"); + }); + } catch (PurchaseNotFoundException _) { throw new WebApplicationException(Response.Status.NOT_FOUND); - } - final PaymentDetails paymentDetails = maybePaymentDetails.get(); - if (paymentDetails.status() == PaymentStatus.PROCESSING) { + } catch (PurchaseReceiptRequestedForOpenPaymentException _) { return Response.noContent().build(); - } - if (paymentDetails.status() != PaymentStatus.SUCCEEDED) { + } catch (PurchasePaymentRequiredException e) { throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED) - .entity(new CreateBoostReceiptCredentialErrorResponse(paymentDetails.chargeFailure())).build()); + .entity(new CreateBoostReceiptCredentialErrorResponse(e.getChargeFailure().orElse(null))).build()); } - // The payment was successful, try to issue the receipt credential - final OneTimeDonationUtil.DonationLevelDetails levelDetails; try { levelDetails = OneTimeDonationUtil.getLevelDetails(paymentDetails, oneTimeDonationConfiguration); @@ -375,6 +373,7 @@ public class OneTimeDonationController { throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } + // try to issue the receipt credential final ReceiptCredentialRequest receiptCredentialRequest; try { receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java index 159b490ba..e661a2427 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/RegistrationController.java @@ -80,8 +80,8 @@ import org.whispersystems.textsecuregcm.storage.DeviceSpec; import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager; import org.whispersystems.textsecuregcm.storage.ReceiptAlreadyRedeemedException; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.ReceiptCredentialPresentationFactory; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; import org.whispersystems.textsecuregcm.util.HeaderUtils; import org.whispersystems.textsecuregcm.util.Util; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/SubscriptionController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/SubscriptionController.java index eeb110ab4..60333c79b 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/SubscriptionController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/SubscriptionController.java @@ -72,32 +72,32 @@ import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfigura import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil; import org.whispersystems.textsecuregcm.limits.RateLimitedByIp; import org.whispersystems.textsecuregcm.limits.RateLimiters; -import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper; +import org.whispersystems.textsecuregcm.mappers.PurchaseExceptionMapper; import org.whispersystems.textsecuregcm.metrics.MetricsUtil; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.SubscriberCredentials; import org.whispersystems.textsecuregcm.storage.SubscriptionManager; import org.whispersystems.textsecuregcm.storage.Subscriptions; -import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager; -import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator; -import org.whispersystems.textsecuregcm.subscriptions.BankTransferType; -import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; -import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; -import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration; -import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; -import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager; -import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration; -import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; -import org.whispersystems.textsecuregcm.subscriptions.StripeManager; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException; +import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager; +import org.whispersystems.textsecuregcm.purchases.BankMandateTranslator; +import org.whispersystems.textsecuregcm.purchases.BankTransferType; +import org.whispersystems.textsecuregcm.purchases.BraintreeManager; +import org.whispersystems.textsecuregcm.purchases.ChargeFailure; +import org.whispersystems.textsecuregcm.purchases.CurrencyConfiguration; +import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager; +import org.whispersystems.textsecuregcm.purchases.LevelConfiguration; +import org.whispersystems.textsecuregcm.purchases.PaymentMethod; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.ProcessorCustomer; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.StripeManager; +import org.whispersystems.textsecuregcm.purchases.PurchaseException; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidLevelException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiresActionException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException; import org.whispersystems.textsecuregcm.util.HeaderUtils; @Path("/v1/subscription") @@ -197,7 +197,7 @@ public class SubscriptionController { @ManagedAsync public Response deleteSubscriber( @Auth Optional authenticatedAccount, - @PathParam("subscriberId") String subscriberId) throws SubscriptionException, RateLimitExceededException { + @PathParam("subscriberId") String subscriberId) throws PurchaseException, RateLimitExceededException { SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock); subscriptionManager.deleteSubscriber(subscriberCredentials); @@ -229,7 +229,7 @@ public class SubscriptionController { @HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent, - @PathParam("subscriberId") String subscriberId) throws SubscriptionException { + @PathParam("subscriberId") String subscriberId) throws PurchaseException { SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock); @@ -277,7 +277,7 @@ public class SubscriptionController { @PathParam("subscriberId") String subscriberId, @QueryParam("type") @DefaultValue("CARD") PaymentMethod paymentMethodType, - @HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws SubscriptionException { + @HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws PurchaseException { SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock); @@ -332,7 +332,7 @@ public class SubscriptionController { @NotNull @Valid CreatePayPalBillingAgreementRequest request, @Context ContainerRequestContext containerRequestContext, @HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) - throws SubscriptionException, IOException { + throws PurchaseException, IOException { final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock); @@ -365,7 +365,7 @@ public class SubscriptionController { @Auth Optional authenticatedAccount, @PathParam("subscriberId") String subscriberId, @PathParam("processor") PaymentProvider processor, - @PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws SubscriptionException, IOException { + @PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws PurchaseException, IOException { SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock); @@ -405,7 +405,7 @@ public class SubscriptionController { @PathParam("subscriberId") String subscriberId, @PathParam("level") long level, @PathParam("currency") String currency, - @PathParam("idempotencyKey") String idempotencyKey) throws SubscriptionException { + @PathParam("idempotencyKey") String idempotencyKey) throws PurchaseException { SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock); try { @@ -424,19 +424,19 @@ public class SubscriptionController { subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, record, manager, level, currency, idempotencyKey, subscriptionTemplateId, this::subscriptionsAreSameType); return new SetSubscriptionLevelSuccessResponse(level); - } catch (SubscriptionInvalidLevelException e) { + } catch (PurchaseInvalidLevelException e) { throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST) .entity(new SubscriptionController.SetSubscriptionLevelErrorResponse(List.of( new SubscriptionController.SetSubscriptionLevelErrorResponse.Error( SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL, null)))) .build()); - } catch (SubscriptionPaymentRequiresActionException e) { + } catch (PurchasePaymentRequiresActionException e) { throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST) .entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error( SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION, null)))) .build()); - } catch (SubscriptionInvalidArgumentsException e) { + } catch (PurchaseInvalidArgumentsException e) { throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST) .entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error( SetSubscriptionLevelErrorResponse.Error.Type.INVALID_ARGUMENTS, e.getMessage())))) @@ -476,7 +476,7 @@ public class SubscriptionController { public SetSubscriptionLevelSuccessResponse setAppStoreSubscription( @Auth Optional authenticatedAccount, @PathParam("subscriberId") String subscriberId, - @PathParam("originalTransactionId") String originalTransactionId) throws SubscriptionException, RateLimitExceededException { + @PathParam("originalTransactionId") String originalTransactionId) throws PurchaseException, RateLimitExceededException { final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock); @@ -520,7 +520,7 @@ public class SubscriptionController { public SetSubscriptionLevelSuccessResponse setPlayStoreSubscription( @Auth Optional authenticatedAccount, @PathParam("subscriberId") String subscriberId, - @PathParam("purchaseToken") String purchaseToken) throws SubscriptionException, RateLimitExceededException { + @PathParam("purchaseToken") String purchaseToken) throws PurchaseException, RateLimitExceededException { final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock); @@ -665,7 +665,7 @@ public class SubscriptionController { @ManagedAsync public GetSubscriptionInformationResponse getSubscriptionInformation( @Auth Optional authenticatedAccount, - @PathParam("subscriberId") String subscriberId) throws SubscriptionException, RateLimitExceededException { + @PathParam("subscriberId") String subscriberId) throws PurchaseException, RateLimitExceededException { SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock); return subscriptionManager.getSubscriptionInformation( subscriberCredentials) @@ -739,7 +739,7 @@ public class SubscriptionController { } } """, - implementation = SubscriptionExceptionMapper.ChargeFailureResponse.class))) + implementation = PurchaseExceptionMapper.ChargeFailureResponse.class))) @ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present") @ApiResponse(responseCode = "404", description = "subscriberId is not found OR malformed OR no subscription setup on the subscriber id") @ApiResponse(responseCode = "409", description = "latest paid receipt on subscription was already redeemed for a receipt credential but with a different receipt credential request") @@ -751,7 +751,7 @@ public class SubscriptionController { @Auth Optional authenticatedAccount, @HeaderParam(HttpHeaders.USER_AGENT) final String userAgent, @PathParam("subscriberId") String subscriberId, - @NotNull @Valid GetReceiptCredentialRequest request) throws SubscriptionException, RateLimitExceededException { + @NotNull @Valid GetReceiptCredentialRequest request) throws PurchaseException, RateLimitExceededException { SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock); try { final SubscriptionManager.ReceiptResult receiptCredential = subscriptionManager.createReceiptCredential( @@ -771,7 +771,7 @@ public class SubscriptionController { UserAgentTagUtil.getPlatformTag(userAgent))) .increment(); return Response.ok(new GetReceiptCredentialResponse(receiptCredentialResponse.serialize())).build(); - } catch (SubscriptionReceiptRequestedForOpenPaymentException e) { + } catch (PurchaseReceiptRequestedForOpenPaymentException e) { return Response.noContent().build(); } } @@ -783,7 +783,7 @@ public class SubscriptionController { public Response setDefaultPaymentMethodForIdeal( @Auth Optional authenticatedAccount, @PathParam("subscriberId") String subscriberId, - @PathParam("setupIntentId") @NotEmpty String setupIntentId) throws SubscriptionException, IOException { + @PathParam("setupIntentId") @NotEmpty String setupIntentId) throws PurchaseException, IOException { SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock); @@ -794,7 +794,7 @@ public class SubscriptionController { private void setDefaultPaymentMethod(final CustomerAwareSubscriptionPaymentProcessor manager, final String paymentMethodId, - final SubscriberCredentials requestData) throws SubscriptionException, IOException { + final SubscriberCredentials requestData) throws PurchaseException, IOException { try { final Subscriptions.Record record = subscriptionManager.getSubscriber(requestData); @@ -805,7 +805,7 @@ public class SubscriptionController { manager .setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, record.subscriptionId); - } catch (final SubscriptionInvalidArgumentsException e) { + } catch (final PurchaseInvalidArgumentsException e) { // Here, invalid arguments must mean that the client has made requests out of order, and needs to finish // setting up the paymentMethod first throw new ClientErrorException(Status.CONFLICT); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcService.java index 7f8ba9d2c..6460e8467 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcService.java @@ -28,8 +28,8 @@ import org.whispersystems.textsecuregcm.storage.AccountBadge; import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.ReceiptCredentialPresentationFactory; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/LoginPurchaseGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/LoginPurchaseGrpcService.java index 3db98ed5a..d4d3ac384 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/LoginPurchaseGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/LoginPurchaseGrpcService.java @@ -10,7 +10,6 @@ import org.signal.chat.errors.FailedPrecondition; import org.signal.chat.errors.NotFound; import org.signal.chat.purchase.CreateLoginReceiptCredentialRequest; import org.signal.chat.purchase.CreateLoginReceiptCredentialResponse; -import org.signal.chat.purchase.PaymentRequired; import org.signal.chat.purchase.SimpleLoginPurchaseGrpc; import org.signal.libsignal.zkgroup.InvalidInputException; import org.signal.libsignal.zkgroup.VerificationFailedException; @@ -19,14 +18,13 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse; import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; -import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException; +import org.whispersystems.textsecuregcm.purchases.LoginPurchaseManager; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException; +import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException; public class LoginPurchaseGrpcService extends SimpleLoginPurchaseGrpc.LoginPurchaseImplBase { @@ -66,28 +64,23 @@ public class LoginPurchaseGrpcService extends SimpleLoginPurchaseGrpc.LoginPurch .setResult(CreateLoginReceiptCredentialResponse.CreateLoginReceiptCredentialResult.newBuilder() .setReceiptCredentialResponse(ByteString.copyFrom(receiptCredentialResponse.serialize()))) .build(); - } catch (final SubscriptionReceiptRequestedForOpenPaymentException e) { + } catch (final PurchaseReceiptRequestedForOpenPaymentException e) { return CreateLoginReceiptCredentialResponse.newBuilder() .setPaymentStillProcessing(FailedPrecondition.getDefaultInstance()) .build(); - } catch (final SubscriptionChargeFailurePaymentRequiredException e) { + } catch (final PurchasePaymentRequiredException e) { return CreateLoginReceiptCredentialResponse.newBuilder() - .setPaymentRequired(PaymentRequired.newBuilder() - .setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure()))) + .setPaymentRequired(SubscriptionsUtil.toPaymentRequired(e)) .build(); - } catch (final SubscriptionPaymentRequiredException e) { - return CreateLoginReceiptCredentialResponse.newBuilder() - .setPaymentRequired(PaymentRequired.getDefaultInstance()) - .build(); - } catch (final SubscriptionNotFoundException e) { + } catch (final PurchaseNotFoundException e) { return CreateLoginReceiptCredentialResponse.newBuilder() .setPaymentNotFound(NotFound.getDefaultInstance()) .build(); - } catch (final SubscriptionReceiptAlreadyRedeemedException e) { + } catch (final PurchaseReceiptAlreadyRedeemedException e) { return CreateLoginReceiptCredentialResponse.newBuilder() .setReceiptAlreadyIssued(FailedPrecondition.getDefaultInstance()) .build(); - } catch (final SubscriptionInvalidArgumentsException e) { + } catch (final PurchaseInvalidArgumentsException e) { throw GrpcExceptions.invalidArguments(e.errorDetail().orElse("")); } catch (final VerificationFailedException e) { throw GrpcExceptions.fieldViolation("receipt_credential_request", diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java index 90fb53666..bf2874e2c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java @@ -7,12 +7,12 @@ import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; -import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; -import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator; -import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails; -import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil; +import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator; +import org.whispersystems.textsecuregcm.purchases.PaymentDetails; +import org.whispersystems.textsecuregcm.purchases.PaymentMethod; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.SubscriptionCurrencyUtil; public class OneTimeDonationUtil { @@ -92,7 +92,7 @@ public class OneTimeDonationUtil { // independently. final Locale locale = SubscriptionsUtil.getPayPalLocale(acceptableLocales); final String localizedLineItemName = payPalDonationsTranslator.translate(acceptableLocales, - org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator.ONE_TIME_DONATION_LINE_ITEM_KEY); + org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator.ONE_TIME_DONATION_LINE_ITEM_KEY); return new LocalizedPayPalDonationLineItem(locale, localizedLineItemName); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java index 821a01e89..264c006b5 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java @@ -17,7 +17,6 @@ import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Locale; -import java.util.Optional; import org.signal.chat.errors.FailedPrecondition; import org.signal.chat.errors.FailedZkAuthentication; import org.signal.chat.errors.NotFound; @@ -31,7 +30,6 @@ import org.signal.chat.purchase.CreateBoostRequest; import org.signal.chat.purchase.CreateBoostResponse; import org.signal.chat.purchase.CreatePayPalBoostRequest; import org.signal.chat.purchase.CreatePayPalBoostResponse; -import org.signal.chat.purchase.PaymentRequired; import org.signal.chat.purchase.SimpleOneTimeDonationsGrpc; import org.signal.libsignal.zkgroup.InvalidInputException; import org.signal.libsignal.zkgroup.VerificationFailedException; @@ -43,19 +41,21 @@ import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfigurati import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; +import org.whispersystems.textsecuregcm.purchases.BraintreeManager; +import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator; +import org.whispersystems.textsecuregcm.purchases.PaymentDetails; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException; +import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException; +import org.whispersystems.textsecuregcm.purchases.StripeManager; +import org.whispersystems.textsecuregcm.purchases.SubscriptionCurrencyUtil; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager; import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager; import org.whispersystems.textsecuregcm.storage.WriteConflictException; -import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; -import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator; -import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus; -import org.whispersystems.textsecuregcm.subscriptions.StripeManager; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneTimeDonationsImplBase { @@ -115,11 +115,11 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT .build(); } - final org.whispersystems.textsecuregcm.subscriptions.PaymentMethod paymentMethod = + final org.whispersystems.textsecuregcm.purchases.PaymentMethod paymentMethod = switch (request.getPaymentMethod()) { - case PAYMENT_METHOD_CARD -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD; - case PAYMENT_METHOD_SEPA_DEBIT -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT; - case PAYMENT_METHOD_IDEAL -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.IDEAL; + case PAYMENT_METHOD_CARD -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.CARD; + case PAYMENT_METHOD_SEPA_DEBIT -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.SEPA_DEBIT; + case PAYMENT_METHOD_IDEAL -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.IDEAL; default -> throw GrpcExceptions.fieldViolation("payment_method", "Unsupported payment method"); }; @@ -157,7 +157,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT request.getCurrency(), request.getAmount(), request.getLevel(), getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))); yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build(); - } catch (final SubscriptionInvalidAmountException e) { + } catch (final PurchaseInvalidAmountException e) { yield CreateBoostResponse.newBuilder() .setInvalidAmount(FailedPrecondition.newBuilder() .setDescription(e.getErrorCode()).build()) @@ -175,7 +175,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT request.getCurrency(), request.getAmount(), request.getLevel(), - org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL, + org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL, oneTimeDonationConfiguration, braintreeManager); @@ -221,7 +221,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT request.getCurrency(), request.getAmount(), request.getLevel(), - org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL, + org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL, oneTimeDonationConfiguration, braintreeManager); @@ -251,7 +251,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT yield ConfirmPayPalBoostResponse.newBuilder() .setResult(ConfirmPayPalBoostResponse.ConfirmPayPalBoostResult.newBuilder() .setPaymentId(chargeSuccessDetails.paymentId()).build()).build(); - } catch (final SubscriptionProcessorException e) { + } catch (final PurchaseProcessorException e) { yield ConfirmPayPalBoostResponse.newBuilder() .setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())) .build(); @@ -267,28 +267,22 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT final PaymentProvider processor = PaymentProvider.fromProto(request.getProcessor()) .orElseThrow(() -> GrpcExceptions.fieldViolation("processor", "Unsupported payment processor")); - final Optional maybePaymentDetails = switch (processor) { - case STRIPE -> stripeManager.claimOneTimePurchase(request.getPaymentIntentId()); - case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.getPaymentIntentId()); - default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor"); - }; - - if (maybePaymentDetails.isEmpty()) { + final PaymentDetails paymentDetails; + try { + paymentDetails = switch (processor) { + case STRIPE -> stripeManager.claimOneTimePurchase(request.getPaymentIntentId()); + case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.getPaymentIntentId()); + default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor"); + }; + } catch (PurchaseNotFoundException _) { return CreateBoostReceiptCredentialResponse.newBuilder() .setPaymentNotFound(NotFound.getDefaultInstance()).build(); - } - final PaymentDetails paymentDetails = maybePaymentDetails.get(); - if (paymentDetails.status() == PaymentStatus.PROCESSING) { + } catch (PurchaseReceiptRequestedForOpenPaymentException _) { return CreateBoostReceiptCredentialResponse.newBuilder() .setPaymentStillProcessing(FailedPrecondition.getDefaultInstance()).build(); - } - if (paymentDetails.status() != PaymentStatus.SUCCEEDED) { - final PaymentRequired.Builder paymentRequiredBuilder = PaymentRequired.newBuilder(); - if (paymentDetails.chargeFailure() != null) { - paymentRequiredBuilder.setChargeFailure(toChargeFailure(processor, paymentDetails.chargeFailure())); - } + } catch (PurchasePaymentRequiredException e) { return CreateBoostReceiptCredentialResponse.newBuilder() - .setPaymentRequired(paymentRequiredBuilder).build(); + .setPaymentRequired(SubscriptionsUtil.toPaymentRequired(e)).build(); } final OneTimeDonationUtil.DonationLevelDetails levelDetails; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcService.java index f2ef0e0d1..26955e532 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcService.java @@ -16,10 +16,10 @@ import org.signal.chat.purchase.SimpleProductConfigurationGrpc; import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration; -import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; -import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil; +import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.purchases.PaymentMethod; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.SubscriptionCurrencyUtil; public class ProductConfigurationGrpcService extends SimpleProductConfigurationGrpc.ProductConfigurationImplBase { private final GetConfigurationResponse configurationResponse; @@ -103,7 +103,7 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG private static CurrencyConfiguration toProtoCurrencyConfiguration( final String currency, - final org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration config) { + final org.whispersystems.textsecuregcm.purchases.CurrencyConfiguration config) { final CurrencyConfiguration.Builder builder = CurrencyConfiguration.newBuilder() .setMinimum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(currency, config.minimum())) .addAllSupportedPaymentMethods(config.supportedPaymentMethods().stream() diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcService.java index 999721cbd..313a2689e 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcService.java @@ -28,7 +28,6 @@ import org.signal.chat.purchase.GetReceiptCredentialRequest; import org.signal.chat.purchase.GetReceiptCredentialResponse; import org.signal.chat.purchase.GetSubscriptionInformationRequest; import org.signal.chat.purchase.GetSubscriptionInformationResponse; -import org.signal.chat.purchase.PaymentRequired; import org.signal.chat.purchase.SetDefaultPaymentMethodRequest; import org.signal.chat.purchase.SetDefaultPaymentMethodResponse; import org.signal.chat.purchase.SetIapSubscriptionRequest; @@ -50,29 +49,28 @@ import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.SubscriberCredentials; import org.whispersystems.textsecuregcm.storage.SubscriptionManager; import org.whispersystems.textsecuregcm.storage.Subscriptions; -import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager; -import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator; -import org.whispersystems.textsecuregcm.subscriptions.BankTransferType; -import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; -import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; -import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager; -import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer; -import org.whispersystems.textsecuregcm.subscriptions.StripeManager; -import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionStatus; +import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager; +import org.whispersystems.textsecuregcm.purchases.BankMandateTranslator; +import org.whispersystems.textsecuregcm.purchases.BankTransferType; +import org.whispersystems.textsecuregcm.purchases.BraintreeManager; +import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager; +import org.whispersystems.textsecuregcm.purchases.ProcessorCustomer; +import org.whispersystems.textsecuregcm.purchases.StripeManager; +import org.whispersystems.textsecuregcm.purchases.SubscriberIdCreationNotPermittedException; +import org.whispersystems.textsecuregcm.purchases.PurchaseForbiddenException; +import org.whispersystems.textsecuregcm.purchases.SubscriptionInformation; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidIdempotencyKeyException; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidLevelException; +import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiresActionException; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorConflictException; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException; +import org.whispersystems.textsecuregcm.purchases.SubscriptionStatus; public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.SubscriptionsImplBase { @@ -139,7 +137,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted); return UpdateSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build(); - } catch (final SubscriptionForbiddenException _) { + } catch (final PurchaseForbiddenException _) { throw GrpcExceptions.invalidArguments("subscriber-ids must be randomly generated"); } catch (SubscriberIdCreationNotPermittedException _) { if (request.getDonationPermit().isEmpty()) { @@ -163,9 +161,9 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti request.getSubscriberId().toByteArray(), clock); subscriptionManager.deleteSubscriber(subscriberCredentials); return DeleteSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build(); - } catch (final SubscriptionNotFoundException e) { + } catch (final PurchaseNotFoundException e) { return DeleteSubscriberResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build(); - } catch (final SubscriptionInvalidArgumentsException e) { + } catch (final PurchaseInvalidArgumentsException e) { return DeleteSubscriberResponse.newBuilder().setCannotCancelSubscription( FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); } @@ -204,9 +202,9 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti return CreatePaymentMethodResponse.newBuilder().setResult( CreatePaymentMethodResponse.CreatePaymentMethodResult.newBuilder().setClientSecret(token) .setPaymentProvider(customerAwareSubscriptionPaymentProcessor.getProvider().toProto()).build()).build(); - } catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) { + } catch (final PurchaseNotFoundException | PurchaseForbiddenException _) { return CreatePaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder()).build(); - } catch (final SubscriptionProcessorConflictException e) { + } catch (final PurchaseProcessorConflictException e) { return CreatePaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict( FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); } @@ -226,10 +224,10 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti return CreatePayPalPaymentMethodResponse.newBuilder().setResult( CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder() .setApprovalUrl(details.approvalUrl()).setToken(details.billingAgreementToken()).build()).build(); - } catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) { + } catch (final PurchaseNotFoundException | PurchaseForbiddenException _) { return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()) .build(); - } catch (final SubscriptionProcessorConflictException e) { + } catch (final PurchaseProcessorConflictException e) { return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict( FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); } @@ -267,9 +265,9 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti .orElseGet(() -> SetDefaultPaymentMethodResponse.newBuilder() .setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build()) .build()); - } catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) { + } catch (final PurchaseNotFoundException | PurchaseForbiddenException _) { return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build(); - } catch (final SubscriptionProcessorConflictException _) { + } catch (final PurchaseProcessorConflictException _) { return SetDefaultPaymentMethodResponse.newBuilder() .setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build()) .build(); @@ -282,7 +280,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti try { processor.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, subscriptionId); return SetDefaultPaymentMethodResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build(); - } catch (final SubscriptionInvalidArgumentsException e) { + } catch (final PurchaseInvalidArgumentsException e) { // Here, invalid arguments must mean that the client has made requests out of order, and needs to finish // setting up the paymentMethod first return SetDefaultPaymentMethodResponse.newBuilder() @@ -306,7 +304,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti .setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build()) .build()); - } catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) { + } catch (final PurchaseNotFoundException | PurchaseForbiddenException _) { return SetSubscriptionLevelResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build(); } } @@ -346,20 +344,20 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti return SetSubscriptionLevelResponse.newBuilder().setSuccess( SetSubscriptionLevelResponse.SetSubscriptionLevelResult.newBuilder().setLevel(request.getLevel()).build()) .build(); - } catch (final SubscriptionInvalidIdempotencyKeyException e) { + } catch (final PurchaseInvalidIdempotencyKeyException e) { return SetSubscriptionLevelResponse.newBuilder() .setInvalidIdempotencyKey(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()) .build(); - } catch (final SubscriptionProcessorException e) { + } catch (final PurchaseProcessorException e) { return SetSubscriptionLevelResponse.newBuilder() .setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build(); - } catch (final SubscriptionPaymentRequiresActionException e) { + } catch (final PurchasePaymentRequiresActionException e) { return SetSubscriptionLevelResponse.newBuilder().setPaymentRequiresAction(FailedPrecondition.newBuilder().build()) .build(); - } catch (final SubscriptionInvalidLevelException e) { + } catch (final PurchaseInvalidLevelException e) { return SetSubscriptionLevelResponse.newBuilder() .setInvalidLevelTransition(FailedPrecondition.newBuilder().build()).build(); - } catch (final SubscriptionProcessorConflictException e) { + } catch (final PurchaseProcessorConflictException e) { return SetSubscriptionLevelResponse.newBuilder().setSubscriptionProcessorConflict( FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); } @@ -382,15 +380,15 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti }; return SetIapSubscriptionResponse.newBuilder() .setSuccess(SetIapSubscriptionResponse.SetIapSubscriptionResult.newBuilder().setLevel(level).build()).build(); - } catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) { + } catch (final PurchaseNotFoundException | PurchaseForbiddenException _) { return SetIapSubscriptionResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build(); - } catch (final SubscriptionProcessorConflictException e) { + } catch (final PurchaseProcessorConflictException e) { return SetIapSubscriptionResponse.newBuilder().setSubscriptionProcessorConflict( FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); - } catch (final SubscriptionPaymentRequiredException e) { + } catch (final PurchasePaymentRequiredException e) { return SetIapSubscriptionResponse.newBuilder().setPaymentRequired(FailedPrecondition.newBuilder().build()) .build(); - } catch (final SubscriptionInvalidArgumentsException e) { + } catch (final PurchaseInvalidArgumentsException e) { return SetIapSubscriptionResponse.newBuilder() .setInvalidTransaction(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()) .build(); @@ -407,7 +405,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti .map(SubscriptionsGrpcService::buildSubscriptionInformationResponse).orElseGet( () -> GetSubscriptionInformationResponse.newBuilder().setNoSubscription(Empty.getDefaultInstance()) .build()); - } catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) { + } catch (final PurchaseNotFoundException | PurchaseForbiddenException _) { return GetSubscriptionInformationResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()) .build(); } @@ -455,22 +453,18 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti GetReceiptCredentialResponse.GetReceiptCredentialResult.newBuilder() .setReceiptCredentialResponse(ByteString.copyFrom(result.receiptCredentialResponse().serialize())) .build()).build(); - } catch (final SubscriptionReceiptRequestedForOpenPaymentException e) { + } catch (final PurchaseReceiptRequestedForOpenPaymentException e) { return GetReceiptCredentialResponse.newBuilder().setNoPaidInvoice(FailedPrecondition.newBuilder().build()) .build(); - } catch (final SubscriptionChargeFailurePaymentRequiredException e) { - return GetReceiptCredentialResponse.newBuilder().setPaymentRequired( - PaymentRequired.newBuilder() - .setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build()).build(); - } catch (final SubscriptionPaymentRequiredException e) { + } catch (final PurchasePaymentRequiredException e) { return GetReceiptCredentialResponse.newBuilder() - .setPaymentRequired(PaymentRequired.newBuilder().build()).build(); - } catch (final SubscriptionInvalidArgumentsException e) { + .setPaymentRequired(SubscriptionsUtil.toPaymentRequired(e)).build(); + } catch (final PurchaseInvalidArgumentsException e) { throw GrpcExceptions.invalidArguments(e.errorDetail().orElse("")); - } catch (final SubscriptionReceiptAlreadyRedeemedException e) { + } catch (final PurchaseReceiptAlreadyRedeemedException e) { return GetReceiptCredentialResponse.newBuilder().setAlreadyRedeemed(FailedPrecondition.newBuilder().build()) .build(); - } catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) { + } catch (final PurchaseNotFoundException | PurchaseForbiddenException _) { return GetReceiptCredentialResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build(); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java index 896b3824d..2c3f0198c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java @@ -13,6 +13,7 @@ import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; +import org.signal.chat.purchase.PaymentRequired; import org.signal.libsignal.zkgroup.VerificationFailedException; import org.signal.libsignal.zkgroup.donation.DonationPermit; import org.whispersystems.textsecuregcm.badges.BadgeTranslator; @@ -25,13 +26,14 @@ import org.whispersystems.textsecuregcm.entities.PurchasableBadge; import org.whispersystems.textsecuregcm.metrics.MetricsUtil; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; -import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; -import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration; -import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; -import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration; -import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.ChargeFailure; +import org.whispersystems.textsecuregcm.purchases.CurrencyConfiguration; +import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.purchases.LevelConfiguration; +import org.whispersystems.textsecuregcm.purchases.PaymentMethod; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; import org.whispersystems.textsecuregcm.util.ua.ClientPlatform; import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException; import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil; @@ -163,6 +165,12 @@ public class SubscriptionsUtil { .increment(); } + public static PaymentRequired toPaymentRequired(final PurchasePaymentRequiredException e) { + final PaymentRequired.Builder builder = PaymentRequired.newBuilder(); + e.getChargeFailure().ifPresent(chargeFailure -> builder.setChargeFailure(toChargeFailure(e.getProcessor(), chargeFailure))); + return builder.build(); + } + public static org.signal.chat.purchase.ChargeFailure toChargeFailure(final PaymentProvider processor, final ChargeFailure chargeFailure) { final org.signal.chat.purchase.ChargeFailure.Builder builder = org.signal.chat.purchase.ChargeFailure.newBuilder() diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/mappers/SubscriptionExceptionMapper.java b/service/src/main/java/org/whispersystems/textsecuregcm/mappers/PurchaseExceptionMapper.java similarity index 52% rename from service/src/main/java/org/whispersystems/textsecuregcm/mappers/SubscriptionExceptionMapper.java rename to service/src/main/java/org/whispersystems/textsecuregcm/mappers/PurchaseExceptionMapper.java index 15d801366..166b358e8 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/mappers/SubscriptionExceptionMapper.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/mappers/PurchaseExceptionMapper.java @@ -12,63 +12,62 @@ import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.ext.ExceptionMapper; import java.util.Map; -import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException; -import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException; +import org.whispersystems.textsecuregcm.purchases.ChargeFailure; +import org.whispersystems.textsecuregcm.purchases.PurchaseException; +import org.whispersystems.textsecuregcm.purchases.PurchaseForbiddenException; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException; +import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorConflictException; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException; +import org.whispersystems.textsecuregcm.purchases.SubscriberIdCreationNotPermittedException; -public class SubscriptionExceptionMapper implements ExceptionMapper { +public class PurchaseExceptionMapper implements ExceptionMapper { @VisibleForTesting public static final int PROCESSOR_ERROR_STATUS_CODE = 440; public record ChargeFailureResponse(String processor, ChargeFailure chargeFailure) {} @Override - public Response toResponse(final SubscriptionException exception) { + public Response toResponse(final PurchaseException exception) { // Some exceptions have specific error body formats - if (exception instanceof SubscriptionInvalidAmountException e) { + if (exception instanceof PurchaseInvalidAmountException e) { return Response .status(Response.Status.BAD_REQUEST) .entity(Map.of("error", e.getErrorCode())) .type(MediaType.APPLICATION_JSON_TYPE) .build(); } - if (exception instanceof SubscriptionProcessorException e) { + if (exception instanceof PurchaseProcessorException e) { return Response.status(PROCESSOR_ERROR_STATUS_CODE) .entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure())) .type(MediaType.APPLICATION_JSON_TYPE) .build(); } - if (exception instanceof SubscriptionChargeFailurePaymentRequiredException e) { + if (exception instanceof PurchasePaymentRequiredException e && e.getChargeFailure().isPresent()) { return Response .status(Response.Status.PAYMENT_REQUIRED) - .entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure())) + .entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure().get())) .type(MediaType.APPLICATION_JSON_TYPE) .build(); } // Otherwise, we'll return a generic error message WebApplicationException, with a detailed error if one is provided final Response.Status status = (switch (exception) { - case SubscriptionNotFoundException _ -> Response.Status.NOT_FOUND; - case SubscriptionForbiddenException _ -> Response.Status.FORBIDDEN; - case SubscriptionInvalidArgumentsException _ -> Response.Status.BAD_REQUEST; - case SubscriptionProcessorConflictException _ -> Response.Status.CONFLICT; - case SubscriptionPaymentRequiredException _ -> Response.Status.PAYMENT_REQUIRED; - case SubscriptionReceiptAlreadyRedeemedException _ -> Response.Status.CONFLICT; + case PurchaseNotFoundException _ -> Response.Status.NOT_FOUND; + case PurchaseForbiddenException _ -> Response.Status.FORBIDDEN; + case PurchaseInvalidArgumentsException _ -> Response.Status.BAD_REQUEST; + case PurchaseProcessorConflictException _ -> Response.Status.CONFLICT; + case PurchasePaymentRequiredException _ -> Response.Status.PAYMENT_REQUIRED; + case PurchaseReceiptAlreadyRedeemedException _ -> Response.Status.CONFLICT; case SubscriberIdCreationNotPermittedException _ -> Response.Status.UNAUTHORIZED; default -> Response.Status.INTERNAL_SERVER_ERROR; }); - // If the SubscriptionException came with suitable error message, include that in the response body. Otherwise, + // If the PurchaseException came with suitable error message, include that in the response body. Otherwise, // don't provide any message to the WebApplicationException constructor so the response includes the default // HTTP error message for the status. final WebApplicationException wae = exception.errorDetail() diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreClient.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreClient.java similarity index 97% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreClient.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreClient.java index 279a579b6..b6ffde821 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreClient.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreClient.java @@ -2,7 +2,7 @@ * Copyright 2025 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import com.apple.itunes.storekit.client.APIError; import com.apple.itunes.storekit.client.APIException; @@ -126,15 +126,15 @@ public class AppleAppStoreClient { } public StatusResponse getAllSubscriptions(final String originalTransactionId, final Tags errorTags) - throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException { + throws PurchaseNotFoundException, PurchaseInvalidArgumentsException, 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 TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND, ACCOUNT_NOT_FOUND -> throw new PurchaseNotFoundException(); case RATE_LIMIT_EXCEEDED -> throw new RateLimitExceededException(null); - case INVALID_ORIGINAL_TRANSACTION_ID -> throw new SubscriptionInvalidArgumentsException(e.getApiErrorMessage()); + case INVALID_ORIGINAL_TRANSACTION_ID -> throw new PurchaseInvalidArgumentsException(e.getApiErrorMessage()); case null, default -> throw new UncheckedIOException(new IOException(e)); } } catch (IOException e) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreDecodedTransaction.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreDecodedTransaction.java similarity index 91% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreDecodedTransaction.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreDecodedTransaction.java index 166fb6e5a..19137017f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreDecodedTransaction.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreDecodedTransaction.java @@ -1,4 +1,4 @@ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import com.apple.itunes.storekit.model.JWSRenewalInfoDecodedPayload; import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreManager.java similarity index 79% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreManager.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreManager.java index 6c3c679db..ac48e9524 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreManager.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import com.apple.itunes.storekit.model.AutoRenewStatus; import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload; @@ -66,16 +66,16 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi * @param originalTransactionId The originalTransactionId associated with the subscription * @return the subscription level of the valid transaction. * @throws RateLimitExceededException If rate-limited - * @throws SubscriptionNotFoundException If the provided originalTransactionId was not found - * @throws SubscriptionPaymentRequiredException If the originalTransactionId exists but is in a state that does not + * @throws PurchaseNotFoundException If the provided originalTransactionId was not found + * @throws PurchasePaymentRequiredException If the originalTransactionId exists but is in a state that does not * grant the user an entitlement - * @throws SubscriptionInvalidArgumentsException If the transaction is valid but does not contain a subscription + * @throws PurchaseInvalidArgumentsException If the transaction is valid but does not contain a subscription */ public Long validateTransaction(final String originalTransactionId) - throws SubscriptionInvalidArgumentsException, RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException { + throws PurchaseInvalidArgumentsException, RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException { final AppleAppStoreDecodedTransaction tx = lookupAndValidateTransaction(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "validate")); if (!isSubscriptionActive(tx)) { - throw new SubscriptionPaymentRequiredException(); + throw new PurchasePaymentRequiredException(getProvider()); } return getLevel(tx.transaction()).getValue(); } @@ -90,20 +90,20 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi * * @param originalTransactionId The originalTransactionId associated with the subscription * @throws RateLimitExceededException If rate-limited - * @throws SubscriptionInvalidArgumentsException If the transaction is valid but does not contain a subscription, or + * @throws PurchaseInvalidArgumentsException If the transaction is valid but does not contain a subscription, or * the transaction has not already been cancelled with storekit */ @Override public void cancelAllActiveSubscriptions(String originalTransactionId) - throws SubscriptionInvalidArgumentsException, RateLimitExceededException { + throws PurchaseInvalidArgumentsException, RateLimitExceededException { try { 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) { - throw new SubscriptionInvalidArgumentsException("must cancel subscription with storekit before deleting"); + throw new PurchaseInvalidArgumentsException("must cancel subscription with storekit before deleting"); } - } catch (SubscriptionNotFoundException _) { + } catch (PurchaseNotFoundException _) { // If the subscription is not found there is no need to do anything, so we can squash it } // The subscription will not auto-renew, so we can stop tracking it @@ -111,7 +111,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi @Override public SubscriptionInformation getSubscriptionInformation(final String originalTransactionId) - throws RateLimitExceededException, SubscriptionNotFoundException { + throws RateLimitExceededException, PurchaseNotFoundException { final AppleAppStoreDecodedTransaction tx = lookupSubscription(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "info")); final SubscriptionStatus status = switch (tx.signedTransaction().getStatus()) { case ACTIVE -> SubscriptionStatus.ACTIVE; @@ -137,10 +137,10 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi @Override public ReceiptItem getReceiptItem(String originalTransactionId) - throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException { + throws RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException { final AppleAppStoreDecodedTransaction tx = lookupSubscription(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "receipt")); if (!isSubscriptionActive(tx)) { - throw new SubscriptionPaymentRequiredException(); + throw new PurchasePaymentRequiredException(getProvider()); } // A new transactionId might be generated if you restore a subscription on a new device. webOrderLineItemId is @@ -154,48 +154,46 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi } @Override - public Optional claimOneTimePurchase(final String transactionId) - throws RateLimitExceededException, SubscriptionInvalidArgumentsException { + public PaymentDetails claimOneTimePurchase(final String transactionId) + throws RateLimitExceededException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, PurchasePaymentRequiredException { final Optional maybeTransaction = appleAppStoreClient.lookupTransaction(transactionId, Tags.of(LOOKUP_TYPE_TAG, "one_time")); if (maybeTransaction.isEmpty()) { - return Optional.empty(); + throw new PurchaseNotFoundException(); } final JWSTransactionDecodedPayload transaction = maybeTransaction.get(); if (transaction.getType() != Type.CONSUMABLE) { - throw new SubscriptionInvalidArgumentsException("transaction is not a consumable one-time purchase"); + throw new PurchaseInvalidArgumentsException("transaction is not a consumable one-time purchase"); } - final PaymentStatus paymentStatus = transaction.getRevocationDate() == null - ? PaymentStatus.SUCCEEDED - : PaymentStatus.FAILED; - - return Optional.of(new PaymentDetails( + if (transaction.getRevocationDate() != null) { + throw new PurchasePaymentRequiredException(getProvider()); + } + return new PaymentDetails( Objects.requireNonNull(transaction.getTransactionId()), getLevel(transaction), - paymentStatus, - transaction.getPurchaseDate() != null ? Instant.ofEpochMilli(transaction.getPurchaseDate()) : null, - null)); + Instant.ofEpochMilli(transaction.getPurchaseDate())); + } private AppleAppStoreDecodedTransaction lookupSubscription(final String originalTransactionId, final Tags tags) - throws RateLimitExceededException, SubscriptionNotFoundException { + throws RateLimitExceededException, PurchaseNotFoundException { try { return lookupAndValidateTransaction(originalTransactionId, tags); - } catch (SubscriptionInvalidArgumentsException e) { + } catch (PurchaseInvalidArgumentsException e) { // Shouldn't happen because we previously validated this transactionId before storing it throw new UncheckedIOException(new IOException(e)); } } private AppleAppStoreDecodedTransaction lookupAndValidateTransaction(final String originalTransactionId, final Tags errorTags) - throws SubscriptionInvalidArgumentsException, RateLimitExceededException, SubscriptionNotFoundException { + throws PurchaseInvalidArgumentsException, RateLimitExceededException, PurchaseNotFoundException { final StatusResponse statuses = appleAppStoreClient.getAllSubscriptions(originalTransactionId, errorTags); final SubscriptionGroupIdentifierItem item = statuses.getData().stream() .filter(s -> subscriptionGroupId.equals(s.getSubscriptionGroupIdentifier())).findFirst() - .orElseThrow(() -> new SubscriptionInvalidArgumentsException("transaction did not contain a backup subscription", null)); + .orElseThrow(() -> new PurchaseInvalidArgumentsException("transaction did not contain a backup subscription", null)); final List txs = item.getLastTransactions().stream() .map(txItem -> appleAppStoreClient.verifySubscription(statuses.getEnvironment(), txItem)) @@ -207,7 +205,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi // Get All Subscriptions only requires that the transaction be some transaction associated with the // subscription. This is too flexible, since we'd like to key on the originalTransactionId in the // SubscriptionManager. - throw new SubscriptionInvalidArgumentsException("transactionId did not include a paid subscription or the provided transactionId was not an originalTransactionId", null); + throw new PurchaseInvalidArgumentsException("transactionId did not include a paid subscription or the provided transactionId was not an originalTransactionId", null); } if (txs.size() > 1) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BankMandateTranslator.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/BankMandateTranslator.java similarity index 95% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BankMandateTranslator.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/BankMandateTranslator.java index 438617b1a..4fc5338bc 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BankMandateTranslator.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/BankMandateTranslator.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import java.util.List; import java.util.Locale; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BankTransferType.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/BankTransferType.java similarity index 70% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BankTransferType.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/BankTransferType.java index 589202692..71cc93f8c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BankTransferType.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/BankTransferType.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; public enum BankTransferType { SEPA_DEBIT diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeGraphqlClient.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/BraintreeGraphqlClient.java similarity index 99% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeGraphqlClient.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/BraintreeGraphqlClient.java index a05cc6968..171520a52 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeGraphqlClient.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/BraintreeGraphqlClient.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import com.apollographql.apollo3.api.ApolloResponse; import com.apollographql.apollo3.api.Operation; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/BraintreeManager.java similarity index 94% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManager.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/BraintreeManager.java index 78c676c47..69a18cd90 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/BraintreeManager.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import com.braintree.graphql.clientoperation.ChargePayPalOneTimePaymentMutation; import com.braintree.graphql.clientoperation.CreatePayPalBillingAgreementMutation; @@ -48,6 +48,7 @@ import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager; import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient; import org.whispersystems.textsecuregcm.metrics.MetricsUtil; import org.whispersystems.textsecuregcm.storage.PaymentTime; +import org.whispersystems.textsecuregcm.subscriptions.DonationsPubsub; import org.whispersystems.textsecuregcm.util.ExecutorUtil; import org.whispersystems.textsecuregcm.util.GoogleApiUtil; import org.whispersystems.textsecuregcm.util.SystemMapper; @@ -131,14 +132,10 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess } @Override - public Optional claimOneTimePurchase(final String paymentId) { + public PaymentDetails claimOneTimePurchase(final String paymentId) + throws PurchaseNotFoundException, PurchaseReceiptRequestedForOpenPaymentException, PurchasePaymentRequiredException { try { final Transaction transaction = braintreeGateway.transaction().find(paymentId); - ChargeFailure chargeFailure = null; - if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) { - chargeFailure = createChargeFailure(transaction); - } - final ReceiptLevel level = Optional.ofNullable(transaction.getCustomFields()) .map(m -> m.get(BraintreeGraphqlClient.LEVEL_METADATA_NAME)) .map(Long::parseLong) @@ -146,14 +143,13 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess .orElseThrow(() -> new IllegalStateException( "failed to retrieve level metadata from payment intent %s".formatted(paymentId))); - return Optional.of(new PaymentDetails(transaction.getGraphQLId(), - level, - getPaymentStatus(transaction.getStatus()), - transaction.getCreatedAt().toInstant(), - chargeFailure)); - + return switch (getPaymentStatus(transaction.getStatus())) { + case SUCCEEDED -> new PaymentDetails(transaction.getGraphQLId(), level, transaction.getCreatedAt().toInstant()); + case PROCESSING -> throw new PurchaseReceiptRequestedForOpenPaymentException(); + case UNKNOWN, FAILED -> throw new PurchasePaymentRequiredException(getProvider(), createChargeFailure(transaction)); + }; } catch (final NotFoundException e) { - return Optional.empty(); + throw new PurchaseNotFoundException(); } } @@ -168,7 +164,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess public PayPalChargeSuccessDetails captureOneTimePayment(final String payerId, final String paymentId, final String paymentToken, final String currency, final long amount, final long level, @Nullable final ClientPlatform clientPlatform) - throws SubscriptionProcessorException, IOException { + throws PurchaseProcessorException, IOException { final TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment response = braintreeGraphqlClient.tokenizePayPalOneTimePayment( payerId, paymentId, paymentToken); final ChargePayPalOneTimePaymentMutation.ChargePaymentMethod chargeResponse = braintreeGraphqlClient.chargeOneTimePayment( @@ -214,7 +210,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess switch (unsuccessfulTx.getProcessorResponseCode()) { case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE -> - throw new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx)); + throw new PurchaseProcessorException(getProvider(), createChargeFailure(unsuccessfulTx)); default -> { logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode()); @@ -364,11 +360,11 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess @Override public SubscriptionId createSubscription(final String customerId, final String planId, final long level, final long lastSubscriptionCreatedAt) - throws SubscriptionProcessorConflictException, SubscriptionProcessorException { + throws PurchaseProcessorConflictException, PurchaseProcessorException { final com.braintreegateway.PaymentMethod paymentMethod = getDefaultPaymentMethod(customerId); if (paymentMethod == null) { - throw new SubscriptionProcessorConflictException(); + throw new PurchaseProcessorConflictException(); } final Optional maybeExistingSubscription = paymentMethod.getSubscriptions().stream() @@ -402,7 +398,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess throw Optional .ofNullable(result.getTarget()) .flatMap(subscription -> subscription.getTransactions().stream().findFirst()) - .map(transaction -> new SubscriptionProcessorException(getProvider(), + .map(transaction -> new PurchaseProcessorException(getProvider(), createChargeFailure(transaction))) .orElseThrow(() -> new BraintreeException(result.getMessage())); } @@ -418,7 +414,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess @Override public CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updateSubscription(final Object subscriptionObj, final String planId, final long level, - final String idempotencyKey) throws SubscriptionProcessorConflictException, SubscriptionProcessorException { + final String idempotencyKey) throws PurchaseProcessorConflictException, PurchaseProcessorException { if (!(subscriptionObj instanceof final Subscription subscription)) { throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName()); @@ -430,7 +426,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess endSubscription(subscription); final Transaction transaction = getLatestTransactionForSubscription(subscription) - .orElseThrow(SubscriptionProcessorConflictException::new); + .orElseThrow(PurchaseProcessorConflictException::new); final Customer customer = transaction.getCustomer(); @@ -583,17 +579,17 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess @Override public ReceiptItem getReceiptItem(final String subscriptionId) - throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionChargeFailurePaymentRequiredException { + throws PurchaseReceiptRequestedForOpenPaymentException, PurchasePaymentRequiredException { final Subscription subscription = getSubscription(getSubscription(subscriptionId)); final Transaction transaction = getLatestTransactionForSubscription(subscription) - .orElseThrow(SubscriptionReceiptRequestedForOpenPaymentException::new); + .orElseThrow(PurchaseReceiptRequestedForOpenPaymentException::new); if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) { final SubscriptionStatus subscriptionStatus = getSubscriptionStatus(subscription.getStatus(), true); if (subscriptionStatus.equals(SubscriptionStatus.ACTIVE) || subscriptionStatus.equals( SubscriptionStatus.PAST_DUE)) { - throw new SubscriptionReceiptRequestedForOpenPaymentException(); + throw new PurchaseReceiptRequestedForOpenPaymentException(); } - throw new SubscriptionChargeFailurePaymentRequiredException(getProvider(), createChargeFailure(transaction)); + throw new PurchasePaymentRequiredException(getProvider(), createChargeFailure(transaction)); } final Instant paidAt = transaction.getSubscriptionDetails().getBillingPeriodStartDate().toInstant(); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreePlanMetadata.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/BraintreePlanMetadata.java similarity index 72% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreePlanMetadata.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/BraintreePlanMetadata.java index ab60cf699..59a28f2a3 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreePlanMetadata.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/BraintreePlanMetadata.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; public record BraintreePlanMetadata(long level) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ChargeFailure.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/ChargeFailure.java similarity index 98% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ChargeFailure.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/ChargeFailure.java index 3911ef03b..6c3ebc1bd 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ChargeFailure.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/ChargeFailure.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import io.swagger.v3.oas.annotations.ExternalDocumentation; import io.swagger.v3.oas.annotations.media.Schema; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/CurrencyConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/CurrencyConfiguration.java similarity index 94% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/CurrencyConfiguration.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/CurrencyConfiguration.java index 69e79226e..1ffc4e6ac 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/CurrencyConfiguration.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/CurrencyConfiguration.java @@ -1,4 +1,4 @@ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import io.swagger.v3.oas.annotations.media.Schema; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/CustomerAwareSubscriptionPaymentProcessor.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/CustomerAwareSubscriptionPaymentProcessor.java similarity index 68% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/CustomerAwareSubscriptionPaymentProcessor.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/CustomerAwareSubscriptionPaymentProcessor.java index 775ecfa40..e1fcd5571 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/CustomerAwareSubscriptionPaymentProcessor.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/CustomerAwareSubscriptionPaymentProcessor.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import java.io.IOException; import java.util.Set; @@ -41,12 +41,12 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP * @param paymentMethodToken a processor-specific token previously acquired at * {@link #createPaymentMethodSetupToken} * @param currentSubscriptionId (nullable) an active subscription ID, in case it needs an explicit update - * @throws SubscriptionInvalidArgumentsException If the paymentMethodToken is invalid or the payment method has not + * @throws PurchaseInvalidArgumentsException If the paymentMethodToken is invalid or the payment method has not * finished being set up * @throws IOException If there was an error talking to the external payment provider */ void setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodToken, - @Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException, IOException; + @Nullable String currentSubscriptionId) throws PurchaseInvalidArgumentsException, IOException; Object getSubscription(String subscriptionId); @@ -58,13 +58,13 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP * @param level The level of the subscription * @param lastSubscriptionCreatedAt The timestamp of the last successfully created subscription * @return A subscription identifier - * @throws SubscriptionProcessorException If there was a failure processing the charge - * @throws SubscriptionPaymentRequiresActionException If the payment requires additional steps before charging - * @throws SubscriptionInvalidIdempotencyKeyException If the idempotency key was reused on a modified request - * @throws SubscriptionProcessorConflictException If there was no payment method on the customer + * @throws PurchaseProcessorException If there was a failure processing the charge + * @throws PurchasePaymentRequiresActionException If the payment requires additional steps before charging + * @throws PurchaseInvalidIdempotencyKeyException If the idempotency key was reused on a modified request + * @throws PurchaseProcessorConflictException If there was no payment method on the customer */ SubscriptionId createSubscription(String customerId, String templateId, long level, long lastSubscriptionCreatedAt) - throws SubscriptionProcessorException, SubscriptionPaymentRequiresActionException, SubscriptionInvalidIdempotencyKeyException, SubscriptionProcessorConflictException; + throws PurchaseProcessorException, PurchasePaymentRequiresActionException, PurchaseInvalidIdempotencyKeyException, PurchaseProcessorConflictException; /** * Update an existing subscription on a customer @@ -74,15 +74,15 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP * @param level The target level of the subscription * @param idempotencyKey An idempotency key to prevent retries of successful requests * @return A subscription identifier - * @throws SubscriptionProcessorException If there was a failure processing the charge - * @throws SubscriptionInvalidIdempotencyKeyException If the idempotency key was reused on a modified request - * @throws SubscriptionInvalidLevelException If the level transition is not permitted - * @throws SubscriptionPaymentRequiresActionException If the payment requires additional steps before charging - * @throws SubscriptionProcessorConflictException If there was no payment method on the customer + * @throws PurchaseProcessorException If there was a failure processing the charge + * @throws PurchaseInvalidIdempotencyKeyException If the idempotency key was reused on a modified request + * @throws PurchaseInvalidLevelException If the level transition is not permitted + * @throws PurchasePaymentRequiresActionException If the payment requires additional steps before charging + * @throws PurchaseProcessorConflictException If there was no payment method on the customer */ SubscriptionId updateSubscription(Object subscription, String templateId, long level, String idempotencyKey) - throws SubscriptionInvalidIdempotencyKeyException, SubscriptionInvalidLevelException, - SubscriptionPaymentRequiresActionException, SubscriptionProcessorException, SubscriptionProcessorConflictException; + throws PurchaseInvalidIdempotencyKeyException, PurchaseInvalidLevelException, + PurchasePaymentRequiresActionException, PurchaseProcessorException, PurchaseProcessorConflictException; /** * @param subscription diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/GooglePlayBillingManager.java similarity index 87% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManager.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/GooglePlayBillingManager.java index 488a70791..e02bac669 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/GooglePlayBillingManager.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonResponseException; @@ -132,7 +132,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O * */ public void acknowledgePurchase() - throws RateLimitExceededException, SubscriptionNotFoundException { + throws RateLimitExceededException, PurchaseNotFoundException { if (!requiresAck) { // We've already acknowledged this purchase on a previous attempt, nothing to do return; @@ -153,12 +153,12 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O * @param purchaseToken The play store billing purchaseToken that represents a subscription purchase * @return A {@link ValidatedToken} that can be acknowledged * @throws RateLimitExceededException If rate-limited by play-billing - * @throws SubscriptionNotFoundException If the provided purchaseToken was not found in play-billing - * @throws SubscriptionPaymentRequiredException If the purchaseToken exists but is in a state that does not grant the + * @throws PurchaseNotFoundException If the provided purchaseToken was not found in play-billing + * @throws PurchasePaymentRequiredException If the purchaseToken exists but is in a state that does not grant the * user an entitlement */ public ValidatedToken validateToken(String purchaseToken) - throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException { + throws RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException { final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken); final SubscriptionState state = SubscriptionState .fromString(subscription.getSubscriptionState()) @@ -173,7 +173,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O if (state != SubscriptionState.ACTIVE && state != SubscriptionState.IN_GRACE_PERIOD && state != SubscriptionState.CANCELED) { - throw new SubscriptionPaymentRequiredException( + throw new PurchasePaymentRequiredException(getProvider(), "Cannot acknowledge purchase for subscription in state " + subscription.getSubscriptionState()); } @@ -212,14 +212,14 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O executeTokenOperation(pub -> pub.purchases().subscriptions().cancel(packageName, purchase.getProductId(), purchaseToken)); - } catch (SubscriptionNotFoundException e) { + } catch (PurchaseNotFoundException e) { // If the subscription is not found there is no need to do anything, so we can squash it } } @Override public SubscriptionInformation getSubscriptionInformation(final String purchaseToken) - throws RateLimitExceededException, SubscriptionNotFoundException { + throws RateLimitExceededException, PurchaseNotFoundException { final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken); final SubscriptionPrice price = getSubscriptionPrice(subscription); @@ -275,7 +275,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O @Override public ReceiptItem getReceiptItem(String purchaseToken) - throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException { + throws RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException { final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken); Metrics.counter(GET_RECEIPT_COUNTER_NAME, subscriptionTags(subscription)).increment(); @@ -288,7 +288,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O // We don't need to check any state at this point, just whether the subscription is currently valid. If the // subscription is in a grace period, the expiration time will be dynamically extended, see // https://developer.android.com/google/play/billing/lifecycle/subscriptions#grace-period - throw new SubscriptionPaymentRequiredException(); + throw new PurchasePaymentRequiredException(getProvider()); } if (requiresAcknowledgement(subscription)) { @@ -318,55 +318,49 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O /// 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 claimOneTimePurchase(final String purchaseToken) - throws IOException, RateLimitExceededException, SubscriptionInvalidArgumentsException { - try { - final ProductPurchaseV2 productPurchaseV2 = executeTokenOperation( + public PaymentDetails claimOneTimePurchase(final String purchaseToken) + throws IOException, RateLimitExceededException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, PurchasePaymentRequiredException, PurchaseReceiptRequestedForOpenPaymentException { + 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 PurchaseState purchaseState = Optional + .ofNullable(productPurchaseV2.getPurchaseStateContext()) + .map(PurchaseStateContext::getPurchaseState) + .flatMap(PurchaseState::fromString) + .orElse(PurchaseState.PURCHASE_STATE_UNSPECIFIED); - final ProductLineItem lineItem = getLineItem(productPurchaseV2); - final String productId = lineItem.getProductId(); - final ReceiptLevel 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)); - } + switch (purchaseState) { + case PURCHASED -> { } - return Optional.of(new PaymentDetails(purchaseToken, level, paymentStatus, purchaseTime, null)); - } catch (SubscriptionNotFoundException e) { - return Optional.empty(); + case PENDING -> throw new PurchaseReceiptRequestedForOpenPaymentException(); + case CANCELLED, PURCHASE_STATE_UNSPECIFIED -> throw new PurchasePaymentRequiredException(getProvider()); } + + final ProductLineItem lineItem = getLineItem(productPurchaseV2); + final String productId = lineItem.getProductId(); + final ReceiptLevel level = productIdToLevel(productId); + final Instant 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 new PaymentDetails(purchaseToken, level, purchaseTime); } - private ProductLineItem getLineItem(final ProductPurchaseV2 purchase) throws SubscriptionInvalidArgumentsException { + private ProductLineItem getLineItem(final ProductPurchaseV2 purchase) throws PurchaseInvalidArgumentsException { final List lineItems = purchase.getProductLineItem(); if (lineItems == null || lineItems.isEmpty()) { - throw new SubscriptionInvalidArgumentsException("purchase has no line items"); + throw new PurchaseInvalidArgumentsException("purchase has no line items"); } if (lineItems.size() > 1) { logger.warn("{} line items found for purchase {}, expected 1", lineItems.size(), purchase.getOrderId()); @@ -381,20 +375,20 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O /** * Execute a synchronous API call on a purchaseToken, mapping expected errors to the appropriate - * {@link SubscriptionException} + * {@link PurchaseException} * * @param apiCall An API call that operates on a purchaseToken * @param The result of the API call * @return A stage that completes with the result of the API call */ private R executeTokenOperation(final ApiCall apiCall) - throws RateLimitExceededException, SubscriptionNotFoundException { + throws RateLimitExceededException, PurchaseNotFoundException { try { return apiCall.req(androidPublisher).execute(); } catch (HttpResponseException e) { if (e.getStatusCode() == Response.Status.NOT_FOUND.getStatusCode() || e.getStatusCode() == Response.Status.GONE.getStatusCode()) { - throw new SubscriptionNotFoundException(); + throw new PurchaseNotFoundException(); } if (e.getStatusCode() == Response.Status.TOO_MANY_REQUESTS.getStatusCode()) { throw new RateLimitExceededException(null); @@ -418,7 +412,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O } private SubscriptionPurchaseV2 lookupSubscription(final String purchaseToken) - throws RateLimitExceededException, SubscriptionNotFoundException { + throws RateLimitExceededException, PurchaseNotFoundException { return executeTokenOperation(publisher -> publisher.purchases().subscriptionsv2().get(packageName, purchaseToken)); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/LevelConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/LevelConfiguration.java similarity index 86% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/LevelConfiguration.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/LevelConfiguration.java index 450cb71a7..3588dc41e 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/LevelConfiguration.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/LevelConfiguration.java @@ -1,4 +1,4 @@ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import io.swagger.v3.oas.annotations.media.Schema; import org.whispersystems.textsecuregcm.entities.Badge; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/LoginPurchaseManager.java similarity index 72% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManager.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/LoginPurchaseManager.java index 53417a48e..397484795 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/LoginPurchaseManager.java @@ -2,15 +2,14 @@ * Copyright 2026 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; +import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Map; -import java.util.Optional; -import com.google.common.annotations.VisibleForTesting; import org.signal.libsignal.zkgroup.VerificationFailedException; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse; @@ -46,7 +45,7 @@ public class LoginPurchaseManager { /// Verify a completed one-time purchase and issue a receipt credential for it. /// /// Repeated calls must use the same `receiptCredentialRequest`; a second request for a purchase that was already - /// redeemed fails with [SubscriptionReceiptAlreadyRedeemedException]. + /// redeemed fails with [PurchaseReceiptAlreadyRedeemedException]. /// /// @param paymentProvider The provider that processed the purchase /// @param purchaseId The identifier for the purchase in the `paymentProvider` @@ -58,37 +57,28 @@ public class LoginPurchaseManager { final PaymentProvider paymentProvider, final String purchaseId, final ReceiptCredentialRequest receiptCredentialRequest) - throws RateLimitExceededException, SubscriptionInvalidArgumentsException, IOException, SubscriptionNotFoundException, SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionPaymentRequiredException, SubscriptionReceiptAlreadyRedeemedException, VerificationFailedException { + throws RateLimitExceededException, PurchaseInvalidArgumentsException, IOException, PurchaseNotFoundException, PurchaseReceiptRequestedForOpenPaymentException, PurchasePaymentRequiredException, PurchaseReceiptAlreadyRedeemedException, VerificationFailedException { final OneTimePaymentProcessor oneTimePaymentProcessor = oneTimePaymentProcessors.get(paymentProvider); if (oneTimePaymentProcessor == null) { - throw new SubscriptionInvalidArgumentsException("unknown payment provider: " + paymentProvider); + throw new PurchaseInvalidArgumentsException("unknown payment provider: " + paymentProvider); } - final PaymentDetails paymentDetails = oneTimePaymentProcessor - .claimOneTimePurchase(purchaseId) - .orElseThrow(SubscriptionNotFoundException::new); - if (paymentDetails.status() == PaymentStatus.PROCESSING) { - throw new SubscriptionReceiptRequestedForOpenPaymentException(); - } else if (paymentDetails.status() != PaymentStatus.SUCCEEDED) { - throw Optional.ofNullable(paymentDetails.chargeFailure()) - .map( - cf -> new SubscriptionChargeFailurePaymentRequiredException(paymentProvider, cf)) - .orElseGet(SubscriptionPaymentRequiredException::new); - } else if (paymentDetails.level() != ReceiptLevel.LOGIN) { - throw new SubscriptionInvalidArgumentsException("purchase was for an unexpected product"); + final PaymentDetails paymentDetails = oneTimePaymentProcessor.claimOneTimePurchase(purchaseId); + if (paymentDetails.level() != ReceiptLevel.LOGIN) { + throw new PurchaseInvalidArgumentsException("purchase was for an unexpected product"); } // Calculating the expiration from the creation date works for IAP purchases. However, for other processors, the // creation date of the payment intent might be days before the payment actually completed. If we support non-IAP - // processors we should attempt to get the latest date. see OneTimeDonationController/OneTimeDonationManager + // processors we should attempt to get the latest date. see OneTimeDonationController/OneTimeDonationsManager final Instant expiration = paymentDetails.created().plus(LOGIN_EXPIRATION).truncatedTo(ChronoUnit.DAYS); try { issuedReceiptsManager.recordOneTimeIssuance(paymentDetails.id(), paymentProvider, receiptCredentialRequest, expiration); } catch (WriteConflictException _) { - throw new SubscriptionReceiptAlreadyRedeemedException(); + throw new PurchaseReceiptAlreadyRedeemedException(); } return zkReceiptOperations.issueReceiptCredential(receiptCredentialRequest, expiration.getEpochSecond(), diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/purchases/OneTimePaymentProcessor.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/OneTimePaymentProcessor.java new file mode 100644 index 000000000..1d6d82614 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/OneTimePaymentProcessor.java @@ -0,0 +1,22 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.purchases; + +import java.io.IOException; +import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; + +public interface OneTimePaymentProcessor { + + /// Retrieve information about a one-time purchase. + /// + /// @param paymentIdentifier A string that identifies the payment in the payment processor + /// @return Details about the purchase if it was successful + /// + /// @throws PurchaseInvalidArgumentsException The purchase does not match a configured product type + /// @throws PurchaseNotFoundException The paymentIdentifier does not identify a transaction in the processor + /// @throws PurchasePaymentRequiredException The identified payment failed or was revoked + /// @throws PurchaseReceiptRequestedForOpenPaymentException The identified payment is still processing + PaymentDetails claimOneTimePurchase(final String paymentIdentifier) throws IOException, RateLimitExceededException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, PurchasePaymentRequiredException, PurchaseReceiptRequestedForOpenPaymentException; +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PayPalDonationsTranslator.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PayPalDonationsTranslator.java similarity index 95% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PayPalDonationsTranslator.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/PayPalDonationsTranslator.java index 3017c1738..c0775a8a2 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PayPalDonationsTranslator.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PayPalDonationsTranslator.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import java.util.List; import java.util.Locale; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PaymentDetails.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PaymentDetails.java new file mode 100644 index 000000000..46b06fee2 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PaymentDetails.java @@ -0,0 +1,16 @@ +/* + * Copyright 2024 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.purchases; + +import java.time.Instant; + +/** + * Payment details for a successful one-time payment specified by id + * + * @param id The id of the payment in the payment processor + * @param level The level identifier of purchase + * @param created When the payment was created + */ +public record PaymentDetails(String id, ReceiptLevel level, Instant created) {} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentMethod.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PaymentMethod.java similarity index 95% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentMethod.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/PaymentMethod.java index 9be06f3e3..9765845a0 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentMethod.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PaymentMethod.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; public enum PaymentMethod { UNKNOWN, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentProvider.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PaymentProvider.java similarity index 97% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentProvider.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/PaymentProvider.java index 4d5f1d402..fd6cf3ee1 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentProvider.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PaymentProvider.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import java.util.Arrays; import java.util.HashMap; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentStatus.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PaymentStatus.java similarity index 62% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentStatus.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/PaymentStatus.java index 4e3bccdb5..f1b780834 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentStatus.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PaymentStatus.java @@ -2,9 +2,9 @@ * Copyright 2024 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; -public enum PaymentStatus { +enum PaymentStatus { SUCCEEDED, PROCESSING, FAILED, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ProcessorCustomer.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/ProcessorCustomer.java similarity index 90% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ProcessorCustomer.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/ProcessorCustomer.java index 0c53e8f1e..1bb3685cd 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ProcessorCustomer.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/ProcessorCustomer.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import java.nio.charset.StandardCharsets; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseException.java similarity index 67% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionException.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseException.java index 349b8115f..efc71e8d9 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionException.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseException.java @@ -2,20 +2,20 @@ * Copyright 2024 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import java.util.Optional; import javax.annotation.Nullable; -public class SubscriptionException extends Exception { +public class PurchaseException extends Exception { private @Nullable String errorDetail; - public SubscriptionException(Exception cause) { + public PurchaseException(Exception cause) { this(cause, null); } - SubscriptionException(Exception cause, String errorDetail) { + PurchaseException(Exception cause, String errorDetail) { super(cause); this.errorDetail = errorDetail; } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseForbiddenException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseForbiddenException.java new file mode 100644 index 000000000..6cef76710 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseForbiddenException.java @@ -0,0 +1,12 @@ +/* + * Copyright 2025 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.purchases; + +public class PurchaseForbiddenException extends PurchaseException { + + public PurchaseForbiddenException(final String message) { + super(null, message); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidAmountException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidAmountException.java similarity index 52% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidAmountException.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidAmountException.java index 548d9e931..0c5148e53 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidAmountException.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidAmountException.java @@ -2,13 +2,13 @@ * Copyright 2025 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; -public class SubscriptionInvalidAmountException extends SubscriptionInvalidArgumentsException { +public class PurchaseInvalidAmountException extends PurchaseInvalidArgumentsException { private String errorCode; - public SubscriptionInvalidAmountException(String errorCode) { + public PurchaseInvalidAmountException(String errorCode) { super(null, null); this.errorCode = errorCode; } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidArgumentsException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidArgumentsException.java new file mode 100644 index 000000000..65d1ecb7a --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidArgumentsException.java @@ -0,0 +1,16 @@ +/* + * Copyright 2025 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.purchases; + +public class PurchaseInvalidArgumentsException extends PurchaseException { + + public PurchaseInvalidArgumentsException(final String message, final Exception cause) { + super(cause, message); + } + + public PurchaseInvalidArgumentsException(final String message) { + this(message, null); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidIdempotencyKeyException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidIdempotencyKeyException.java new file mode 100644 index 000000000..3a9aac576 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidIdempotencyKeyException.java @@ -0,0 +1,12 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.purchases; + +public class PurchaseInvalidIdempotencyKeyException extends PurchaseInvalidArgumentsException { + + public PurchaseInvalidIdempotencyKeyException(final String message) { + super(message); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidLevelException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidLevelException.java new file mode 100644 index 000000000..3cce8642d --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseInvalidLevelException.java @@ -0,0 +1,12 @@ +/* + * Copyright 2025 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.purchases; + +public class PurchaseInvalidLevelException extends PurchaseInvalidArgumentsException { + + public PurchaseInvalidLevelException() { + super(null, null); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseNotFoundException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseNotFoundException.java new file mode 100644 index 000000000..6b01fc049 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseNotFoundException.java @@ -0,0 +1,16 @@ +/* + * Copyright 2025 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.purchases; + +public class PurchaseNotFoundException extends PurchaseException { + + public PurchaseNotFoundException() { + super(null); + } + + public PurchaseNotFoundException(Exception cause) { + super(cause); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchasePaymentRequiredException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchasePaymentRequiredException.java new file mode 100644 index 000000000..1f406ada7 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchasePaymentRequiredException.java @@ -0,0 +1,43 @@ +/* + * Copyright 2025 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.purchases; + +import java.util.Optional; +import javax.annotation.Nullable; + +public class PurchasePaymentRequiredException extends PurchaseException { + + private final PaymentProvider processor; + @Nullable + private final ChargeFailure chargeFailure; + + public PurchasePaymentRequiredException(final PaymentProvider processor) { + this(processor, null, null); + } + + public PurchasePaymentRequiredException(final PaymentProvider processor, final String message) { + this(processor, null, message); + } + + public PurchasePaymentRequiredException(final PaymentProvider processor, final ChargeFailure chargeFailure) { + this(processor, chargeFailure, null); + } + + private PurchasePaymentRequiredException(final PaymentProvider processor, + @Nullable final ChargeFailure chargeFailure, @Nullable final String message) { + super(null, message); + this.processor = processor; + this.chargeFailure = chargeFailure; + } + + public PaymentProvider getProcessor() { + return processor; + } + + /// @return The reason the processor reported for the payment failure, if it reported one + public Optional getChargeFailure() { + return Optional.ofNullable(chargeFailure); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchasePaymentRequiresActionException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchasePaymentRequiresActionException.java new file mode 100644 index 000000000..744b04d03 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchasePaymentRequiresActionException.java @@ -0,0 +1,16 @@ +/* + * Copyright 2025 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.purchases; + +public class PurchasePaymentRequiresActionException extends PurchaseInvalidArgumentsException { + + public PurchasePaymentRequiresActionException(String message) { + super(message, null); + } + + public PurchasePaymentRequiresActionException() { + super(null, null); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseProcessorConflictException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseProcessorConflictException.java new file mode 100644 index 000000000..77869366b --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseProcessorConflictException.java @@ -0,0 +1,16 @@ +/* + * Copyright 2025 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.purchases; + +public class PurchaseProcessorConflictException extends PurchaseException { + + public PurchaseProcessorConflictException() { + super(null, null); + } + + public PurchaseProcessorConflictException(final String message) { + super(null, message); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionProcessorException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseProcessorException.java similarity index 63% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionProcessorException.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseProcessorException.java index b276233e2..2eeeded44 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionProcessorException.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseProcessorException.java @@ -2,14 +2,14 @@ * Copyright 2025 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; -public class SubscriptionProcessorException extends SubscriptionException { +public class PurchaseProcessorException extends PurchaseException { private final PaymentProvider processor; private final ChargeFailure chargeFailure; - public SubscriptionProcessorException(final PaymentProvider processor, final ChargeFailure chargeFailure) { + public PurchaseProcessorException(final PaymentProvider processor, final ChargeFailure chargeFailure) { super(null, null); this.processor = processor; this.chargeFailure = chargeFailure; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseReceiptAlreadyRedeemedException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseReceiptAlreadyRedeemedException.java new file mode 100644 index 000000000..e8e57efb3 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseReceiptAlreadyRedeemedException.java @@ -0,0 +1,16 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.purchases; + +public class PurchaseReceiptAlreadyRedeemedException extends PurchaseException { + + public PurchaseReceiptAlreadyRedeemedException() { + super(null, null); + } + + public PurchaseReceiptAlreadyRedeemedException(final String message) { + super(null, message); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionReceiptRequestedForOpenPaymentException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseReceiptRequestedForOpenPaymentException.java similarity index 53% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionReceiptRequestedForOpenPaymentException.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseReceiptRequestedForOpenPaymentException.java index 65845e8c8..4d2369d7a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionReceiptRequestedForOpenPaymentException.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/PurchaseReceiptRequestedForOpenPaymentException.java @@ -2,14 +2,14 @@ * Copyright 2025 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; /** * Attempted to retrieve a receipt for a subscription that hasn't yet been charged or the invoice is in the open state */ -public class SubscriptionReceiptRequestedForOpenPaymentException extends SubscriptionException { +public class PurchaseReceiptRequestedForOpenPaymentException extends PurchaseException { - public SubscriptionReceiptRequestedForOpenPaymentException() { + public PurchaseReceiptRequestedForOpenPaymentException() { super(null, null); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ReceiptCredentialPresentationFactory.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/ReceiptCredentialPresentationFactory.java similarity index 83% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ReceiptCredentialPresentationFactory.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/ReceiptCredentialPresentationFactory.java index 6d67a948c..33a02230e 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ReceiptCredentialPresentationFactory.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/ReceiptCredentialPresentationFactory.java @@ -1,4 +1,4 @@ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import org.signal.libsignal.zkgroup.InvalidInputException; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ReceiptLevel.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/ReceiptLevel.java similarity index 95% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ReceiptLevel.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/ReceiptLevel.java index 706e0c454..faf064be9 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ReceiptLevel.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/ReceiptLevel.java @@ -2,7 +2,7 @@ * Copyright 2026 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import java.util.Arrays; import java.util.Optional; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/StripeManager.java similarity index 90% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/StripeManager.java index 1c9b8ec31..7da53547b 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/StripeManager.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; @@ -46,7 +46,6 @@ import com.stripe.param.SubscriptionUpdateParams.BillingCycleAnchor; import com.stripe.param.SubscriptionUpdateParams.ProrationBehavior; import java.io.IOException; import java.io.UncheckedIOException; -import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; @@ -175,7 +174,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, @Override public void setDefaultPaymentMethodForCustomer(final String customerId, final String paymentMethodId, - @Nullable final String currentSubscriptionId) throws SubscriptionInvalidArgumentsException { + @Nullable final String currentSubscriptionId) throws PurchaseInvalidArgumentsException { final CustomerUpdateParams params = CustomerUpdateParams.builder() .setInvoiceSettings(InvoiceSettings.builder() .setDefaultPaymentMethod(paymentMethodId) @@ -185,7 +184,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, stripeClient.v1().customers().update(customerId, params, commonOptions()); } catch (final InvalidRequestException e) { // Could happen if the paymentMethodId was bunk or the client didn't actually finish setting it up - throw new SubscriptionInvalidArgumentsException(e.getMessage()); + throw new PurchaseInvalidArgumentsException(e.getMessage()); } catch (final StripeException e) { throw new UncheckedIOException(new IOException(e)); } @@ -209,13 +208,13 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, } /** - * Creates a payment intent. May throw a {@link SubscriptionInvalidAmountException} if stripe rejects the attempt if + * Creates a payment intent. May throw a {@link PurchaseInvalidAmountException} if stripe rejects the attempt if * the amount is too large or too small */ public PaymentIntent createPaymentIntent(final String currency, final long amount, final long level, - @Nullable final ClientPlatform clientPlatform) throws SubscriptionInvalidAmountException { + @Nullable final ClientPlatform clientPlatform) throws PurchaseInvalidAmountException { final PaymentIntentCreateParams.Builder builder = PaymentIntentCreateParams.builder() .setAmount(amount) @@ -235,25 +234,18 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, ? "unknown" : e.getCode().toLowerCase(Locale.ROOT); switch (errorCode) { - case "amount_too_small", "amount_too_large" -> throw new SubscriptionInvalidAmountException(errorCode); + case "amount_too_small", "amount_too_large" -> throw new PurchaseInvalidAmountException(errorCode); default -> throw new RuntimeException(e); } } } @Override - public Optional claimOneTimePurchase(final String paymentIntentId) throws IOException { + public PaymentDetails claimOneTimePurchase(final String paymentIntentId) + throws IOException, PurchaseNotFoundException, PurchaseReceiptRequestedForOpenPaymentException, PurchasePaymentRequiredException { try { final PaymentIntent paymentIntent = getPaymentIntent(paymentIntentId); - ChargeFailure chargeFailure = null; - if (paymentIntent.getLatestChargeObject() != null) { - final Charge charge = paymentIntent.getLatestChargeObject(); - if (charge.getFailureCode() != null || charge.getFailureMessage() != null) { - chargeFailure = createChargeFailure(charge); - } - } - final ReceiptLevel level = Optional.ofNullable(paymentIntent.getMetadata()) .map(m -> m.get(METADATA_KEY_LEVEL)) .map(Long::parseLong) @@ -261,14 +253,23 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, .orElseThrow(() -> new IllegalStateException( "failed to retrieve level metadata from payment intent %s".formatted(paymentIntentId))); - return Optional.of(new PaymentDetails(paymentIntent.getId(), - level, - getPaymentStatusForStatus(paymentIntent.getStatus()), - Instant.ofEpochSecond(paymentIntent.getCreated()), - chargeFailure)); + return switch (getPaymentStatusForStatus(paymentIntent.getStatus())) { + case SUCCEEDED -> + new PaymentDetails(paymentIntent.getId(), level, Instant.ofEpochSecond(paymentIntent.getCreated())); + case PROCESSING -> throw new PurchaseReceiptRequestedForOpenPaymentException(); + case FAILED, UNKNOWN -> { + if (paymentIntent.getLatestChargeObject() != null) { + final Charge charge = paymentIntent.getLatestChargeObject(); + if (charge.getFailureCode() != null || charge.getFailureMessage() != null) { + throw new PurchasePaymentRequiredException(getProvider(), createChargeFailure(charge)); + } + } + throw new PurchasePaymentRequiredException(getProvider()); + } + }; } catch (final StripeException e) { if (e.getStatusCode() == 404) { - return Optional.empty(); + throw new PurchaseNotFoundException(); } else { throw new IOException(e); } @@ -290,8 +291,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, @Override public SubscriptionId createSubscription(final String customerId, final String priceId, final long level, final long lastSubscriptionCreatedAt) - throws SubscriptionProcessorException, SubscriptionInvalidIdempotencyKeyException, - SubscriptionPaymentRequiresActionException { + throws PurchaseProcessorException, PurchaseInvalidIdempotencyKeyException, + PurchasePaymentRequiresActionException { // this relies on Stripe's idempotency key to avoid creating more than one subscription if the client // retries this request final SubscriptionCreateParams params = SubscriptionCreateParams.builder() @@ -313,12 +314,12 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, commonOptions(generateIdempotencyKeyForCreateSubscription(customerId, lastSubscriptionCreatedAt))); return new SubscriptionId(subscription.getId()); } catch (final IdempotencyException e) { - throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage()); + throw new PurchaseInvalidIdempotencyKeyException(e.getStripeError().getMessage()); } catch (final CardException e) { - throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e)); + throw new PurchaseProcessorException(getProvider(), createChargeFailureFromCardException(e)); } catch (final StripeException e) { if ("subscription_payment_intent_requires_action".equals(e.getCode())) { - throw new SubscriptionPaymentRequiresActionException(); + throw new PurchasePaymentRequiresActionException(); } throw new UncheckedIOException(new IOException(e)); } @@ -326,8 +327,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, @Override public SubscriptionId updateSubscription(final Object subscriptionObj, final String priceId, final long level, final String idempotencyKey) - throws SubscriptionInvalidIdempotencyKeyException, SubscriptionPaymentRequiresActionException, - SubscriptionProcessorException { + throws PurchaseInvalidIdempotencyKeyException, PurchasePaymentRequiresActionException, + PurchaseProcessorException { final Subscription subscription = getSubscription(subscriptionObj); @@ -366,9 +367,9 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, commonOptions(generateIdempotencyKeyForSubscriptionUpdate(subscription.getCustomer(), idempotencyKey))); return new SubscriptionId(subscription1.getId()); } catch (final IdempotencyException e) { - throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage()); + throw new PurchaseInvalidIdempotencyKeyException(e.getStripeError().getMessage()); } catch (final CardException e) { - throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e)); + throw new PurchaseProcessorException(getProvider(), createChargeFailureFromCardException(e)); } catch (final StripeException e) { throw new UncheckedIOException(new IOException(e)); } @@ -635,37 +636,34 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, @Override public ReceiptItem getReceiptItem(final String subscriptionId) - throws SubscriptionPaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException { + throws PurchasePaymentRequiredException, PurchaseReceiptRequestedForOpenPaymentException { final Invoice invoice = getSubscription(getSubscription(subscriptionId)).getLatestInvoiceObject(); return convertInvoiceToReceipt(invoice, subscriptionId); } private ReceiptItem convertInvoiceToReceipt(final Invoice latestSubscriptionInvoice, final String subscriptionId) - throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionPaymentRequiredException { + throws PurchaseReceiptRequestedForOpenPaymentException, PurchasePaymentRequiredException { if (latestSubscriptionInvoice == null) { - throw new SubscriptionReceiptRequestedForOpenPaymentException(); + throw new PurchaseReceiptRequestedForOpenPaymentException(); } if ("open".equalsIgnoreCase(latestSubscriptionInvoice.getStatus()) || "draft".equalsIgnoreCase( latestSubscriptionInvoice.getStatus())) { - throw new SubscriptionReceiptRequestedForOpenPaymentException(); + throw new PurchaseReceiptRequestedForOpenPaymentException(); } if (!"paid".equalsIgnoreCase(latestSubscriptionInvoice.getStatus())) { final Optional latestInvoicePayment = getMostRecentInvoicePayment(latestSubscriptionInvoice); - final SubscriptionPaymentRequiredException exception = latestInvoicePayment.map(invoicePayment -> { + final PurchasePaymentRequiredException exception = latestInvoicePayment.map(invoicePayment -> { final Optional maybeCharge = getChargeForInvoicePayment(invoicePayment); return maybeCharge.filter(charge -> charge.getFailureCode() != null || charge.getFailureMessage() != null) - .map(charge -> { - // If the charge object has a failure reason we can present to the user, create a detailed exception - return (SubscriptionPaymentRequiredException) (new SubscriptionChargeFailurePaymentRequiredException( - getProvider(), createChargeFailure(charge))); - }) - .orElseGet(SubscriptionPaymentRequiredException::new); + // If the charge object has a failure reason we can present to the user, create a detailed exception + .map(charge -> new PurchasePaymentRequiredException(getProvider(), createChargeFailure(charge))) + .orElseGet(() -> new PurchasePaymentRequiredException(getProvider())); }) - .orElseGet(SubscriptionPaymentRequiredException::new); + .orElseGet(() -> new PurchasePaymentRequiredException(getProvider())); throw exception; } @@ -715,7 +713,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, } public String getGeneratedSepaIdFromSetupIntent(final String setupIntentId) - throws SubscriptionNotFoundException, SubscriptionProcessorConflictException, IOException { + throws PurchaseNotFoundException, PurchaseProcessorConflictException, IOException { final SetupIntentRetrieveParams params = SetupIntentRetrieveParams.builder() .addExpand("latest_attempt") .build(); @@ -729,12 +727,12 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, // This usually indicates that the client has made requests out of order, either by not confirming // the SetupIntent or not having the user authorize the transaction. logger.debug("setupIntent {} missing expected fields", setupIntentId); - throw new SubscriptionProcessorConflictException(); + throw new PurchaseProcessorConflictException(); } return setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit(); } catch (final StripeException e) { if (e.getStatusCode() == 404) { - throw new SubscriptionNotFoundException(); + throw new PurchaseNotFoundException(); } logger.error("unexpected error from Stripe when retrieving setupIntent {}", setupIntentId, e); throw new IOException(e); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriberIdCreationNotPermittedException.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriberIdCreationNotPermittedException.java similarity index 54% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriberIdCreationNotPermittedException.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriberIdCreationNotPermittedException.java index 457ea5778..1be035142 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriberIdCreationNotPermittedException.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriberIdCreationNotPermittedException.java @@ -3,9 +3,9 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; -public class SubscriberIdCreationNotPermittedException extends SubscriptionException { +public class SubscriberIdCreationNotPermittedException extends PurchaseException { public SubscriberIdCreationNotPermittedException() { super(null); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionCurrencyUtil.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionCurrencyUtil.java similarity index 98% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionCurrencyUtil.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionCurrencyUtil.java index b4f94edff..15df6ef39 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionCurrencyUtil.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionCurrencyUtil.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import com.google.api.services.androidpublisher.model.Money; import java.math.BigDecimal; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInformation.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionInformation.java similarity index 90% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInformation.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionInformation.java index ecd200e01..f9f0a58eb 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInformation.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionInformation.java @@ -2,7 +2,7 @@ * Copyright 2024 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import java.time.Instant; import javax.annotation.Nullable; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPaymentProcessor.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionPaymentProcessor.java similarity index 69% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPaymentProcessor.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionPaymentProcessor.java index 452cfd202..32e269fbc 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPaymentProcessor.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionPaymentProcessor.java @@ -2,7 +2,7 @@ * Copyright 2022 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; import org.whispersystems.textsecuregcm.storage.PaymentTime; @@ -27,15 +27,15 @@ public interface SubscriptionPaymentProcessor { * @param subscriptionId A subscriptionId that potentially corresponds to a valid subscription * @return A {@link ReceiptItem} if the subscription is valid * @throws RateLimitExceededException If rate-limited - * @throws SubscriptionNotFoundException If the provided subscriptionId could not be found with + * @throws PurchaseNotFoundException If the provided subscriptionId could not be found with * the provider - * @throws SubscriptionPaymentRequiredException If the subscription is in a state does not grant the + * @throws PurchasePaymentRequiredException If the subscription is in a state does not grant the * user an entitlement - * @throws SubscriptionReceiptRequestedForOpenPaymentException If a receipt was requested while a payment transaction + * @throws PurchaseReceiptRequestedForOpenPaymentException If a receipt was requested while a payment transaction * was still open */ ReceiptItem getReceiptItem(String subscriptionId) - throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionChargeFailurePaymentRequiredException, SubscriptionPaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException; + throws RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException, PurchaseReceiptRequestedForOpenPaymentException; /** * Cancel all active subscriptions for this key within the payment processor. @@ -43,10 +43,10 @@ public interface SubscriptionPaymentProcessor { * @param key An identifier for the subscriber within the payment provider, corresponds to the customerId field in the * subscriptions table * @throws RateLimitExceededException If rate-limited - * @throws SubscriptionInvalidArgumentsException If a precondition for cancellation was not met + * @throws PurchaseInvalidArgumentsException If a precondition for cancellation was not met */ void cancelAllActiveSubscriptions(String key) - throws SubscriptionInvalidArgumentsException, RateLimitExceededException; + throws PurchaseInvalidArgumentsException, RateLimitExceededException; /** * Retrieve subscription information from the processor @@ -54,8 +54,8 @@ public interface SubscriptionPaymentProcessor { * @param subscriptionId The identifier with the processor to retrieve information for * @return {@link SubscriptionInformation} from the provider * @throws RateLimitExceededException If rate-limited - * @throws SubscriptionNotFoundException If the provided key was not found with the provider + * @throws PurchaseNotFoundException If the provided key was not found with the provider */ SubscriptionInformation getSubscriptionInformation(final String subscriptionId) - throws RateLimitExceededException, SubscriptionNotFoundException; + throws RateLimitExceededException, PurchaseNotFoundException; } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPrice.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionPrice.java similarity index 84% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPrice.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionPrice.java index 44f75dca3..d1cf7f41f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPrice.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionPrice.java @@ -2,7 +2,7 @@ * Copyright 2024 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; /// @param currency The upper-case 3-character currency specifier of the price /// @param amount The amount in the currency's minor unit (as defined by stripe) diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionStatus.java b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionStatus.java similarity index 97% rename from service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionStatus.java rename to service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionStatus.java index 4fcca22e0..e6361ba10 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionStatus.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/purchases/SubscriptionStatus.java @@ -2,7 +2,7 @@ * Copyright 2024 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManager.java index 546c47f39..922bc3b76 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManager.java @@ -24,7 +24,7 @@ import javax.annotation.Nonnull; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/OneTimeDonationsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/OneTimeDonationsManager.java index 70142ada3..04f51a271 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/OneTimeDonationsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/OneTimeDonationsManager.java @@ -14,7 +14,7 @@ import java.util.Map; import java.util.Objects; import javax.annotation.Nonnull; import io.micrometer.core.instrument.Tags; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; import org.whispersystems.textsecuregcm.util.AttributeValues; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriberCredentials.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriberCredentials.java index 8f0a683c9..af386db26 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriberCredentials.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriberCredentials.java @@ -15,9 +15,9 @@ import javax.annotation.Nonnull; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException; +import org.whispersystems.textsecuregcm.purchases.PurchaseException; +import org.whispersystems.textsecuregcm.purchases.PurchaseForbiddenException; +import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; public record SubscriberCredentials(@Nonnull byte[] subscriberBytes, @Nonnull byte[] subscriberUser, @@ -28,9 +28,9 @@ public record SubscriberCredentials(@Nonnull byte[] subscriberBytes, public static SubscriberCredentials process( final Optional authenticatedAccount, final String subscriberId, - final Clock clock) throws SubscriptionException { + final Clock clock) throws PurchaseException { if (authenticatedAccount.isPresent()) { - throw new SubscriptionForbiddenException("must not use authenticated connection for subscriber operations"); + throw new PurchaseForbiddenException("must not use authenticated connection for subscriber operations"); } final byte[] subscriberBytes = convertSubscriberIdStringToBytes(subscriberId); return process(subscriberBytes, clock); @@ -46,15 +46,15 @@ public record SubscriberCredentials(@Nonnull byte[] subscriberBytes, return new SubscriberCredentials(subscriberBytes, subscriberUser, subscriberKey, hmac, now); } - private static byte[] convertSubscriberIdStringToBytes(String subscriberId) throws SubscriptionNotFoundException { + private static byte[] convertSubscriberIdStringToBytes(String subscriberId) throws PurchaseNotFoundException { try { byte[] bytes = Base64.getUrlDecoder().decode(subscriberId); if (bytes.length != 32) { - throw new SubscriptionNotFoundException(); + throw new PurchaseNotFoundException(); } return bytes; } catch (IllegalArgumentException e) { - throw new SubscriptionNotFoundException(e); + throw new PurchaseNotFoundException(e); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriptionManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriptionManager.java index 29007895a..a17fcc022 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriptionManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriptionManager.java @@ -27,26 +27,26 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; import org.whispersystems.textsecuregcm.metrics.MetricsUtil; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; -import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager; -import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; -import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; -import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException; +import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager; +import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.ProcessorCustomer; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.SubscriberIdCreationNotPermittedException; +import org.whispersystems.textsecuregcm.purchases.PurchaseForbiddenException; +import org.whispersystems.textsecuregcm.purchases.SubscriptionInformation; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidIdempotencyKeyException; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidLevelException; +import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; +import org.whispersystems.textsecuregcm.purchases.SubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiresActionException; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorConflictException; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException; import org.whispersystems.textsecuregcm.util.ThrowingBiFunction; import org.whispersystems.textsecuregcm.util.ua.ClientPlatform; @@ -85,17 +85,17 @@ public class SubscriptionManager { * * @param subscriberCredentials Subscriber credentials derived from the subscriberId * @throws RateLimitExceededException if rate-limited - * @throws SubscriptionNotFoundException if the provided credentials are incorrect or the subscriber does not + * @throws PurchaseNotFoundException if the provided credentials are incorrect or the subscriber does not * exist - * @throws SubscriptionInvalidArgumentsException if a precondition for cancellation was not met + * @throws PurchaseInvalidArgumentsException if a precondition for cancellation was not met */ public void deleteSubscriber(final SubscriberCredentials subscriberCredentials) - throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException { + throws PurchaseNotFoundException, PurchaseInvalidArgumentsException, RateLimitExceededException { final Subscriptions.GetResult getResult = subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()); if (getResult == Subscriptions.GetResult.NOT_STORED || getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) { - throw new SubscriptionNotFoundException(); + throw new PurchaseNotFoundException(); } // a missing customer ID is OK; it means the subscriber never started to add a payment method, so we can skip cancelling @@ -114,16 +114,16 @@ public class SubscriptionManager { * * @param subscriberCredentials Subscriber credentials derived from the subscriberId * @param createPermitted Whether creating a new subscriber is permitted if one does not exist - * @throws SubscriptionForbiddenException if the subscriber credentials were incorrect + * @throws PurchaseForbiddenException if the subscriber credentials were incorrect * @throws SubscriberIdCreationNotPermittedException if a new subscriber ID would be created, but the caller does not permit it */ public void updateSubscriber(final SubscriberCredentials subscriberCredentials, final boolean createPermitted) - throws SubscriptionForbiddenException, SubscriberIdCreationNotPermittedException { + throws PurchaseForbiddenException, SubscriberIdCreationNotPermittedException { final Subscriptions.GetResult getResult = subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()); if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) { - throw new SubscriptionForbiddenException("subscriberId mismatch"); + throw new PurchaseForbiddenException("subscriberId mismatch"); } else if (getResult == Subscriptions.GetResult.NOT_STORED) { if (!createPermitted) { @@ -135,7 +135,7 @@ public class SubscriptionManager { subscriberCredentials.hmac(), subscriberCredentials.now()); if (updatedRecord == null) { - throw new SubscriptionForbiddenException("subscriberId mismatch"); + throw new PurchaseForbiddenException("subscriberId mismatch"); } } else { // already exists so just touch access time and return @@ -145,7 +145,7 @@ public class SubscriptionManager { public Optional getSubscriptionInformation( final SubscriberCredentials subscriberCredentials) - throws SubscriptionForbiddenException, SubscriptionNotFoundException, RateLimitExceededException { + throws PurchaseForbiddenException, PurchaseNotFoundException, RateLimitExceededException { final Subscriptions.Record record = getSubscriber(subscriberCredentials); if (record.subscriptionId == null) { return Optional.empty(); @@ -158,17 +158,17 @@ public class SubscriptionManager { * Get the subscriber record * * @param subscriberCredentials Subscriber credentials derived from the subscriberId - * @throws SubscriptionForbiddenException if the subscriber credentials were incorrect - * @throws SubscriptionNotFoundException if the subscriber did not exist + * @throws PurchaseForbiddenException if the subscriber credentials were incorrect + * @throws PurchaseNotFoundException if the subscriber did not exist */ public Subscriptions.Record getSubscriber(final SubscriberCredentials subscriberCredentials) - throws SubscriptionForbiddenException, SubscriptionNotFoundException { + throws PurchaseForbiddenException, PurchaseNotFoundException { final Subscriptions.GetResult getResult = subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()); if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) { - throw new SubscriptionForbiddenException("subscriberId mismatch"); + throw new PurchaseForbiddenException("subscriberId mismatch"); } else if (getResult == Subscriptions.GetResult.NOT_STORED) { - throw new SubscriptionNotFoundException(); + throw new PurchaseNotFoundException(); } else { return getResult.record; } @@ -189,15 +189,15 @@ public class SubscriptionManager { * expiration time of the receipt * @param userAgent The requesting client's user agent * @return the requested ZK receipt credential - * @throws SubscriptionForbiddenException if the subscriber credentials were incorrect - * @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a + * @throws PurchaseForbiddenException if the subscriber credentials were incorrect + * @throws PurchaseNotFoundException if the subscriber did not exist or did not have a * subscription attached - * @throws SubscriptionInvalidArgumentsException if the receipt credential request failed verification - * @throws SubscriptionPaymentRequiredException if the subscription is in a state does not grant the + * @throws PurchaseInvalidArgumentsException if the receipt credential request failed verification + * @throws PurchasePaymentRequiredException if the subscription is in a state does not grant the * user an entitlement - * @throws SubscriptionReceiptRequestedForOpenPaymentException if a receipt was requested while a payment transaction + * @throws PurchaseReceiptRequestedForOpenPaymentException if a receipt was requested while a payment transaction * was still open - * @throws SubscriptionReceiptAlreadyRedeemedException if the receipt was already redeemed by a different + * @throws PurchaseReceiptAlreadyRedeemedException if the receipt was already redeemed by a different * request * @throws RateLimitExceededException if rate-limited */ @@ -206,17 +206,17 @@ public class SubscriptionManager { final byte[] receiptCredentialRequestBytes, final Function expiration, @Nullable final String userAgent) - throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException, SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionReceiptAlreadyRedeemedException { + throws PurchaseForbiddenException, PurchaseNotFoundException, PurchaseInvalidArgumentsException, PurchasePaymentRequiredException, RateLimitExceededException, PurchaseReceiptRequestedForOpenPaymentException, PurchaseReceiptAlreadyRedeemedException { final Subscriptions.Record record = getSubscriber(subscriberCredentials); if (record.subscriptionId == null) { - throw new SubscriptionNotFoundException(); + throw new PurchaseNotFoundException(); } final ReceiptCredentialRequest receiptCredentialRequest; try { receiptCredentialRequest = new ReceiptCredentialRequest(receiptCredentialRequestBytes); } catch (final InvalidInputException e) { - throw new SubscriptionInvalidArgumentsException("invalid receipt credential request", e); + throw new PurchaseInvalidArgumentsException("invalid receipt credential request", e); } final PaymentProvider processor = record.getProcessorCustomer().orElseThrow().processor(); @@ -232,7 +232,7 @@ public class SubscriptionManager { expirationInstant.getEpochSecond(), receipt.level()); } catch (final VerificationFailedException e) { - throw new SubscriptionInvalidArgumentsException("receipt credential request failed verification", e); + throw new PurchaseInvalidArgumentsException("receipt credential request failed verification", e); } catch (final WriteConflictException _) { Metrics.counter(RECEIPT_ALREADY_REDEEMED_COUNTER_NAME, Tags.of( Tag.of("receiptLevel", ReceiptLevel.lookupLevel(receipt.level()) @@ -240,7 +240,7 @@ public class SubscriptionManager { .orElse("n/a")), UserAgentTagUtil.getPlatformTag(userAgent))) .increment(); - throw new SubscriptionReceiptAlreadyRedeemedException(); + throw new PurchaseReceiptAlreadyRedeemedException(); } return new ReceiptResult(receiptCredentialResponse, receipt, processor); } @@ -265,9 +265,9 @@ public class SubscriptionManager { * to configure the newly created payment method * @param An exception thrown by the paymentSetupFunction * @return The return value of the paymentSetupFunction - * @throws SubscriptionForbiddenException if the subscriber credentials were incorrect - * @throws SubscriptionNotFoundException if the subscriber did not exist - * @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with + * @throws PurchaseForbiddenException if the subscriber credentials were incorrect + * @throws PurchaseNotFoundException if the subscriber did not exist + * @throws PurchaseProcessorConflictException if the new payment processor does not match the existing processor associated with * the subscriberId */ public R addPaymentMethodToCustomer( @@ -275,7 +275,7 @@ public class SubscriptionManager { final T subscriptionPaymentProcessor, final ClientPlatform clientPlatform, final ThrowingBiFunction paymentSetupFunction) - throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException, E { + throws PurchaseForbiddenException, PurchaseNotFoundException, PurchaseProcessorConflictException, E { Subscriptions.Record record = this.getSubscriber(subscriberCredentials); if (record.getProcessorCustomer().isEmpty()) { @@ -289,7 +289,7 @@ public class SubscriptionManager { .orElseThrow(() -> new UncheckedIOException(new IOException("processor must now exist"))); if (processorCustomer.processor() != subscriptionPaymentProcessor.getProvider()) { - throw new SubscriptionProcessorConflictException("existing processor does not match"); + throw new PurchaseProcessorConflictException("existing processor does not match"); } return paymentSetupFunction.apply(subscriptionPaymentProcessor, processorCustomer.customerId()); } @@ -324,13 +324,13 @@ public class SubscriptionManager { * @param subscriptionTemplateId Specifies the product associated with the provided level within the payment * processor * @param transitionValidator A function that checks if the level update is valid - * @throws SubscriptionInvalidArgumentsException if the transitionValidator failed for the level transition, or the + * @throws PurchaseInvalidArgumentsException if the transitionValidator failed for the level transition, or the * subscription could not be created because the payment provider * requires additional action, or there was a failure because an * idempotency key was reused on a * modified request - * @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with + * @throws PurchaseProcessorConflictException if the new payment processor the existing processor associated with * the subscriber - * @throws SubscriptionProcessorException if there was no payment method on the customer + * @throws PurchaseProcessorException if there was no payment method on the customer */ public void updateSubscriptionLevelForCustomer( final SubscriberCredentials subscriberCredentials, @@ -341,7 +341,7 @@ public class SubscriptionManager { final String idempotencyKey, final String subscriptionTemplateId, final LevelTransitionValidator transitionValidator) - throws SubscriptionInvalidLevelException, SubscriptionInvalidIdempotencyKeyException, SubscriptionPaymentRequiresActionException, SubscriptionProcessorConflictException, SubscriptionProcessorException { + throws PurchaseInvalidLevelException, PurchaseInvalidIdempotencyKeyException, PurchasePaymentRequiresActionException, PurchaseProcessorConflictException, PurchaseProcessorException { if (record.subscriptionId != null) { // we already have a subscription in our records so let's check the level and currency, @@ -355,7 +355,7 @@ public class SubscriptionManager { return; } if (!transitionValidator.isTransitionValid(existingLevelAndCurrency.level(), level)) { - throw new SubscriptionInvalidLevelException(); + throw new PurchaseInvalidLevelException(); } final CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updatedSubscriptionId = processor.updateSubscription(subscription, subscriptionTemplateId, level, idempotencyKey); @@ -389,12 +389,12 @@ public class SubscriptionManager { * @param purchaseToken The client provided purchaseToken that represents a purchased subscription in the * play store * @return the subscription level for the accepted subscription - * @throws SubscriptionForbiddenException if the subscriber credentials were incorrect - * @throws SubscriptionNotFoundException if the subscriber did not exist, or the purchaseToken was not found + * @throws PurchaseForbiddenException if the subscriber credentials were incorrect + * @throws PurchaseNotFoundException if the subscriber did not exist, or the purchaseToken was not found * in the play store - * @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with + * @throws PurchaseProcessorConflictException if the new payment processor does not match the existing processor associated with * the subscriberId - * @throws SubscriptionPaymentRequiredException if the subscription is not in a state that grants the user an + * @throws PurchasePaymentRequiredException if the subscription is not in a state that grants the user an * entitlement * @throws RateLimitExceededException if rate-limited */ @@ -402,7 +402,7 @@ public class SubscriptionManager { final SubscriberCredentials subscriberCredentials, final GooglePlayBillingManager googlePlayBillingManager, final String purchaseToken) - throws SubscriptionProcessorConflictException, SubscriptionForbiddenException, SubscriptionNotFoundException, RateLimitExceededException, SubscriptionPaymentRequiredException { + throws PurchaseProcessorConflictException, PurchaseForbiddenException, PurchaseNotFoundException, RateLimitExceededException, PurchasePaymentRequiredException { // For IAP providers, the subscriptionId and the customerId are both just the purchaseToken. Changes to the // subscription always just result in a new purchaseToken @@ -413,7 +413,7 @@ public class SubscriptionManager { // Check the record for an existing subscription if (record.processorCustomer != null && record.processorCustomer.processor() != PaymentProvider.GOOGLE_PLAY_BILLING) { - throw new SubscriptionProcessorConflictException("existing processor does not match"); + throw new PurchaseProcessorConflictException("existing processor does not match"); } // If we're replacing an existing purchaseToken, cancel it first @@ -442,14 +442,14 @@ public class SubscriptionManager { * @param originalTransactionId The client provided originalTransactionId that represents a purchased subscription in * the app store * @return the subscription level for the accepted subscription - * @throws SubscriptionForbiddenException if the subscriber credentials are incorrect - * @throws SubscriptionNotFoundException if the subscriber did not exist, or the originalTransactionId does + * @throws PurchaseForbiddenException if the subscriber credentials are incorrect + * @throws PurchaseNotFoundException if the subscriber did not exist, or the originalTransactionId does * not exist - * @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with + * @throws PurchaseProcessorConflictException if the new payment processor does not match the existing processor associated with * the subscriber - * @throws SubscriptionInvalidArgumentsException if the originalTransactionId is malformed or does not represent a + * @throws PurchaseInvalidArgumentsException if the originalTransactionId is malformed or does not represent a * valid subscription - * @throws SubscriptionPaymentRequiredException if the subscription is not in a state that grants the user an + * @throws PurchasePaymentRequiredException if the subscription is not in a state that grants the user an * entitlement * @throws RateLimitExceededException if rate-limited */ @@ -457,12 +457,12 @@ public class SubscriptionManager { final SubscriberCredentials subscriberCredentials, final AppleAppStoreManager appleAppStoreManager, final String originalTransactionId) - throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException, SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException { + throws PurchaseForbiddenException, PurchaseNotFoundException, PurchaseProcessorConflictException, PurchaseInvalidArgumentsException, PurchasePaymentRequiredException, RateLimitExceededException { final Subscriptions.Record record = getSubscriber(subscriberCredentials); if (record.processorCustomer != null && record.processorCustomer.processor() != PaymentProvider.APPLE_APP_STORE) { - throw new SubscriptionProcessorConflictException("existing processor does not match"); + throw new PurchaseProcessorConflictException("existing processor does not match"); } // For IAP providers, the subscriptionId and the customerId are both just the identifier for the subscription in diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Subscriptions.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Subscriptions.java index 1446d3f3b..3721fd990 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Subscriptions.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Subscriptions.java @@ -22,8 +22,8 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.ProcessorCustomer; import org.whispersystems.textsecuregcm.util.Pair; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/OneTimePaymentProcessor.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/OneTimePaymentProcessor.java deleted file mode 100644 index e62d21a5e..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/OneTimePaymentProcessor.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright 2026 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ -package org.whispersystems.textsecuregcm.subscriptions; - -import java.io.IOException; -import java.util.Optional; -import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; - -public interface OneTimePaymentProcessor { - - /// Retrieve information about a one-time purchase. - /// - /// @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 claimOneTimePurchase(final String paymentIdentifier) throws IOException, RateLimitExceededException, SubscriptionInvalidArgumentsException; -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentDetails.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentDetails.java deleted file mode 100644 index 06c8e0e51..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentDetails.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ -package org.whispersystems.textsecuregcm.subscriptions; - -import java.time.Instant; -import javax.annotation.Nullable; - -/** - * Payment details for a one-time payment specified by id - * - * @param id The id of the payment in the payment processor - * @param level The level identifier of purchase - * @param status The status of the payment in the payment processor - * @param created When the payment was created - * @param chargeFailure If present, additional information about why the payment failed. Will not be set if the status - * is not {@link PaymentStatus#SUCCEEDED} - */ -public record PaymentDetails(String id, - ReceiptLevel level, - PaymentStatus status, - @Nullable Instant created, - @Nullable ChargeFailure chargeFailure) {} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionChargeFailurePaymentRequiredException.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionChargeFailurePaymentRequiredException.java deleted file mode 100644 index e310e7007..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionChargeFailurePaymentRequiredException.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2025 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ -package org.whispersystems.textsecuregcm.subscriptions; - -public class SubscriptionChargeFailurePaymentRequiredException extends SubscriptionPaymentRequiredException { - - private final PaymentProvider processor; - private final ChargeFailure chargeFailure; - - public SubscriptionChargeFailurePaymentRequiredException(final PaymentProvider processor, - final ChargeFailure chargeFailure) { - super(); - this.processor = processor; - this.chargeFailure = chargeFailure; - } - - public PaymentProvider getProcessor() { - return processor; - } - - public ChargeFailure getChargeFailure() { - return chargeFailure; - } - -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionForbiddenException.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionForbiddenException.java deleted file mode 100644 index 1a044b9d5..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionForbiddenException.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright 2025 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ -package org.whispersystems.textsecuregcm.subscriptions; - -public class SubscriptionForbiddenException extends SubscriptionException { - - public SubscriptionForbiddenException(final String message) { - super(null, message); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidArgumentsException.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidArgumentsException.java deleted file mode 100644 index 96007b652..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidArgumentsException.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright 2025 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ -package org.whispersystems.textsecuregcm.subscriptions; - -public class SubscriptionInvalidArgumentsException extends SubscriptionException { - - public SubscriptionInvalidArgumentsException(final String message, final Exception cause) { - super(cause, message); - } - - public SubscriptionInvalidArgumentsException(final String message) { - this(message, null); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidIdempotencyKeyException.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidIdempotencyKeyException.java deleted file mode 100644 index 45ded4d65..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidIdempotencyKeyException.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright 2026 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ -package org.whispersystems.textsecuregcm.subscriptions; - -public class SubscriptionInvalidIdempotencyKeyException extends SubscriptionInvalidArgumentsException { - - public SubscriptionInvalidIdempotencyKeyException(final String message) { - super(message); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidLevelException.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidLevelException.java deleted file mode 100644 index d613a63df..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidLevelException.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright 2025 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ -package org.whispersystems.textsecuregcm.subscriptions; - -public class SubscriptionInvalidLevelException extends SubscriptionInvalidArgumentsException { - - public SubscriptionInvalidLevelException() { - super(null, null); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionNotFoundException.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionNotFoundException.java deleted file mode 100644 index 2640eac8f..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionNotFoundException.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright 2025 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ -package org.whispersystems.textsecuregcm.subscriptions; - -public class SubscriptionNotFoundException extends SubscriptionException { - - public SubscriptionNotFoundException() { - super(null); - } - - public SubscriptionNotFoundException(Exception cause) { - super(cause); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPaymentRequiredException.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPaymentRequiredException.java deleted file mode 100644 index 8691b51f8..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPaymentRequiredException.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright 2025 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ -package org.whispersystems.textsecuregcm.subscriptions; - -public class SubscriptionPaymentRequiredException extends SubscriptionException { - - public SubscriptionPaymentRequiredException() { - super(null, null); - } - - public SubscriptionPaymentRequiredException(String message) { - super(null, message); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPaymentRequiresActionException.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPaymentRequiresActionException.java deleted file mode 100644 index ca74ea339..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionPaymentRequiresActionException.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright 2025 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ -package org.whispersystems.textsecuregcm.subscriptions; - -public class SubscriptionPaymentRequiresActionException extends SubscriptionInvalidArgumentsException { - - public SubscriptionPaymentRequiresActionException(String message) { - super(message, null); - } - - public SubscriptionPaymentRequiresActionException() { - super(null, null); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionProcessorConflictException.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionProcessorConflictException.java deleted file mode 100644 index d33aa665b..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionProcessorConflictException.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright 2025 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ -package org.whispersystems.textsecuregcm.subscriptions; - -public class SubscriptionProcessorConflictException extends SubscriptionException { - - public SubscriptionProcessorConflictException() { - super(null, null); - } - - public SubscriptionProcessorConflictException(final String message) { - super(null, message); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionReceiptAlreadyRedeemedException.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionReceiptAlreadyRedeemedException.java deleted file mode 100644 index 842868ae4..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionReceiptAlreadyRedeemedException.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright 2026 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ -package org.whispersystems.textsecuregcm.subscriptions; - -public class SubscriptionReceiptAlreadyRedeemedException extends SubscriptionException { - - public SubscriptionReceiptAlreadyRedeemedException() { - super(null, null); - } - - public SubscriptionReceiptAlreadyRedeemedException(final String message) { - super(null, message); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearIssuedReceiptRedemptionsCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearIssuedReceiptRedemptionsCommand.java index 69be013b6..e4fb7dda6 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearIssuedReceiptRedemptionsCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearIssuedReceiptRedemptionsCommand.java @@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.workers; import io.dropwizard.core.Application; import io.dropwizard.core.setup.Environment; import java.time.Clock; -import java.util.Base64; import java.util.Optional; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser; @@ -19,8 +18,8 @@ import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager; import org.whispersystems.textsecuregcm.storage.SubscriberCredentials; import org.whispersystems.textsecuregcm.storage.SubscriptionManager; import org.whispersystems.textsecuregcm.storage.Subscriptions; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.SubscriptionPaymentProcessor; public class ClearIssuedReceiptRedemptionsCommand extends AbstractCommandWithDependencies { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java index 95bec7b9c..67840dad9 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java @@ -89,9 +89,9 @@ import org.whispersystems.textsecuregcm.storage.TotpManager; import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase; import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore; import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher; -import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient; -import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager; -import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager; +import org.whispersystems.textsecuregcm.purchases.AppleAppStoreClient; +import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager; +import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager; import org.whispersystems.textsecuregcm.util.ManagedAwsCrt; import org.whispersystems.textsecuregcm.util.ManagedExecutors; import org.whispersystems.textsecuregcm.util.ResilienceUtil; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AbstractV1SubscriptionControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AbstractV1SubscriptionControllerTest.java index 52a164d58..543718010 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AbstractV1SubscriptionControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AbstractV1SubscriptionControllerTest.java @@ -26,9 +26,9 @@ import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfigurati import org.whispersystems.textsecuregcm.storage.DonationPermits; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager; -import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.StripeManager; +import org.whispersystems.textsecuregcm.purchases.BraintreeManager; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.StripeManager; import org.whispersystems.textsecuregcm.tests.util.SubscriptionConfigTestHelper; import org.whispersystems.textsecuregcm.util.MockUtils; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DonationControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DonationControllerTest.java index b7962d0f5..594327a41 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DonationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DonationControllerTest.java @@ -54,8 +54,8 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.DonationPermits; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.ReceiptCredentialPresentationFactory; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; import org.whispersystems.textsecuregcm.tests.util.AccountsHelper; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.util.TestClock; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/LoginPurchaseControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/LoginPurchaseControllerTest.java index 453532fe5..cd00ce46b 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/LoginPurchaseControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/LoginPurchaseControllerTest.java @@ -42,17 +42,16 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicLoginPurchaseConfiguration; import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper; import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper; -import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper; +import org.whispersystems.textsecuregcm.mappers.PurchaseExceptionMapper; import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; -import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; -import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException; +import org.whispersystems.textsecuregcm.purchases.ChargeFailure; +import org.whispersystems.textsecuregcm.purchases.LoginPurchaseManager; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException; +import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.util.SystemMapper; import org.whispersystems.textsecuregcm.util.TestRandomUtil; @@ -83,7 +82,7 @@ class LoginPurchaseControllerTest { .addProvider(AuthHelper.getAuthFilter()) .addProvider(CompletionExceptionMapper.class) .addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class)) - .addProvider(SubscriptionExceptionMapper.class) + .addProvider(PurchaseExceptionMapper.class) .addProvider(RateLimitExceededExceptionMapper.class) .setMapper(SystemMapper.jsonMapper()) .setTestContainerFactory(new GrizzlyWebTestContainerFactory()) @@ -163,11 +162,11 @@ class LoginPurchaseControllerTest { static Stream createReceiptCredentialErrors() { return Stream.of( - Arguments.of(new SubscriptionReceiptRequestedForOpenPaymentException(), 204), - Arguments.of(new SubscriptionPaymentRequiredException(), 402), - Arguments.of(new SubscriptionNotFoundException(), 404), - Arguments.of(new SubscriptionInvalidArgumentsException("test"), 400), - Arguments.of(new SubscriptionReceiptAlreadyRedeemedException(), 409), + Arguments.of(new PurchaseReceiptRequestedForOpenPaymentException(), 204), + Arguments.of(new PurchasePaymentRequiredException(PaymentProvider.APPLE_APP_STORE), 402), + Arguments.of(new PurchaseNotFoundException(), 404), + Arguments.of(new PurchaseInvalidArgumentsException("test"), 400), + Arguments.of(new PurchaseReceiptAlreadyRedeemedException(), 409), Arguments.of(new VerificationFailedException(), 400), Arguments.of(new RateLimitExceededException(null), 429)); } @@ -193,7 +192,7 @@ class LoginPurchaseControllerTest { final ChargeFailure chargeFailure = new ChargeFailure("generic_decline", "some failure message", null, null, null); when(LOGIN_PURCHASE_MANAGER.generateReceipt(any(), any(), any())) - .thenThrow(new SubscriptionChargeFailurePaymentRequiredException(PaymentProvider.APPLE_APP_STORE, chargeFailure)); + .thenThrow(new PurchasePaymentRequiredException(PaymentProvider.APPLE_APP_STORE, chargeFailure)); try (final Response response = RESOURCE_EXTENSION.target("/v1/login-purchase/receipt_credentials") .request() @@ -201,8 +200,8 @@ class LoginPurchaseControllerTest { PURCHASE_ID, receiptCredentialRequestContext.getRequest().serialize(), PaymentProvider.APPLE_APP_STORE)))) { - final SubscriptionExceptionMapper.ChargeFailureResponse failureResponse = - response.readEntity(SubscriptionExceptionMapper.ChargeFailureResponse.class); + final PurchaseExceptionMapper.ChargeFailureResponse failureResponse = + response.readEntity(PurchaseExceptionMapper.ChargeFailureResponse.class); assertThat(failureResponse.chargeFailure()).isEqualTo(chargeFailure); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java index 1dd78ec39..6b400b48c 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java @@ -25,7 +25,6 @@ import java.time.Instant; import java.util.Base64; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import org.assertj.core.api.InstanceOfAssertFactories; @@ -44,19 +43,20 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest; import org.signal.libsignal.zkgroup.receipts.ReceiptSerial; import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice; import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper; -import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper; +import org.whispersystems.textsecuregcm.mappers.PurchaseExceptionMapper; +import org.whispersystems.textsecuregcm.purchases.BraintreeManager; +import org.whispersystems.textsecuregcm.purchases.ChargeFailure; +import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator; +import org.whispersystems.textsecuregcm.purchases.PaymentDetails; +import org.whispersystems.textsecuregcm.purchases.PaymentMethod; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.PurchaseException; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager; import org.whispersystems.textsecuregcm.storage.WriteConflictException; -import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; -import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; -import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator; -import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails; -import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.util.HeaderUtils; import org.whispersystems.textsecuregcm.util.SystemMapper; @@ -78,7 +78,7 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest .addProvider(AuthHelper.getAuthFilter()) .addProvider(CompletionExceptionMapper.class) .addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class)) - .addProvider(SubscriptionExceptionMapper.class) + .addProvider(PurchaseExceptionMapper.class) .setMapper(SystemMapper.jsonMapper()) .setTestContainerFactory(new GrizzlyWebTestContainerFactory()) .addResource(ONE_TIME_CONTROLLER) @@ -180,7 +180,7 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest @ParameterizedTest @ValueSource(booleans = {true, false}) - void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) throws SubscriptionInvalidAmountException { + void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) throws PurchaseInvalidAmountException { when(DONATION_PERMITS.spend(any(byte[].class), any(Instant.class))).thenReturn(donationPermitSpendOk); when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.CARD)) @@ -256,14 +256,10 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest @ParameterizedTest @MethodSource void createBoostReceiptPaymentRequired(final ChargeFailure chargeFailure, boolean expectChargeFailure) - throws IOException { - when(STRIPE_MANAGER.claimOneTimePurchase(any())).thenReturn(Optional.of(new PaymentDetails( - "id", - null, - PaymentStatus.FAILED, - Instant.now(), - chargeFailure)) - ); + throws IOException, PurchaseException { + when(STRIPE_MANAGER.claimOneTimePurchase(any())).thenThrow(chargeFailure == null + ? new PurchasePaymentRequiredException(PaymentProvider.STRIPE) + : new PurchasePaymentRequiredException(PaymentProvider.STRIPE, chargeFailure)); try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials") .request() .post(Entity.json(""" @@ -298,12 +294,12 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest } @Test - void confirmPaypalBoostProcessorError() throws SubscriptionProcessorException, IOException { + void confirmPaypalBoostProcessorError() throws PurchaseProcessorException, IOException { when(BRAINTREE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.PAYPAL)) .thenReturn(Set.of("usd", "jpy", "bif", "eur")); when(BRAINTREE_MANAGER.captureOneTimePayment(anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), any())) - .thenThrow(new SubscriptionProcessorException(PaymentProvider.BRAINTREE, + .thenThrow(new PurchaseProcessorException(PaymentProvider.BRAINTREE, new ChargeFailure("2046", "Declined", null, null, null))); try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/confirm") @@ -314,7 +310,7 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest "currency", "usd", "amount", 300)))) { - assertThat(response.getStatus()).isEqualTo(SubscriptionExceptionMapper.PROCESSOR_ERROR_STATUS_CODE); + assertThat(response.getStatus()).isEqualTo(PurchaseExceptionMapper.PROCESSOR_ERROR_STATUS_CODE); final Map responseMap = response.readEntity(Map.class); assertThat(responseMap.get("processor")).isEqualTo("BRAINTREE"); @@ -341,12 +337,8 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest(); when(ONE_TIME_DONATIONS_MANAGER.getPaidAt(any(), anyString(), any())).thenReturn(Instant.now()); - when(STRIPE_MANAGER.claimOneTimePurchase(any())).thenReturn(Optional.of(new PaymentDetails( - "id", - ReceiptLevel.ONE_TIME_DONATION, - PaymentStatus.SUCCEEDED, - Instant.now(), - null))); + when(STRIPE_MANAGER.claimOneTimePurchase(any())) + .thenReturn(new PaymentDetails("id", ReceiptLevel.ONE_TIME_DONATION, Instant.now())); doThrow(WriteConflictException.class).when(ISSUED_RECEIPTS_MANAGER).recordOneTimeIssuance(any(), any(), any(), any()); try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials") diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java index 35cee390a..6a7813ec3 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java @@ -110,7 +110,7 @@ import org.whispersystems.textsecuregcm.storage.DeviceCapability; import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; import org.whispersystems.textsecuregcm.storage.ProfilesManager; import org.whispersystems.textsecuregcm.storage.VersionedProfileV1; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; import org.whispersystems.textsecuregcm.tests.util.AccountsHelper; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java index faa218161..78cdc1e48 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java @@ -117,7 +117,7 @@ import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; import org.whispersystems.textsecuregcm.storage.ReceiptAlreadyRedeemedException; import org.whispersystems.textsecuregcm.storage.ReceiptCredentialTestUtil; import org.whispersystems.textsecuregcm.storage.TotpKey; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.tests.util.KeysHelper; import org.whispersystems.textsecuregcm.util.MockUtils; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java index 32857a198..45edf57a4 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java @@ -67,30 +67,29 @@ import org.whispersystems.textsecuregcm.controllers.SubscriptionController.GetSu import org.whispersystems.textsecuregcm.entities.Badge; import org.whispersystems.textsecuregcm.entities.BadgeSvg; import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper; -import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper; +import org.whispersystems.textsecuregcm.mappers.PurchaseExceptionMapper; import org.whispersystems.textsecuregcm.storage.PaymentTime; import org.whispersystems.textsecuregcm.storage.SubscriptionManager; import org.whispersystems.textsecuregcm.storage.Subscriptions; import org.whispersystems.textsecuregcm.storage.WriteConflictException; -import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager; -import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator; -import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; -import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; -import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager; -import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration; -import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException; +import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager; +import org.whispersystems.textsecuregcm.purchases.BankMandateTranslator; +import org.whispersystems.textsecuregcm.purchases.ChargeFailure; +import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager; +import org.whispersystems.textsecuregcm.purchases.LevelConfiguration; +import org.whispersystems.textsecuregcm.purchases.PaymentMethod; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.ProcessorCustomer; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.PurchaseException; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException; +import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiresActionException; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorConflictException; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.tests.util.SubscriptionConfigTestHelper; import org.whispersystems.textsecuregcm.util.HeaderUtils; @@ -123,7 +122,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { .addProvider(AuthHelper.getAuthFilter()) .addProvider(CompletionExceptionMapper.class) .addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class)) - .addProvider(SubscriptionExceptionMapper.class) + .addProvider(PurchaseExceptionMapper.class) .setMapper(SystemMapper.jsonMapper()) .setTestContainerFactory(new GrizzlyWebTestContainerFactory()) .addResource(SUBSCRIPTION_CONTROLLER) @@ -181,7 +180,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { } @Test - void createSubscriptionSuccess() throws SubscriptionException { + void createSubscriptionSuccess() throws PurchaseException { when(STRIPE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong())) .thenReturn(mock(CustomerAwareSubscriptionPaymentProcessor.SubscriptionId.class)); @@ -197,9 +196,9 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { } @Test - void createSubscriptionProcessorDeclined() throws SubscriptionException { + void createSubscriptionProcessorDeclined() throws PurchaseException { when(STRIPE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong())) - .thenThrow(new SubscriptionProcessorException(PaymentProvider.STRIPE, + .thenThrow(new PurchaseProcessorException(PaymentProvider.STRIPE, new ChargeFailure("card_declined", "Insufficient funds", null, null, null))); final String level = String.valueOf(levelId); @@ -210,7 +209,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { .request() .put(Entity.json(""))) { - assertThat(response.getStatus()).isEqualTo(SubscriptionExceptionMapper.PROCESSOR_ERROR_STATUS_CODE); + assertThat(response.getStatus()).isEqualTo(PurchaseExceptionMapper.PROCESSOR_ERROR_STATUS_CODE); responseMap = response.readEntity(Map.class); } @@ -278,9 +277,9 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { @Test void stripePaymentIntentRequiresAction() - throws SubscriptionInvalidArgumentsException, SubscriptionProcessorException { + throws PurchaseInvalidArgumentsException, PurchaseProcessorException { when(STRIPE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong())) - .thenThrow(new SubscriptionPaymentRequiresActionException()); + .thenThrow(new PurchasePaymentRequiresActionException()); final String level = String.valueOf(levelId); final String idempotencyKey = UUID.randomUUID().toString(); @@ -519,7 +518,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { "201, M4", }) void setSubscriptionLevel(long levelId, String expectedProcessorId) - throws SubscriptionProcessorConflictException, SubscriptionProcessorException { + throws PurchaseProcessorConflictException, PurchaseProcessorException { // set up record final byte[] subscriberUserAndKey = new byte[32]; Arrays.fill(subscriberUserAndKey, (byte) 1); @@ -564,7 +563,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { @MethodSource void setSubscriptionLevelExistingSubscription(final String existingCurrency, final long existingLevel, final String requestCurrency, final long requestLevel, final boolean expectUpdate) - throws SubscriptionProcessorConflictException, SubscriptionProcessorException { + throws PurchaseProcessorConflictException, PurchaseProcessorException { // set up record final byte[] subscriberUserAndKey = new byte[32]; @@ -682,7 +681,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { @Test public void setAppStoreTransactionId() - throws SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException, SubscriptionNotFoundException { + throws PurchaseInvalidArgumentsException, PurchasePaymentRequiredException, RateLimitExceededException, PurchaseNotFoundException { final String originalTxId = "aTxId"; final byte[] subscriberUserAndKey = new byte[32]; Arrays.fill(subscriberUserAndKey, (byte) 1); @@ -723,7 +722,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { @Test - public void setPlayPurchaseToken() throws RateLimitExceededException, SubscriptionException { + public void setPlayPurchaseToken() throws RateLimitExceededException, PurchaseException { final String purchaseToken = "aPurchaseToken"; final byte[] subscriberUserAndKey = new byte[32]; Arrays.fill(subscriberUserAndKey, (byte) 1); @@ -763,7 +762,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { } @Test - public void replacePlayPurchaseToken() throws RateLimitExceededException, SubscriptionException { + public void replacePlayPurchaseToken() throws RateLimitExceededException, PurchaseException { final String oldPurchaseToken = "oldPurchaseToken"; final String newPurchaseToken = "newPurchaseToken"; final byte[] subscriberUserAndKey = new byte[32]; @@ -809,7 +808,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { @Test void createReceiptChargeFailure() - throws InvalidInputException, VerificationFailedException, SubscriptionException { + throws InvalidInputException, VerificationFailedException, PurchaseException { final byte[] subscriberUserAndKey = new byte[32]; Arrays.fill(subscriberUserAndKey, (byte) 1); final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey); @@ -824,7 +823,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { b(new ProcessorCustomer("customer", PaymentProvider.STRIPE).toDynamoBytes()), Subscriptions.KEY_SUBSCRIPTION_ID, s("subscriptionId"))))); when(STRIPE_MANAGER.getReceiptItem(any())) - .thenThrow(new SubscriptionChargeFailurePaymentRequiredException( + .thenThrow(new PurchasePaymentRequiredException( PaymentProvider.STRIPE, new ChargeFailure("card_declined", "Insufficient funds", null, null, null))); @@ -849,7 +848,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { @Test void createReceiptCredentialAlreadyRedeemed() - throws InvalidInputException, VerificationFailedException, SubscriptionException, WriteConflictException { + throws InvalidInputException, VerificationFailedException, PurchaseException, WriteConflictException { final byte[] subscriberUserAndKey = new byte[32]; Arrays.fill(subscriberUserAndKey, (byte) 1); final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey); @@ -885,7 +884,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { @ParameterizedTest @CsvSource({"5, P45D", "201, P13D"}) public void createReceiptCredential(long level, Duration expectedExpirationWindow) - throws InvalidInputException, VerificationFailedException, SubscriptionChargeFailurePaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException { + throws InvalidInputException, VerificationFailedException, PurchasePaymentRequiredException, PurchaseReceiptRequestedForOpenPaymentException { final byte[] subscriberUserAndKey = new byte[32]; Arrays.fill(subscriberUserAndKey, (byte) 1); final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcServiceTest.java index 5efd83295..0349a6e87 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcServiceTest.java @@ -47,8 +47,8 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.DonationPermits; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.ReceiptCredentialPresentationFactory; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; import org.whispersystems.textsecuregcm.tests.util.AccountsHelper; import org.whispersystems.textsecuregcm.util.TestClock; import org.whispersystems.textsecuregcm.util.TestRandomUtil; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/LoginPurchaseGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/LoginPurchaseGrpcServiceTest.java index 17497ea89..6119a66e2 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/LoginPurchaseGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/LoginPurchaseGrpcServiceTest.java @@ -39,15 +39,14 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicLoginPurchaseConfiguration; import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; -import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; -import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException; +import org.whispersystems.textsecuregcm.purchases.ChargeFailure; +import org.whispersystems.textsecuregcm.purchases.LoginPurchaseManager; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException; +import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException; import org.whispersystems.textsecuregcm.util.TestRandomUtil; class LoginPurchaseGrpcServiceTest extends @@ -126,13 +125,13 @@ class LoginPurchaseGrpcServiceTest extends static Stream createReceiptCredentialErrorResponses() { return Stream.of( - Arguments.of( new SubscriptionReceiptRequestedForOpenPaymentException(), + Arguments.of( new PurchaseReceiptRequestedForOpenPaymentException(), CreateLoginReceiptCredentialResponse.ResponseCase.PAYMENT_STILL_PROCESSING), - Arguments.of( new SubscriptionPaymentRequiredException(), + Arguments.of( new PurchasePaymentRequiredException(PaymentProvider.APPLE_APP_STORE), CreateLoginReceiptCredentialResponse.ResponseCase.PAYMENT_REQUIRED), - Arguments.of(new SubscriptionNotFoundException(), + Arguments.of(new PurchaseNotFoundException(), CreateLoginReceiptCredentialResponse.ResponseCase.PAYMENT_NOT_FOUND), - Arguments.of(new SubscriptionReceiptAlreadyRedeemedException(), CreateLoginReceiptCredentialResponse.ResponseCase.RECEIPT_ALREADY_ISSUED)); + Arguments.of(new PurchaseReceiptAlreadyRedeemedException(), CreateLoginReceiptCredentialResponse.ResponseCase.RECEIPT_ALREADY_ISSUED)); } @ParameterizedTest @@ -146,7 +145,7 @@ class LoginPurchaseGrpcServiceTest extends static Stream createReceiptCredentialErrorStatuses() { return Stream.of( - Arguments.of(new SubscriptionInvalidArgumentsException("test"), Status.INVALID_ARGUMENT), + Arguments.of(new PurchaseInvalidArgumentsException("test"), Status.INVALID_ARGUMENT), Arguments.of(new VerificationFailedException(), Status.INVALID_ARGUMENT), Arguments.of(new RateLimitExceededException(null), Status.RESOURCE_EXHAUSTED)); } @@ -163,7 +162,7 @@ class LoginPurchaseGrpcServiceTest extends final ChargeFailure chargeFailure = new ChargeFailure("generic_decline", "some failure message", "networkStatus", null, "type"); when(loginPurchaseManager.generateReceipt(any(), any(), any())).thenThrow( - new SubscriptionChargeFailurePaymentRequiredException(PaymentProvider.APPLE_APP_STORE, chargeFailure)); + new PurchasePaymentRequiredException(PaymentProvider.APPLE_APP_STORE, chargeFailure)); final CreateLoginReceiptCredentialResponse loginReceiptResponse = unauthenticatedServiceStub().createLoginReceiptCredential(createRequest(receiptContext())); assertTrue(loginReceiptResponse.hasPaymentRequired()); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcServiceTest.java index 97b8584cb..49cc6d2a0 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcServiceTest.java @@ -22,7 +22,6 @@ import java.io.IOException; import java.time.Instant; import java.util.HashSet; import java.util.List; -import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import org.junit.jupiter.api.Test; @@ -54,20 +53,21 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; import org.whispersystems.textsecuregcm.limits.RateLimiter; import org.whispersystems.textsecuregcm.limits.RateLimiters; +import org.whispersystems.textsecuregcm.purchases.BraintreeManager; +import org.whispersystems.textsecuregcm.purchases.ChargeFailure; +import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator; +import org.whispersystems.textsecuregcm.purchases.PaymentDetails; +import org.whispersystems.textsecuregcm.purchases.PurchaseException; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.StripeManager; import org.whispersystems.textsecuregcm.storage.DonationPermits; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager; import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager; import org.whispersystems.textsecuregcm.storage.WriteConflictException; -import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; -import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; -import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator; -import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails; -import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; -import org.whispersystems.textsecuregcm.subscriptions.StripeManager; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; import org.whispersystems.textsecuregcm.tests.util.SubscriptionConfigTestHelper; import org.whispersystems.textsecuregcm.util.TestClock; @@ -137,11 +137,11 @@ public class OneTimeDonationsGrpcServiceTest extends } @Test - void createBoost() throws SubscriptionInvalidAmountException { + void createBoost() throws PurchaseInvalidAmountException { final PaymentIntent paymentIntent = mock(PaymentIntent.class); when(paymentIntent.getClientSecret()).thenReturn("test-client-secret"); when(stripeManager.getSupportedCurrenciesForPaymentMethod( - org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD)) + org.whispersystems.textsecuregcm.purchases.PaymentMethod.CARD)) .thenReturn(Set.of("usd")); when(stripeManager.createPaymentIntent(any(), anyLong(), anyLong(), any())) .thenReturn(paymentIntent); @@ -183,10 +183,10 @@ public class OneTimeDonationsGrpcServiceTest extends final PaymentMethod paymentMethod, final CreateBoostResponse.ResponseCase expectedResponseCase) { when(stripeManager.getSupportedCurrenciesForPaymentMethod( - org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD)) + org.whispersystems.textsecuregcm.purchases.PaymentMethod.CARD)) .thenReturn(Set.of("usd")); when(stripeManager.getSupportedCurrenciesForPaymentMethod( - org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT)) + org.whispersystems.textsecuregcm.purchases.PaymentMethod.SEPA_DEBIT)) .thenReturn(Set.of("eur")); final CreateBoostResponse response = unauthenticatedServiceStub().createBoost( @@ -220,7 +220,7 @@ public class OneTimeDonationsGrpcServiceTest extends when(approvalDetails.approvalUrl()).thenReturn("test-approval-url"); when(approvalDetails.paymentId()).thenReturn("test-id"); when(braintreeManager.getSupportedCurrenciesForPaymentMethod( - org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL)) + org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL)) .thenReturn(Set.of("usd")); when(payPalDonationsTranslator.translate(any(), any())) .thenReturn("Donation to Signal Technology Foundation"); @@ -243,9 +243,9 @@ public class OneTimeDonationsGrpcServiceTest extends } @Test - void confirmPayPalBoost() throws SubscriptionProcessorException, IOException { + void confirmPayPalBoost() throws PurchaseProcessorException, IOException { when(braintreeManager.getSupportedCurrenciesForPaymentMethod( - org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL)) + org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL)) .thenReturn(Set.of("usd")); when(braintreeManager.captureOneTimePayment(anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), any())) @@ -270,10 +270,11 @@ public class OneTimeDonationsGrpcServiceTest extends @MethodSource void createBoostReceiptCredentialPaymentRequired( @Nullable final ChargeFailure chargeFailure, - final boolean expectChargeFailure) throws IOException { - when(stripeManager.claimOneTimePurchase(any())).thenReturn( - Optional.of(new PaymentDetails("id", null, PaymentStatus.FAILED, - clock.instant(), chargeFailure))); + final boolean expectChargeFailure) throws IOException, PurchaseException { + when(stripeManager.claimOneTimePurchase(any())).thenThrow(chargeFailure == null + ? new PurchasePaymentRequiredException(org.whispersystems.textsecuregcm.purchases.PaymentProvider.STRIPE) + : new PurchasePaymentRequiredException( + org.whispersystems.textsecuregcm.purchases.PaymentProvider.STRIPE, chargeFailure)); final CreateBoostReceiptCredentialResponse response = unauthenticatedServiceStub().createBoostReceiptCredential( @@ -306,9 +307,8 @@ public class OneTimeDonationsGrpcServiceTest extends new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest(); when(oneTimeDonationsManager.getPaidAt(any(), anyString(), any())).thenReturn(clock.instant()); - when(stripeManager.claimOneTimePurchase(any())).thenReturn( - Optional.of(new PaymentDetails("id", ReceiptLevel.ONE_TIME_DONATION, - PaymentStatus.SUCCEEDED, clock.instant(), null))); + when(stripeManager.claimOneTimePurchase(any())) + .thenReturn(new PaymentDetails("id", ReceiptLevel.ONE_TIME_DONATION, clock.instant())); doThrow(WriteConflictException.class).when(issuedReceiptsManager) .recordOneTimeIssuance(any(), any(), any(), any()); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcServiceTest.java index d89566a99..1e7a2dc42 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcServiceTest.java @@ -25,9 +25,9 @@ import org.signal.chat.purchase.ProductConfigurationGrpc; import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration; -import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; -import org.whispersystems.textsecuregcm.subscriptions.StripeManager; +import org.whispersystems.textsecuregcm.purchases.BraintreeManager; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.StripeManager; import org.whispersystems.textsecuregcm.tests.util.SubscriptionConfigTestHelper; public class ProductConfigurationGrpcServiceTest extends @@ -55,17 +55,17 @@ public class ProductConfigurationGrpcServiceTest extends when(stripeManager.supportsPaymentMethod(any())).thenCallRealMethod(); when(stripeManager.getSupportedCurrenciesForPaymentMethod( - org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD)) + org.whispersystems.textsecuregcm.purchases.PaymentMethod.CARD)) .thenReturn(Set.of("usd", "jpy", "bif", "eur")); when(stripeManager.getSupportedCurrenciesForPaymentMethod( - org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT)) + org.whispersystems.textsecuregcm.purchases.PaymentMethod.SEPA_DEBIT)) .thenReturn(Set.of("eur")); when(stripeManager.getSupportedCurrenciesForPaymentMethod( - org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.IDEAL)) + org.whispersystems.textsecuregcm.purchases.PaymentMethod.IDEAL)) .thenReturn(Set.of("eur")); when(braintreeManager.supportsPaymentMethod(any())).thenCallRealMethod(); when(braintreeManager.getSupportedCurrenciesForPaymentMethod( - org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL)) + org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL)) .thenReturn(Set.of("usd", "jpy")); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java index 6765880e6..430266d69 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java @@ -107,7 +107,7 @@ import org.whispersystems.textsecuregcm.storage.ProfilesManager; import org.whispersystems.textsecuregcm.storage.VersionedProfile; import org.whispersystems.textsecuregcm.storage.VersionedProfileV1; import org.whispersystems.textsecuregcm.storage.WriteConflictException; -import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; +import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper; import org.whispersystems.textsecuregcm.util.MockUtils; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcServiceTest.java index fa886da60..d2f4857df 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcServiceTest.java @@ -69,33 +69,32 @@ import org.whispersystems.textsecuregcm.storage.DonationPermits; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.SubscriptionManager; import org.whispersystems.textsecuregcm.storage.Subscriptions; -import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager; -import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator; -import org.whispersystems.textsecuregcm.subscriptions.BankTransferType; -import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; -import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; -import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer; -import org.whispersystems.textsecuregcm.subscriptions.StripeManager; -import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPrice; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionStatus; +import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager; +import org.whispersystems.textsecuregcm.purchases.BankMandateTranslator; +import org.whispersystems.textsecuregcm.purchases.BankTransferType; +import org.whispersystems.textsecuregcm.purchases.BraintreeManager; +import org.whispersystems.textsecuregcm.purchases.ChargeFailure; +import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.ProcessorCustomer; +import org.whispersystems.textsecuregcm.purchases.StripeManager; +import org.whispersystems.textsecuregcm.purchases.SubscriberIdCreationNotPermittedException; +import org.whispersystems.textsecuregcm.purchases.PurchaseException; +import org.whispersystems.textsecuregcm.purchases.PurchaseForbiddenException; +import org.whispersystems.textsecuregcm.purchases.SubscriptionInformation; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidIdempotencyKeyException; +import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidLevelException; +import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; +import org.whispersystems.textsecuregcm.purchases.SubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; +import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiresActionException; +import org.whispersystems.textsecuregcm.purchases.SubscriptionPrice; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorConflictException; +import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException; +import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException; +import org.whispersystems.textsecuregcm.purchases.SubscriptionStatus; import org.whispersystems.textsecuregcm.tests.util.SubscriptionConfigTestHelper; import org.whispersystems.textsecuregcm.util.TestClock; import org.whispersystems.textsecuregcm.util.TestRandomUtil; @@ -162,7 +161,7 @@ public class SubscriptionsGrpcServiceTest extends } @Test - void updateSubscriberCreationNotPermittedPermitRejected() throws SubscriptionException { + void updateSubscriberCreationNotPermittedPermitRejected() throws PurchaseException { doThrow(new SubscriberIdCreationNotPermittedException()) .when(subscriptionManager).updateSubscriber(any(), eq(false)); @@ -179,7 +178,7 @@ public class SubscriptionsGrpcServiceTest extends } @Test - void updateSubscriberCreationNotPermittedMissingPermit() throws SubscriptionException { + void updateSubscriberCreationNotPermittedMissingPermit() throws PurchaseException { doThrow(new SubscriberIdCreationNotPermittedException()) .when(subscriptionManager).updateSubscriber(any(), eq(false)); GrpcTestUtils.assertStatusInvalidArgument(() -> unauthenticatedServiceStub().updateSubscriber( @@ -189,8 +188,8 @@ public class SubscriptionsGrpcServiceTest extends } @Test - void updateSubscriberIdMismatch() throws SubscriptionException { - doThrow(new SubscriptionForbiddenException("subscriberId mismatch")) + void updateSubscriberIdMismatch() throws PurchaseException { + doThrow(new PurchaseForbiddenException("subscriberId mismatch")) .when(subscriptionManager).updateSubscriber(any(), anyBoolean()); GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().updateSubscriber( UpdateSubscriberRequest.newBuilder() @@ -209,8 +208,8 @@ public class SubscriptionsGrpcServiceTest extends @Test void deleteSubscriberNotFound() - throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException { - doThrow(new SubscriptionNotFoundException()) + throws PurchaseNotFoundException, PurchaseInvalidArgumentsException, RateLimitExceededException { + doThrow(new PurchaseNotFoundException()) .when(subscriptionManager).deleteSubscriber(any()); final DeleteSubscriberResponse response = unauthenticatedServiceStub().deleteSubscriber( DeleteSubscriberRequest.newBuilder() @@ -221,8 +220,8 @@ public class SubscriptionsGrpcServiceTest extends @Test void deleteSubscriberCannotCancel() - throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException { - doThrow(new SubscriptionInvalidArgumentsException("cannot cancel subscription")) + throws PurchaseNotFoundException, PurchaseInvalidArgumentsException, RateLimitExceededException { + doThrow(new PurchaseInvalidArgumentsException("cannot cancel subscription")) .when(subscriptionManager).deleteSubscriber(any()); final DeleteSubscriberResponse response = unauthenticatedServiceStub().deleteSubscriber( DeleteSubscriberRequest.newBuilder() @@ -235,7 +234,7 @@ public class SubscriptionsGrpcServiceTest extends @EnumSource(value = PaymentMethod.class, names = {"PAYMENT_METHOD_CARD", "PAYMENT_METHOD_SEPA_DEBIT", "PAYMENT_METHOD_IDEAL"}) void createPaymentMethod(final PaymentMethod paymentMethod) - throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException { + throws PurchaseForbiddenException, PurchaseNotFoundException, PurchaseProcessorConflictException { when(subscriptionManager.addPaymentMethodToCustomer(any(), any(), any(), any())).thenReturn("test-client-secret"); when(stripeManager.getProvider()).thenReturn(PaymentProvider.STRIPE); @@ -291,8 +290,8 @@ public class SubscriptionsGrpcServiceTest extends @Test void createPaymentMethodProcessorConflict() - throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException { - doThrow(new SubscriptionProcessorConflictException()) + throws PurchaseForbiddenException, PurchaseNotFoundException, PurchaseProcessorConflictException { + doThrow(new PurchaseProcessorConflictException()) .when(subscriptionManager).addPaymentMethodToCustomer(any(), any(), any(), any()); final CreatePaymentMethodResponse response = unauthenticatedServiceStub().createPaymentMethod( CreatePaymentMethodRequest.newBuilder() @@ -305,7 +304,7 @@ public class SubscriptionsGrpcServiceTest extends @Test void createPayPalPaymentMethod() - throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException { + throws PurchaseForbiddenException, PurchaseNotFoundException, PurchaseProcessorConflictException { final BraintreeManager.PayPalBillingAgreementApprovalDetails details = new BraintreeManager.PayPalBillingAgreementApprovalDetails("https://fake-approval", "test-billing-token"); when(subscriptionManager.addPaymentMethodToCustomer(any(), any(), any(), any())) @@ -323,8 +322,8 @@ public class SubscriptionsGrpcServiceTest extends @Test void createPayPalPaymentMethodProcessorConflict() - throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException { - doThrow(new SubscriptionProcessorConflictException()) + throws PurchaseForbiddenException, PurchaseNotFoundException, PurchaseProcessorConflictException { + doThrow(new PurchaseProcessorConflictException()) .when(subscriptionManager).addPaymentMethodToCustomer(any(), any(), any(), any()); final CreatePayPalPaymentMethodResponse response = unauthenticatedServiceStub().createPayPalPaymentMethod( CreatePayPalPaymentMethodRequest.newBuilder() @@ -339,7 +338,7 @@ public class SubscriptionsGrpcServiceTest extends @ParameterizedTest @EnumSource(value = SetDefaultPaymentMethodRequest.RequestCase.class, names = {"STRIPE", "BRAINTREE", "SEPA"}) void setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest.RequestCase requestCase) - throws SubscriptionNotFoundException, SubscriptionForbiddenException, IOException, SubscriptionProcessorConflictException { + throws PurchaseNotFoundException, PurchaseForbiddenException, IOException, PurchaseProcessorConflictException { final PaymentProvider provider = requestCase == SetDefaultPaymentMethodRequest.RequestCase.BRAINTREE ? PaymentProvider.BRAINTREE : PaymentProvider.STRIPE; final Subscriptions.Record record = mock(Subscriptions.Record.class); @@ -376,8 +375,8 @@ public class SubscriptionsGrpcServiceTest extends @Test void setDefaultPaymentMethodSubscriptionNotFound() - throws SubscriptionNotFoundException, SubscriptionForbiddenException { - doThrow(new SubscriptionNotFoundException()) + throws PurchaseNotFoundException, PurchaseForbiddenException { + doThrow(new PurchaseNotFoundException()) .when(subscriptionManager).getSubscriber(any()); final SetDefaultPaymentMethodResponse response = unauthenticatedServiceStub().setDefaultPaymentMethod( SetDefaultPaymentMethodRequest.newBuilder() @@ -389,7 +388,7 @@ public class SubscriptionsGrpcServiceTest extends } @Test - void setDefaultPaymentMethodNoCustomer() throws SubscriptionNotFoundException, SubscriptionForbiddenException { + void setDefaultPaymentMethodNoCustomer() throws PurchaseNotFoundException, PurchaseForbiddenException { final Subscriptions.Record record = mock(Subscriptions.Record.class); when(record.getProcessorCustomer()).thenReturn(Optional.empty()); when(subscriptionManager.getSubscriber(any())).thenReturn(record); @@ -402,7 +401,7 @@ public class SubscriptionsGrpcServiceTest extends assertEquals(SetDefaultPaymentMethodResponse.ResponseCase.PAYMENT_METHOD_NOT_SET_UP, response.getResponseCase()); } - private void mockValidSubscription() throws SubscriptionNotFoundException, SubscriptionForbiddenException { + private void mockValidSubscription() throws PurchaseNotFoundException, PurchaseForbiddenException { final Subscriptions.Record record = mock(Subscriptions.Record.class); when(record.getProcessorCustomer()).thenReturn( Optional.of(new ProcessorCustomer("test-customer", PaymentProvider.STRIPE))); @@ -410,7 +409,7 @@ public class SubscriptionsGrpcServiceTest extends } @Test - void setSubscriptionLevel() throws SubscriptionException { + void setSubscriptionLevel() throws PurchaseException { mockValidSubscription(); final SetSubscriptionLevelResponse response = unauthenticatedServiceStub().setSubscriptionLevel( SetSubscriptionLevelRequest.newBuilder() @@ -424,8 +423,8 @@ public class SubscriptionsGrpcServiceTest extends } @Test - void setSubscriptionLevelNotFound() throws SubscriptionNotFoundException, SubscriptionForbiddenException { - doThrow(new SubscriptionNotFoundException()) + void setSubscriptionLevelNotFound() throws PurchaseNotFoundException, PurchaseForbiddenException { + doThrow(new PurchaseNotFoundException()) .when(subscriptionManager).getSubscriber(any()); final SetSubscriptionLevelResponse response = unauthenticatedServiceStub().setSubscriptionLevel( SetSubscriptionLevelRequest.newBuilder() @@ -436,7 +435,7 @@ public class SubscriptionsGrpcServiceTest extends } @Test - void setSubscriptionLevelNoCustomer() throws SubscriptionNotFoundException, SubscriptionForbiddenException { + void setSubscriptionLevelNoCustomer() throws PurchaseNotFoundException, PurchaseForbiddenException { final Subscriptions.Record record = mock(Subscriptions.Record.class); when(record.getProcessorCustomer()).thenReturn(Optional.empty()); when(subscriptionManager.getSubscriber(any())).thenReturn(record); @@ -449,7 +448,7 @@ public class SubscriptionsGrpcServiceTest extends } @Test - void setSubscriptionLevelUnsupportedLevel() throws SubscriptionNotFoundException, SubscriptionForbiddenException { + void setSubscriptionLevelUnsupportedLevel() throws PurchaseNotFoundException, PurchaseForbiddenException { final Subscriptions.Record record = mock(Subscriptions.Record.class); when(record.getProcessorCustomer()).thenReturn( Optional.of(new ProcessorCustomer("test-customer", PaymentProvider.STRIPE))); @@ -463,7 +462,7 @@ public class SubscriptionsGrpcServiceTest extends } @Test - void setSubscriptionLevelUnsupportedCurrency() throws SubscriptionNotFoundException, SubscriptionForbiddenException { + void setSubscriptionLevelUnsupportedCurrency() throws PurchaseNotFoundException, PurchaseForbiddenException { final Subscriptions.Record record = mock(Subscriptions.Record.class); when(record.getProcessorCustomer()).thenReturn( Optional.of(new ProcessorCustomer("test-customer", PaymentProvider.STRIPE))); @@ -478,9 +477,9 @@ public class SubscriptionsGrpcServiceTest extends @ParameterizedTest @MethodSource - void setSubscriptionLevelUpdateExceptions(final SubscriptionException exception, + void setSubscriptionLevelUpdateExceptions(final PurchaseException exception, final SetSubscriptionLevelResponse.ResponseCase expectedCase) - throws SubscriptionException { + throws PurchaseException { mockValidSubscription(); doThrow(exception).when(subscriptionManager).updateSubscriptionLevelForCustomer( any(), any(), any(), anyLong(), any(), any(), any(), any()); @@ -494,22 +493,22 @@ public class SubscriptionsGrpcServiceTest extends static Stream setSubscriptionLevelUpdateExceptions() { return Stream.of( - Arguments.of(new SubscriptionInvalidIdempotencyKeyException("bad key"), + Arguments.of(new PurchaseInvalidIdempotencyKeyException("bad key"), SetSubscriptionLevelResponse.ResponseCase.INVALID_IDEMPOTENCY_KEY), - Arguments.of(new SubscriptionPaymentRequiresActionException(), + Arguments.of(new PurchasePaymentRequiresActionException(), SetSubscriptionLevelResponse.ResponseCase.PAYMENT_REQUIRES_ACTION), - Arguments.of(new SubscriptionInvalidLevelException(), + Arguments.of(new PurchaseInvalidLevelException(), SetSubscriptionLevelResponse.ResponseCase.INVALID_LEVEL_TRANSITION), - Arguments.of(new SubscriptionProcessorConflictException(), + Arguments.of(new PurchaseProcessorConflictException(), SetSubscriptionLevelResponse.ResponseCase.SUBSCRIPTION_PROCESSOR_CONFLICT) ); } @Test void setSubscriptionLevelChargeFailure() - throws SubscriptionException { + throws PurchaseException { mockValidSubscription(); - doThrow(new SubscriptionProcessorException(PaymentProvider.STRIPE, + doThrow(new PurchaseProcessorException(PaymentProvider.STRIPE, new ChargeFailure("card_declined", "Insufficient funds", null, null, null))) .when(subscriptionManager).updateSubscriptionLevelForCustomer( any(), any(), any(), anyLong(), any(), any(), any(), any()); @@ -527,7 +526,7 @@ public class SubscriptionsGrpcServiceTest extends @Test void getSubscriptionInformation() - throws SubscriptionNotFoundException, SubscriptionForbiddenException, RateLimitExceededException { + throws PurchaseNotFoundException, PurchaseForbiddenException, RateLimitExceededException { final SubscriptionInformation info = new SubscriptionInformation( new SubscriptionPrice(CURRENCY, 500), LEVEL, @@ -537,7 +536,7 @@ public class SubscriptionsGrpcServiceTest extends false, SubscriptionStatus.ACTIVE, PaymentProvider.STRIPE, - org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD, + org.whispersystems.textsecuregcm.purchases.PaymentMethod.CARD, false, null); when(subscriptionManager.getSubscriptionInformation(any())).thenReturn(Optional.of(info)); @@ -559,7 +558,7 @@ public class SubscriptionsGrpcServiceTest extends @Test void getSubscriptionInformationNoSubscription() - throws SubscriptionNotFoundException, SubscriptionForbiddenException, RateLimitExceededException { + throws PurchaseNotFoundException, PurchaseForbiddenException, RateLimitExceededException { when(subscriptionManager.getSubscriptionInformation(any())).thenReturn(Optional.empty()); final GetSubscriptionInformationResponse response = unauthenticatedServiceStub().getSubscriptionInformation( GetSubscriptionInformationRequest.newBuilder() @@ -586,18 +585,18 @@ public class SubscriptionsGrpcServiceTest extends static Stream getReceiptCredentialExceptions() { return Stream.of( - Arguments.of(new SubscriptionReceiptRequestedForOpenPaymentException(), + Arguments.of(new PurchaseReceiptRequestedForOpenPaymentException(), GetReceiptCredentialResponse.ResponseCase.NO_PAID_INVOICE), - Arguments.of(new SubscriptionPaymentRequiredException(), + Arguments.of(new PurchasePaymentRequiredException(PaymentProvider.STRIPE), GetReceiptCredentialResponse.ResponseCase.PAYMENT_REQUIRED), - Arguments.of(new SubscriptionReceiptAlreadyRedeemedException(), + Arguments.of(new PurchaseReceiptAlreadyRedeemedException(), GetReceiptCredentialResponse.ResponseCase.ALREADY_REDEEMED) ); } @ParameterizedTest @MethodSource - void getReceiptCredentialExceptions(final SubscriptionException exception, + void getReceiptCredentialExceptions(final PurchaseException exception, final GetReceiptCredentialResponse.ResponseCase expectedCase) throws Exception { doThrow(exception).when(subscriptionManager).createReceiptCredential(any(), any(), any(), any()); final GetReceiptCredentialResponse response = unauthenticatedServiceStub().getReceiptCredential( @@ -610,7 +609,7 @@ public class SubscriptionsGrpcServiceTest extends @Test void getReceiptCredentialChargeFailure() throws Exception { - doThrow(new SubscriptionChargeFailurePaymentRequiredException(PaymentProvider.STRIPE, + doThrow(new PurchasePaymentRequiredException(PaymentProvider.STRIPE, new ChargeFailure("card_declined", "Insufficient funds", null, null, null))) .when(subscriptionManager).createReceiptCredential(any(), any(), any(), any()); final GetReceiptCredentialResponse response = unauthenticatedServiceStub().getReceiptCredential( @@ -627,7 +626,7 @@ public class SubscriptionsGrpcServiceTest extends @ParameterizedTest @EnumSource(value = SetIapSubscriptionRequest.RequestCase.class, names = {"APP_STORE", "PLAY_BILLING"}) void setIapSubscription(final SetIapSubscriptionRequest.RequestCase requestCase) - throws SubscriptionException, RateLimitExceededException { + throws PurchaseException, RateLimitExceededException { when(subscriptionManager.updateAppStoreTransactionId(any(), any(), any())).thenReturn(LEVEL); when(subscriptionManager.updatePlayBillingPurchaseToken(any(), any(), any())).thenReturn(LEVEL); final SetIapSubscriptionRequest.Builder builder = SetIapSubscriptionRequest.newBuilder() @@ -656,22 +655,22 @@ public class SubscriptionsGrpcServiceTest extends static Stream setIapSubscriptionExceptions() { return Stream.of( - Arguments.of(new SubscriptionNotFoundException(), + Arguments.of(new PurchaseNotFoundException(), SetIapSubscriptionResponse.ResponseCase.SUBSCRIBER_NOT_FOUND), - Arguments.of(new SubscriptionProcessorConflictException(), + Arguments.of(new PurchaseProcessorConflictException(), SetIapSubscriptionResponse.ResponseCase.SUBSCRIPTION_PROCESSOR_CONFLICT), - Arguments.of(new SubscriptionPaymentRequiredException(), + Arguments.of(new PurchasePaymentRequiredException(PaymentProvider.GOOGLE_PLAY_BILLING), SetIapSubscriptionResponse.ResponseCase.PAYMENT_REQUIRED), - Arguments.of(new SubscriptionInvalidArgumentsException("invalid"), + Arguments.of(new PurchaseInvalidArgumentsException("invalid"), SetIapSubscriptionResponse.ResponseCase.INVALID_TRANSACTION) ); } @ParameterizedTest @MethodSource - void setIapSubscriptionExceptions(final SubscriptionException exception, + void setIapSubscriptionExceptions(final PurchaseException exception, final SetIapSubscriptionResponse.ResponseCase expectedCase) - throws SubscriptionException, RateLimitExceededException { + throws PurchaseException, RateLimitExceededException { doThrow(exception).when(subscriptionManager).updateAppStoreTransactionId(any(), any(), any()); final SetIapSubscriptionResponse response = unauthenticatedServiceStub().setIapSubscription( SetIapSubscriptionRequest.newBuilder() diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreClientTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreClientTest.java similarity index 95% rename from service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreClientTest.java rename to service/src/test/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreClientTest.java index 7657aa0d6..2bfc12686 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreClientTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreClientTest.java @@ -2,7 +2,7 @@ * Copyright 2025 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -60,7 +60,7 @@ class AppleAppStoreClientTest { @Test public void getAllSubscriptions() - throws APIException, IOException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException { + throws APIException, IOException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, RateLimitExceededException { when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{})) .thenReturn(new StatusResponse().environment(Environment.PRODUCTION)); assertThat(apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty()).getEnvironment()) @@ -69,7 +69,7 @@ class AppleAppStoreClientTest { @Test public void getAllSubscriptionsFallback() - throws APIException, IOException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException { + throws APIException, IOException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, 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[]{})) @@ -80,10 +80,10 @@ class AppleAppStoreClientTest { public static Stream 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(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND, "test"), PurchaseNotFoundException.class), + Arguments.of(new APIException(404, APIError.ACCOUNT_NOT_FOUND, "test"), PurchaseNotFoundException.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)); + Arguments.of(new APIException(429, APIError.INVALID_ORIGINAL_TRANSACTION_ID, "test"), PurchaseInvalidArgumentsException.class)); } @ParameterizedTest diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreManagerTest.java similarity index 89% rename from service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreManagerTest.java rename to service/src/test/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreManagerTest.java index f3059071a..fd48cad8f 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/AppleAppStoreManagerTest.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -64,7 +64,7 @@ class AppleAppStoreManagerTest { } @Test - public void lookupTransaction() throws APIException, IOException, VerificationException, SubscriptionException, RateLimitExceededException { + public void lookupTransaction() throws APIException, IOException, VerificationException, PurchaseException, RateLimitExceededException { mockValidSubscription(); final SubscriptionInformation info = appleAppStoreManager.getSubscriptionInformation(ORIGINAL_TX_ID); @@ -78,7 +78,7 @@ class AppleAppStoreManagerTest { @Test public void validateTransaction() - throws VerificationException, APIException, IOException, SubscriptionException, RateLimitExceededException { + throws VerificationException, APIException, IOException, PurchaseException, RateLimitExceededException { mockValidSubscription(); assertThat(appleAppStoreManager.validateTransaction(ORIGINAL_TX_ID)) .isEqualTo(ReceiptLevel.BACKUP_PAID.getValue()); @@ -86,7 +86,7 @@ class AppleAppStoreManagerTest { @Test public void generateReceipt() - throws VerificationException, APIException, IOException, SubscriptionException, RateLimitExceededException { + throws VerificationException, APIException, IOException, PurchaseException, RateLimitExceededException { mockValidSubscription(); final SubscriptionPaymentProcessor.ReceiptItem receipt = appleAppStoreManager.getReceiptItem(ORIGINAL_TX_ID); assertThat(receipt.level()).isEqualTo(ReceiptLevel.BACKUP_PAID.getValue()); @@ -99,12 +99,12 @@ class AppleAppStoreManagerTest { public void generateReceiptExpired() throws VerificationException, APIException, IOException { mockSubscription(Status.EXPIRED, AutoRenewStatus.ON); - assertThatExceptionOfType(SubscriptionPaymentRequiredException.class) + assertThatExceptionOfType(PurchasePaymentRequiredException.class) .isThrownBy(() -> appleAppStoreManager.getReceiptItem(ORIGINAL_TX_ID)); } @Test - public void autoRenewOff() throws VerificationException, APIException, IOException, SubscriptionException, RateLimitExceededException { + public void autoRenewOff() throws VerificationException, APIException, IOException, PurchaseException, RateLimitExceededException { mockSubscription(Status.ACTIVE, AutoRenewStatus.OFF); final SubscriptionInformation info = appleAppStoreManager.getSubscriptionInformation(ORIGINAL_TX_ID); @@ -117,7 +117,7 @@ class AppleAppStoreManagerTest { } @Test - public void lookupMultipleProducts() throws APIException, IOException, VerificationException, RateLimitExceededException, SubscriptionException { + public void lookupMultipleProducts() throws APIException, IOException, VerificationException, RateLimitExceededException, PurchaseException { // The lookup should select the transaction at i=1 final List products = List.of("otherProduct1", SUBSCRIPTION_PRODUCT_ID, "otherProduct3"); @@ -154,7 +154,7 @@ class AppleAppStoreManagerTest { @Test public void multipleLastTransactionsItems() - throws VerificationException, APIException, IOException, SubscriptionPaymentRequiredException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException { + throws VerificationException, APIException, IOException, PurchasePaymentRequiredException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, RateLimitExceededException { when(apiClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{})) .thenReturn(new StatusResponse() .data(List.of(new SubscriptionGroupIdentifierItem() @@ -185,7 +185,7 @@ class AppleAppStoreManagerTest { @EnumSource(mode = EnumSource.Mode.EXCLUDE, names = {"EXPIRED", "REVOKED"}) public void cancelFailsForActiveSubscription(Status status) throws APIException, VerificationException, IOException { mockSubscription(status, AutoRenewStatus.ON); - assertThatExceptionOfType(SubscriptionInvalidArgumentsException.class) + assertThatExceptionOfType(PurchaseInvalidArgumentsException.class) .isThrownBy(() -> appleAppStoreManager.cancelAllActiveSubscriptions(ORIGINAL_TX_ID)); } @@ -198,7 +198,7 @@ class AppleAppStoreManagerTest { @Test public void getPaymentDetails() - throws APIException, IOException, VerificationException, SubscriptionException, RateLimitExceededException { + throws APIException, IOException, VerificationException, PurchaseException, RateLimitExceededException { when(apiClient.getTransactionInfo(TRANSACTION_ID)) .thenReturn(new TransactionInfoResponse().signedTransactionInfo(SIGNED_TX_INFO)); final JWSTransactionDecodedPayload payload = new JWSTransactionDecodedPayload() @@ -211,19 +211,17 @@ class AppleAppStoreManagerTest { { // PURCHASED payment - final PaymentDetails paymentDetails = appleAppStoreManager.claimOneTimePurchase(TRANSACTION_ID).orElseThrow(); + final PaymentDetails paymentDetails = appleAppStoreManager.claimOneTimePurchase(TRANSACTION_ID); assertThat(paymentDetails.id()).isEqualTo(TRANSACTION_ID); assertThat(paymentDetails.level()).isEqualTo(ReceiptLevel.LOGIN); 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); + assertThatExceptionOfType(PurchasePaymentRequiredException.class) + .isThrownBy(() -> appleAppStoreManager.claimOneTimePurchase(TRANSACTION_ID)); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeGraphqlClientTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/BraintreeGraphqlClientTest.java similarity index 98% rename from service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeGraphqlClientTest.java rename to service/src/test/java/org/whispersystems/textsecuregcm/purchases/BraintreeGraphqlClientTest.java index 79c7d131c..0d16da9d0 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeGraphqlClientTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/BraintreeGraphqlClientTest.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/BraintreeManagerTest.java similarity index 96% rename from service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManagerTest.java rename to service/src/test/java/org/whispersystems/textsecuregcm/purchases/BraintreeManagerTest.java index 8a4dd7091..3cfc6d699 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/BraintreeManagerTest.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.mockito.ArgumentMatchers.anyString; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/GooglePlayBillingManagerTest.java similarity index 88% rename from service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManagerTest.java rename to service/src/test/java/org/whispersystems/textsecuregcm/purchases/GooglePlayBillingManagerTest.java index 023d2d32a..b1d8aaf8b 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/GooglePlayBillingManagerTest.java @@ -2,7 +2,7 @@ * Copyright 2024 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatException; @@ -115,7 +115,7 @@ class GooglePlayBillingManagerTest { } @Test - public void validatePurchase() throws IOException, RateLimitExceededException, SubscriptionException { + public void validatePurchase() throws IOException, RateLimitExceededException, PurchaseException { when(subscriptionsv2Get.execute()).thenReturn(new SubscriptionPurchaseV2() .setAcknowledgementState(GooglePlayBillingManager.AcknowledgementState.PENDING.apiString()) .setSubscriptionState(GooglePlayBillingManager.SubscriptionState.ACTIVE.apiString()) @@ -143,13 +143,13 @@ class GooglePlayBillingManagerTest { switch (subscriptionState) { case ACTIVE, IN_GRACE_PERIOD, CANCELED -> assertThatNoException() .isThrownBy(() -> googlePlayBillingManager.validateToken(PURCHASE_TOKEN)); - default -> assertThatExceptionOfType(SubscriptionPaymentRequiredException.class) + default -> assertThatExceptionOfType(PurchasePaymentRequiredException.class) .isThrownBy(() -> googlePlayBillingManager.validateToken(PURCHASE_TOKEN)); } } @Test - public void avoidDoubleAcknowledge() throws IOException, RateLimitExceededException, SubscriptionException { + public void avoidDoubleAcknowledge() throws IOException, RateLimitExceededException, PurchaseException { when(subscriptionsv2Get.execute()).thenReturn(new SubscriptionPurchaseV2() .setAcknowledgementState(GooglePlayBillingManager.AcknowledgementState.ACKNOWLEDGED.apiString()) .setSubscriptionState(GooglePlayBillingManager.SubscriptionState.ACTIVE.apiString()) @@ -203,7 +203,7 @@ class GooglePlayBillingManagerTest { @Test public void getReceiptUnacknowledged() - throws IOException, SubscriptionPaymentRequiredException, SubscriptionNotFoundException, RateLimitExceededException { + throws IOException, PurchasePaymentRequiredException, PurchaseNotFoundException, RateLimitExceededException { when(subscriptionsv2Get.execute()).thenReturn(new SubscriptionPurchaseV2() .setAcknowledgementState(GooglePlayBillingManager.AcknowledgementState.PENDING.apiString()) .setSubscriptionState(GooglePlayBillingManager.SubscriptionState.ACTIVE.apiString()) @@ -216,7 +216,7 @@ class GooglePlayBillingManagerTest { @Test public void getReceiptExpiring() - throws IOException, RateLimitExceededException, SubscriptionException { + throws IOException, RateLimitExceededException, PurchaseException { final Instant day9 = Instant.EPOCH.plus(Duration.ofDays(9)); final Instant day10 = Instant.EPOCH.plus(Duration.ofDays(10)); @@ -245,12 +245,12 @@ class GooglePlayBillingManagerTest { // next second should be expired clock.setTimeInstant(day10.plus(Duration.ofSeconds(1))); - assertThatExceptionOfType(SubscriptionPaymentRequiredException.class) + assertThatExceptionOfType(PurchasePaymentRequiredException.class) .isThrownBy(() -> googlePlayBillingManager.getReceiptItem(PURCHASE_TOKEN)); } @Test - public void getSubscriptionInfo() throws IOException, RateLimitExceededException, SubscriptionException { + public void getSubscriptionInfo() throws IOException, RateLimitExceededException, PurchaseException { final String basePlanId = "basePlanId"; when(subscriptionsv2Get.execute()).thenReturn(new SubscriptionPurchaseV2() .setAcknowledgementState(GooglePlayBillingManager.AcknowledgementState.ACKNOWLEDGED.apiString()) @@ -297,25 +297,27 @@ class GooglePlayBillingManagerTest { public void getPaymentDetails( @CartesianTest.Enum final GooglePlayBillingManager.PurchaseState purchaseState, @CartesianTest.Enum final GooglePlayBillingManager.ConsumptionState consumptionState) - throws IOException, RateLimitExceededException, SubscriptionException { + throws IOException, RateLimitExceededException, PurchaseException { when(getProductPurchase.execute()).thenReturn(productPurchase( purchaseState.apiString(), consumptionState.apiString(), Instant.EPOCH.plus(Duration.ofDays(3)), ONE_TIME_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; + final Class expectedException = switch (purchaseState) { + case PURCHASED -> null; + case PENDING -> PurchaseReceiptRequestedForOpenPaymentException.class; + case CANCELLED, PURCHASE_STATE_UNSPECIFIED -> PurchasePaymentRequiredException.class; }; - assertThat(googlePlayBillingManager.claimOneTimePurchase(PURCHASE_TOKEN)).hasValueSatisfying(details -> { - assertThat(details.status()).isEqualTo(expected); + if (expectedException != null) { + assertThatExceptionOfType(expectedException).isThrownBy(() -> + googlePlayBillingManager.claimOneTimePurchase(PURCHASE_TOKEN)); + } else { + final PaymentDetails details = googlePlayBillingManager.claimOneTimePurchase(PURCHASE_TOKEN); assertThat(details.id()).isEqualTo(PURCHASE_TOKEN); assertThat(details.level()).isEqualTo(ReceiptLevel.LOGIN); - }); + } final boolean expectConsume = purchaseState == GooglePlayBillingManager.PurchaseState.PURCHASED && consumptionState == GooglePlayBillingManager.ConsumptionState.YET_TO_BE_CONSUMED; @@ -325,8 +327,8 @@ class GooglePlayBillingManagerTest { public static Stream getPaymentDetailsErrors() { return Stream.of( - Arguments.of(404, null), - Arguments.of(410, null), + Arguments.of(404, PurchaseNotFoundException.class), + Arguments.of(410, PurchaseNotFoundException.class), Arguments.of(400, IOException.class), Arguments.of(429, RateLimitExceededException.class) ); @@ -334,34 +336,30 @@ class GooglePlayBillingManagerTest { @ParameterizedTest @MethodSource - public void getPaymentDetailsErrors(final int httpStatus, final @Nullable Class expectedException) - throws IOException, SubscriptionInvalidArgumentsException, RateLimitExceededException { + public void getPaymentDetailsErrors(final int httpStatus, final Class expectedException) + throws IOException, PurchaseInvalidArgumentsException, 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); - }); - } + 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 tokenErrors() { return Stream.of( - Arguments.of(404, SubscriptionNotFoundException.class), - Arguments.of(410, SubscriptionNotFoundException.class), + Arguments.of(404, PurchaseNotFoundException.class), + Arguments.of(410, PurchaseNotFoundException.class), Arguments.of(400, IOException.class) ); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/LoginPurchaseManagerTest.java similarity index 61% rename from service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManagerTest.java rename to service/src/test/java/org/whispersystems/textsecuregcm/purchases/LoginPurchaseManagerTest.java index 4dfd35eef..d4790fc8d 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/LoginPurchaseManagerTest.java @@ -2,7 +2,7 @@ * Copyright 2026 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -12,19 +12,13 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Map; -import java.util.Optional; -import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.signal.libsignal.zkgroup.ServerSecretParams; @@ -34,7 +28,6 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequestContext; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse; import org.signal.libsignal.zkgroup.receipts.ReceiptSerial; import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; -import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager; import org.whispersystems.textsecuregcm.storage.WriteConflictException; import org.whispersystems.textsecuregcm.util.TestRandomUtil; @@ -45,8 +38,6 @@ class LoginPurchaseManagerTest { private static final PaymentProvider PROVIDER = PaymentProvider.APPLE_APP_STORE; private static final String PURCHASE_ID = "purchaseId"; private static final Instant PURCHASED_AT = Instant.now().minus(Duration.ofHours(3)); - private static final ChargeFailure CHARGE_FAILURE = - new ChargeFailure("generic_decline", "some failure message", null, null, null); private static final ServerSecretParams SERVER_SECRET_PARAMS = ServerSecretParams.generate(); @@ -75,7 +66,7 @@ class LoginPurchaseManagerTest { @Test void generateReceiptSuccess() throws Exception { when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID)) - .thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PaymentStatus.SUCCEEDED, PURCHASED_AT, null))); + .thenReturn(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PURCHASED_AT)); final ReceiptCredentialResponse receipt = loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest()); @@ -93,36 +84,11 @@ class LoginPurchaseManagerTest { PURCHASE_ID, PROVIDER, receiptCredentialRequestContext.getRequest(), expectedExpiration); } - static Stream generateReceiptErrors() { - return Stream.of( - Arguments.of(Optional.empty(), SubscriptionNotFoundException.class), - Arguments.of( - Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PaymentStatus.PROCESSING, PURCHASED_AT, null)), - SubscriptionReceiptRequestedForOpenPaymentException.class), - Arguments.of( - Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PaymentStatus.FAILED, PURCHASED_AT, CHARGE_FAILURE)), - SubscriptionChargeFailurePaymentRequiredException.class), - Arguments.of( - Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PaymentStatus.FAILED, PURCHASED_AT, null)), - SubscriptionPaymentRequiredException.class), - Arguments.of(Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PaymentStatus.UNKNOWN, PURCHASED_AT, null)), - SubscriptionPaymentRequiredException.class)); - } - - @ParameterizedTest - @MethodSource - void generateReceiptErrors(final Optional paymentDetails, final Class expectedException) - throws SubscriptionInvalidArgumentsException, RateLimitExceededException, IOException { - when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID)).thenReturn(paymentDetails); - assertThatExceptionOfType(expectedException).isThrownBy(() -> - loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest())); - } - @Test void generateReceiptUnknownLevel() throws Exception { when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID)) - .thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, null, PaymentStatus.SUCCEEDED, PURCHASED_AT, null))); - assertThatExceptionOfType(SubscriptionInvalidArgumentsException.class).isThrownBy(() -> + .thenReturn(new PaymentDetails(PURCHASE_ID, null, PURCHASED_AT)); + assertThatExceptionOfType(PurchaseInvalidArgumentsException.class).isThrownBy(() -> loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest())); verifyNoInteractions(issuedReceiptsManager); } @@ -130,8 +96,8 @@ class LoginPurchaseManagerTest { @Test void generateReceiptNonLoginLevel() throws Exception { when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID)) - .thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.ONE_TIME_DONATION, PaymentStatus.SUCCEEDED, PURCHASED_AT, null))); - assertThatExceptionOfType(SubscriptionInvalidArgumentsException.class).isThrownBy(() -> + .thenReturn(new PaymentDetails(PURCHASE_ID, ReceiptLevel.ONE_TIME_DONATION, PURCHASED_AT)); + assertThatExceptionOfType(PurchaseInvalidArgumentsException.class).isThrownBy(() -> loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest())); verifyNoInteractions(issuedReceiptsManager); } @@ -139,10 +105,10 @@ class LoginPurchaseManagerTest { @Test void generateReceiptAlreadyRedeemed() throws Exception { when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID)) - .thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PaymentStatus.SUCCEEDED, PURCHASED_AT, null))); + .thenReturn(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PURCHASED_AT)); doThrow(new WriteConflictException()) .when(issuedReceiptsManager).recordOneTimeIssuance(any(), any(), any(), any()); - assertThatExceptionOfType(SubscriptionReceiptAlreadyRedeemedException.class).isThrownBy(() -> + assertThatExceptionOfType(PurchaseReceiptAlreadyRedeemedException.class).isThrownBy(() -> loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest())); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/PayPalDonationsTranslatorTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/PayPalDonationsTranslatorTest.java similarity index 94% rename from service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/PayPalDonationsTranslatorTest.java rename to service/src/test/java/org/whispersystems/textsecuregcm/purchases/PayPalDonationsTranslatorTest.java index eaa317ca3..5956a838e 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/PayPalDonationsTranslatorTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/PayPalDonationsTranslatorTest.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/ProcessorCustomerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/ProcessorCustomerTest.java similarity index 87% rename from service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/ProcessorCustomerTest.java rename to service/src/test/java/org/whispersystems/textsecuregcm/purchases/ProcessorCustomerTest.java index 0f6ecb6a2..100cfa803 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/ProcessorCustomerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/ProcessorCustomerTest.java @@ -1,4 +1,4 @@ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import org.junit.jupiter.api.Test; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/StripeManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/StripeManagerTest.java similarity index 96% rename from service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/StripeManagerTest.java rename to service/src/test/java/org/whispersystems/textsecuregcm/purchases/StripeManagerTest.java index 2234c3d50..78221feee 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/StripeManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/StripeManagerTest.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -81,7 +81,7 @@ class StripeManagerTest { UUID.randomUUID().toString(), "subscription_payment_intent_requires_action", 400, new Exception()); when(subscriptionService.create(any(), any())).thenThrow(stripeException); - assertThatExceptionOfType(SubscriptionPaymentRequiresActionException.class).isThrownBy(() -> + assertThatExceptionOfType(PurchasePaymentRequiresActionException.class).isThrownBy(() -> stripeManager.createSubscription("customerId", "priceId", 1, 0)); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionCurrencyUtilTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/SubscriptionCurrencyUtilTest.java similarity index 98% rename from service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionCurrencyUtilTest.java rename to service/src/test/java/org/whispersystems/textsecuregcm/purchases/SubscriptionCurrencyUtilTest.java index 12368220c..247b4a70b 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionCurrencyUtilTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/purchases/SubscriptionCurrencyUtilTest.java @@ -2,7 +2,7 @@ * Copyright 2025 Signal Messenger, LLC * SPDX-License-Identifier: AGPL-3.0-only */ -package org.whispersystems.textsecuregcm.subscriptions; +package org.whispersystems.textsecuregcm.purchases; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManagerTest.java index ae51341c9..d90a508d6 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManagerTest.java @@ -25,7 +25,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest; import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; import org.whispersystems.textsecuregcm.util.AttributeValues; import org.whispersystems.textsecuregcm.util.TestRandomUtil; import software.amazon.awssdk.core.SdkBytes; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/OnetimeDonationsManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/OnetimeDonationsManagerTest.java index 60abf6626..7069ed4b9 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/OnetimeDonationsManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/OnetimeDonationsManagerTest.java @@ -12,7 +12,7 @@ import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; public class OnetimeDonationsManagerTest { @RegisterExtension diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/SubscriptionManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/SubscriptionManagerTest.java index 4b1f6cbcd..3f12016b6 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/SubscriptionManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/SubscriptionManagerTest.java @@ -22,10 +22,10 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.SubscriberIdCreationNotPermittedException; +import org.whispersystems.textsecuregcm.purchases.PurchaseForbiddenException; +import org.whispersystems.textsecuregcm.purchases.SubscriptionPaymentProcessor; import org.whispersystems.textsecuregcm.util.TestRandomUtil; class SubscriptionManagerTest { @@ -100,7 +100,7 @@ class SubscriptionManagerTest { when(SUBSCRIPTIONS.get(any(byte[].class), any(byte[].class))).thenReturn(Subscriptions.GetResult.PASSWORD_MISMATCH); - assertThrows(SubscriptionForbiddenException.class, + assertThrows(PurchaseForbiddenException.class, () -> subscriptionManager.updateSubscriber(credentials, true)); verify(SUBSCRIPTIONS, never()).create(any(byte[].class), any(byte[].class), any(Instant.class)); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/SubscriptionsTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/SubscriptionsTest.java index 5c80c53bd..6e75e537b 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/SubscriptionsTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/SubscriptionsTest.java @@ -29,8 +29,8 @@ import org.junit.jupiter.api.extension.RegisterExtension; import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables; import org.whispersystems.textsecuregcm.storage.Subscriptions.GetResult; import org.whispersystems.textsecuregcm.storage.Subscriptions.Record; -import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; -import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer; +import org.whispersystems.textsecuregcm.purchases.PaymentProvider; +import org.whispersystems.textsecuregcm.purchases.ProcessorCustomer; import org.whispersystems.textsecuregcm.util.TestRandomUtil; import software.amazon.awssdk.services.dynamodb.model.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.QueryResponse;