From 5b6d6f28c924c3a241f11412979af300863514c0 Mon Sep 17 00:00:00 2001 From: Ravi Khadiwala Date: Fri, 31 Jul 2026 12:50:15 -0500 Subject: [PATCH] Add an interface for one-time purchase retrieval --- .../OneTimeDonationController.java | 4 ++-- .../grpc/OneTimeDonationUtil.java | 24 ++++++++++--------- .../grpc/OneTimeDonationsGrpcService.java | 4 ++-- .../subscriptions/BraintreeGraphqlClient.java | 7 +++--- .../subscriptions/BraintreeManager.java | 18 +++++++++++--- .../OneTimePaymentProcessor.java | 18 ++++++++++++++ .../subscriptions/PaymentDetails.java | 5 ++-- .../subscriptions/StripeManager.java | 19 +++++++++++---- .../OneTimeDonationControllerTest.java | 10 ++++---- .../grpc/OneTimeDonationsGrpcServiceTest.java | 11 ++++----- 10 files changed, 80 insertions(+), 40 deletions(-) create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/OneTimePaymentProcessor.java 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 1a1c52f24..fcead5cad 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java @@ -350,8 +350,8 @@ public class OneTimeDonationController { } final Optional maybePaymentDetails = (switch (request.processor) { - case STRIPE -> stripeManager.getPaymentDetails(request.paymentIntentId); - case BRAINTREE -> braintreeManager.getPaymentDetails(request.paymentIntentId); + 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"); }); 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 91ba14dcc..58e23643e 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java @@ -1,5 +1,7 @@ package org.whispersystems.textsecuregcm.grpc; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.Metrics; import java.math.BigDecimal; import java.time.Duration; import java.util.List; @@ -7,6 +9,7 @@ import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; +import org.whispersystems.textsecuregcm.metrics.MetricsUtil; import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator; import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails; @@ -19,6 +22,9 @@ public class OneTimeDonationUtil { private static final Logger LOGGER = LoggerFactory.getLogger(OneTimeDonationUtil.class); + private static final Counter MISSING_LEVEL_COUNTER = + Metrics.counter(MetricsUtil.name(OneTimeDonationUtil.class, "missingLevelMetadata")); + /// Thrown if a one time donation level cannot be parsed or if it is not found in configuration public static class InvalidLevelException extends Exception { @@ -102,17 +108,13 @@ public class OneTimeDonationUtil { final OneTimeDonationConfiguration oneTimeDonationConfiguration) throws InvalidLevelException { - long level = oneTimeDonationConfiguration.boost().level(); - if (paymentDetails.customMetadata() != null) { - final String levelMetadata = paymentDetails.customMetadata() - .getOrDefault("level", Long.toString(oneTimeDonationConfiguration.boost().level())); - try { - level = Long.parseLong(levelMetadata); - } catch (final NumberFormatException e) { - LOGGER.error("failed to parse level metadata ({}) on payment intent {}", levelMetadata, - paymentDetails.id(), e); - throw new InvalidLevelException("failed to parse level metadata"); - } + Long level = paymentDetails.level(); + if (level == null) { + LOGGER.warn("paymentId {} did not have attached level metadata", paymentDetails.id()); + MISSING_LEVEL_COUNTER.increment(); + + // Default to boost if the level was not encoded in the metadata + level = oneTimeDonationConfiguration.boost().level(); } final Duration levelExpiration; 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 e67fd275f..d8148b347 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java @@ -261,11 +261,11 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT switch (request.getProcessor()) { case PAYMENT_PROVIDER_STRIPE -> { processor = PaymentProvider.STRIPE; - maybePaymentDetails = stripeManager.getPaymentDetails(request.getPaymentIntentId()); + maybePaymentDetails = stripeManager.claimOneTimePurchase(request.getPaymentIntentId()); } case PAYMENT_PROVIDER_BRAINTREE -> { processor = PaymentProvider.BRAINTREE; - maybePaymentDetails = braintreeManager.getPaymentDetails(request.getPaymentIntentId()); + maybePaymentDetails = braintreeManager.claimOneTimePurchase(request.getPaymentIntentId()); } default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor"); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeGraphqlClient.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeGraphqlClient.java index f498a8ac8..a05cc6968 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeGraphqlClient.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeGraphqlClient.java @@ -50,13 +50,14 @@ import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient; class BraintreeGraphqlClient { + private static final Logger logger = LoggerFactory.getLogger(BraintreeGraphqlClient.class); + + static final String LEVEL_METADATA_NAME = "level"; // required header value, recommended to be the date the integration began // https://graphql.braintreepayments.com/guides/making_api_calls/#the-braintree-version-header private static final String BRAINTREE_VERSION = "2022-10-01"; - private static final Logger logger = LoggerFactory.getLogger(BraintreeGraphqlClient.class); - private final FaultTolerantHttpClient httpClient; private final URI graphqlUri; private final String authorizationHeader; @@ -165,7 +166,7 @@ class BraintreeGraphqlClient { throws IOException { final List customFields = List.of( - new CustomFieldInput("level", Optional.present(Long.toString(level)))); + new CustomFieldInput(LEVEL_METADATA_NAME, Optional.present(Long.toString(level)))); final ChargePaymentMethodInput input = buildChargePaymentMethodInput(paymentMethodId, amount, merchantAccount, customFields); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManager.java index 31b797a44..49cc58d36 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManager.java @@ -53,7 +53,7 @@ import org.whispersystems.textsecuregcm.util.GoogleApiUtil; import org.whispersystems.textsecuregcm.util.SystemMapper; import org.whispersystems.textsecuregcm.util.ua.ClientPlatform; -public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcessor { +public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcessor, OneTimePaymentProcessor { private static final Logger logger = LoggerFactory.getLogger(BraintreeManager.class); @@ -130,15 +130,27 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess return paymentMethod == PaymentMethod.PAYPAL; } - public Optional getPaymentDetails(final String paymentId) { + @Override + public Optional claimOneTimePurchase(final String paymentId) { try { final Transaction transaction = braintreeGateway.transaction().find(paymentId); ChargeFailure chargeFailure = null; if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) { chargeFailure = createChargeFailure(transaction); } + + final Long level; + try { + level = Optional.ofNullable(transaction.getCustomFields()) + .map(m -> m.get(BraintreeGraphqlClient.LEVEL_METADATA_NAME)) + .map(Long::parseLong) + .orElse(null); + } catch (final NumberFormatException e) { + throw new IllegalStateException("failed to parse level metadata on payment intent %s".formatted(paymentId), e); + } + return Optional.of(new PaymentDetails(transaction.getGraphQLId(), - transaction.getCustomFields(), + level, getPaymentStatus(transaction.getStatus()), transaction.getCreatedAt().toInstant(), chargeFailure)); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/OneTimePaymentProcessor.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/OneTimePaymentProcessor.java new file mode 100644 index 000000000..c1d6161ff --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/OneTimePaymentProcessor.java @@ -0,0 +1,18 @@ +/* + * 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; +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentDetails.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentDetails.java index de4748c7c..bdda28a7d 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentDetails.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentDetails.java @@ -5,21 +5,20 @@ package org.whispersystems.textsecuregcm.subscriptions; import java.time.Instant; -import java.util.Map; 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 customMetadata Any custom metadata attached to the payment + * @param level The level identifier of purchase, if it could be identified from the processor. * @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, - Map customMetadata, + @Nullable Long level, PaymentStatus status, Instant created, @Nullable ChargeFailure chargeFailure) {} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java index b4a88ed88..600192154 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java @@ -76,7 +76,7 @@ import org.whispersystems.textsecuregcm.util.Conversions; import org.whispersystems.textsecuregcm.util.ExecutorUtil; import org.whispersystems.textsecuregcm.util.ua.ClientPlatform; -public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor { +public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, OneTimePaymentProcessor { private static final Logger logger = LoggerFactory.getLogger(StripeManager.class); private static final String METADATA_KEY_LEVEL = "level"; @@ -221,7 +221,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor .setCurrency(currency.toLowerCase(Locale.ROOT)) .setDescription(boostDescription) .setCaptureMethod(PaymentIntentCreateParams.CaptureMethod.AUTOMATIC) - .putMetadata("level", Long.toString(level)); + .putMetadata(METADATA_KEY_LEVEL, Long.toString(level)); if (clientPlatform != null) { builder.putMetadata(METADATA_KEY_CLIENT_PLATFORM, clientPlatform.name().toLowerCase()); @@ -240,7 +240,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor } } - public Optional getPaymentDetails(final String paymentIntentId) throws IOException { + @Override + public Optional claimOneTimePurchase(final String paymentIntentId) throws IOException { try { final PaymentIntent paymentIntent = getPaymentIntent(paymentIntentId); @@ -252,8 +253,18 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor } } + final Long level; + try { + level = Optional.ofNullable(paymentIntent.getMetadata()) + .map(m -> m.get(METADATA_KEY_LEVEL)) + .map(Long::parseLong) + .orElse(null); + } catch (final NumberFormatException e) { + throw new IllegalStateException("failed to parse level metadata on payment intent %s".formatted(paymentIntentId), e); + } + return Optional.of(new PaymentDetails(paymentIntent.getId(), - paymentIntent.getMetadata() == null ? Collections.emptyMap() : paymentIntent.getMetadata(), + level, getPaymentStatusForStatus(paymentIntent.getStatus()), Instant.ofEpochSecond(paymentIntent.getCreated()), 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 29d85e94d..bfab15691 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java @@ -23,12 +23,10 @@ import jakarta.ws.rs.core.Response; import java.io.IOException; import java.time.Instant; import java.util.Base64; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; import org.assertj.core.api.InstanceOfAssertFactories; import org.glassfish.jersey.server.ServerProperties; @@ -258,9 +256,9 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest @MethodSource void createBoostReceiptPaymentRequired(final ChargeFailure chargeFailure, boolean expectChargeFailure) throws IOException { - when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(Optional.of(new PaymentDetails( + when(STRIPE_MANAGER.claimOneTimePurchase(any())).thenReturn(Optional.of(new PaymentDetails( "id", - Collections.emptyMap(), + null, PaymentStatus.FAILED, Instant.now(), chargeFailure)) @@ -341,9 +339,9 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext( new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest(); - when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(Optional.of(new PaymentDetails( + when(STRIPE_MANAGER.claimOneTimePurchase(any())).thenReturn(Optional.of(new PaymentDetails( "id", - Collections.emptyMap(), + ONETIME_CONFIG.boost().level(), PaymentStatus.SUCCEEDED, Instant.now(), null))); 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 da0c4c95b..524b7b409 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcServiceTest.java @@ -20,7 +20,6 @@ import com.stripe.model.PaymentIntent; import jakarta.annotation.Nullable; import java.io.IOException; import java.time.Instant; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; @@ -271,8 +270,8 @@ public class OneTimeDonationsGrpcServiceTest extends void createBoostReceiptCredentialsPaymentRequired( @Nullable final ChargeFailure chargeFailure, final boolean expectChargeFailure) throws IOException { - when(stripeManager.getPaymentDetails(any())).thenReturn( - Optional.of(new PaymentDetails("id", Collections.emptyMap(), PaymentStatus.FAILED, + when(stripeManager.claimOneTimePurchase(any())).thenReturn( + Optional.of(new PaymentDetails("id", null, PaymentStatus.FAILED, clock.instant(), chargeFailure))); final CreateBoostReceiptCredentialsResponse response = @@ -305,9 +304,9 @@ public class OneTimeDonationsGrpcServiceTest extends ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext( new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest(); - when(stripeManager.getPaymentDetails(any())).thenReturn( - Optional.of(new PaymentDetails("id", Collections.emptyMap(), PaymentStatus.SUCCEEDED, - clock.instant(), null))); + when(stripeManager.claimOneTimePurchase(any())).thenReturn( + Optional.of(new PaymentDetails("id", oneTimeDonationConfiguration.boost().level(), + PaymentStatus.SUCCEEDED, clock.instant(), null))); doThrow(WriteConflictException.class).when(issuedReceiptsManager) .recordIssuance(any(), any(), any(), any());