Add an interface for one-time purchase retrieval

This commit is contained in:
Ravi Khadiwala authored and ravi-signal committed 2026-08-05 13:24:14 -05:00
1 parent e4b09112f1
commit 5b6d6f28c9
10 files changed
+80 -40

No files matched your search

@@ -350,8 +350,8 @@ public class OneTimeDonationController {
}
final Optional<PaymentDetails> 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");
});
@@ -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;
@@ -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");
}
@@ -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<CustomFieldInput> 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);
@@ -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<PaymentDetails> getPaymentDetails(final String paymentId) {
@Override
public Optional<PaymentDetails> 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));
@@ -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<PaymentDetails> claimOneTimePurchase(final String paymentIdentifier) throws IOException;
}
@@ -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<String, String> customMetadata,
@Nullable Long level,
PaymentStatus status,
Instant created,
@Nullable ChargeFailure chargeFailure) {}
@@ -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<PaymentDetails> getPaymentDetails(final String paymentIntentId) throws IOException {
@Override
public Optional<PaymentDetails> 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));
@@ -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)));
@@ -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());