Make OneTimeDonationController sync

This commit is contained in:
Ameya Lokare authored and Jon Chambers committed 2026-07-01 18:17:16 -04:00
1 parent 8fd72549fb
commit f02caf78cd
16 files changed
+615 -602

No files matched your search

@@ -8,6 +8,7 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientP
import com.fasterxml.jackson.annotation.JsonInclude;
import com.google.common.net.HttpHeaders;
import com.stripe.model.PaymentIntent;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
@@ -34,9 +35,9 @@ import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
@@ -45,7 +46,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
@@ -74,6 +75,8 @@ 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;
@@ -168,14 +171,15 @@ public class OneTimeDonationController {
})))
@ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent")
@RateLimitedByIp(RateLimiters.For.ONE_TIME_DONATION)
public CompletableFuture<Response> createBoostPaymentIntent(
@ManagedAsync
public CreateBoostResponse createBoostPaymentIntent(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@Parameter(description = "A base64-encoded donation permit retrieved from POST /v1/donation/permit")
@HeaderParam(HeaderUtils.DONATION_PERMIT) final Optional<DonationPermitHeader> donationPermitHeader,
@NotNull @Valid final CreateBoostRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionInvalidAmountException {
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
@@ -195,11 +199,11 @@ public class OneTimeDonationController {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
return CompletableFuture.runAsync(() ->
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager))
.thenCompose(_ -> stripeManager.createPaymentIntent(request.currency, request.amount, request.level,
getClientPlatform(userAgent)))
.thenApply(paymentIntent -> Response.ok(new CreateBoostResponse(paymentIntent.getClientSecret())).build());
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager);
final PaymentIntent paymentIntent = stripeManager.createPaymentIntent(request.currency, request.amount,
request.level,
getClientPlatform(userAgent));
return new CreateBoostResponse(paymentIntent.getClientSecret());
}
/**
@@ -245,34 +249,32 @@ public class OneTimeDonationController {
}
}
record CreatePayPalBoostResponse(String approvalUrl, String paymentId) {}
public record CreatePayPalBoostResponse(String approvalUrl, String paymentId) {}
@POST
@Path("/paypal/create")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createPayPalBoost(
@ManagedAsync
public CreatePayPalBoostResponse createPayPalBoost(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final CreatePayPalBoostRequest request,
@Context final ContainerRequestContext containerRequestContext) {
@Context final ContainerRequestContext containerRequestContext) throws IOException {
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
return CompletableFuture.runAsync(() ->
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
.thenCompose(_ -> {
final List<Locale> acceptableLanguages =
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
payPalDonationsTranslator, acceptableLanguages);
return braintreeManager.createOneTimePayment(request.currency.toUpperCase(Locale.ROOT), request.amount,
localizedLineItem.locale().toLanguageTag(),
request.returnUrl, request.cancelUrl, localizedLineItem.itemName());
})
.thenApply(approvalDetails -> Response.ok(
new CreatePayPalBoostResponse(approvalDetails.approvalUrl(), approvalDetails.paymentId())).build());
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
final List<Locale> acceptableLanguages =
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
payPalDonationsTranslator, acceptableLanguages);
final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails =
braintreeManager.createOneTimePayment(request.currency.toUpperCase(Locale.ROOT), request.amount,
localizedLineItem.locale().toLanguageTag(),
request.returnUrl, request.cancelUrl, localizedLineItem.itemName());
return new CreatePayPalBoostResponse(approvalDetails.approvalUrl(), approvalDetails.paymentId());
}
public static class ConfirmPayPalBoostRequest extends CreateBoostRequest {
@@ -289,30 +291,28 @@ public class OneTimeDonationController {
}
}
record ConfirmPayPalBoostResponse(String paymentId) {}
public record ConfirmPayPalBoostResponse(String paymentId) {}
@POST
@Path("/paypal/confirm")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> confirmPayPalBoost(
@ManagedAsync
public ConfirmPayPalBoostResponse confirmPayPalBoost(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final ConfirmPayPalBoostRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionProcessorException, IOException {
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
return CompletableFuture.runAsync(() ->
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
.thenCompose(_ -> braintreeManager.captureOneTimePayment(request.payerId, request.paymentId,
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent)))
.thenApply(chargeSuccessDetails -> {
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now());
return Response.ok(
new ConfirmPayPalBoostResponse(chargeSuccessDetails.paymentId())).build();
});
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails = braintreeManager.captureOneTimePayment(
request.payerId, request.paymentId,
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent));
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now());
return new ConfirmPayPalBoostResponse(chargeSuccessDetails.paymentId());
}
public static class CreateBoostReceiptCredentialsRequest {
@@ -339,77 +339,76 @@ public class OneTimeDonationController {
@Path("/receipt_credentials")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createBoostReceiptCredentials(
@ManagedAsync
public Response createBoostReceiptCredentials(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final CreateBoostReceiptCredentialsRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws IOException {
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
final CompletableFuture<Optional<PaymentDetails>> paymentDetailsFut = switch (request.processor) {
final Optional<PaymentDetails> maybePaymentDetails = (switch (request.processor) {
case STRIPE -> stripeManager.getPaymentDetails(request.paymentIntentId);
case BRAINTREE -> braintreeManager.getPaymentDetails(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");
};
return paymentDetailsFut.thenApply(maybePaymentDetails -> {
if (maybePaymentDetails.isEmpty()) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
final PaymentDetails paymentDetails = maybePaymentDetails.get();
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
return Response.noContent().build();
}
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
}
// The payment was successful, try to issue the receipt credential
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
try {
levelDetails = OneTimeDonationUtil.getLevelDetails(paymentDetails, oneTimeDonationConfiguration);
} catch (OneTimeDonationUtil.InvalidLevelException _) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
final ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
} catch (final InvalidInputException e) {
throw new BadRequestException("invalid receipt credential request", e);
}
try {
issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
receiptCredentialRequest, clock.instant());
} catch (WriteConflictException _) {
throw new WebApplicationException(Response.Status.CONFLICT);
}
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
final Instant expiration = paidAt
.plus(levelDetails.levelExpiration())
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
final ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
} catch (final VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
Metrics.counter(SubscriptionController.RECEIPT_ISSUED_COUNTER_NAME,
Tags.of(
Tag.of(SubscriptionController.PROCESSOR_TAG_NAME, request.processor.toString()),
Tag.of(SubscriptionController.TYPE_TAG_NAME, "boost"),
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
return Response.ok(
new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize()))
.build();
});
if (maybePaymentDetails.isEmpty()) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
final PaymentDetails paymentDetails = maybePaymentDetails.get();
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
return Response.noContent().build();
}
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
}
// The payment was successful, try to issue the receipt credential
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
try {
levelDetails = OneTimeDonationUtil.getLevelDetails(paymentDetails, oneTimeDonationConfiguration);
} catch (OneTimeDonationUtil.InvalidLevelException _) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
final ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
} catch (final InvalidInputException e) {
throw new BadRequestException("invalid receipt credential request", e);
}
try {
issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
receiptCredentialRequest, clock.instant());
} catch (WriteConflictException _) {
throw new WebApplicationException(Response.Status.CONFLICT);
}
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
final Instant expiration = paidAt
.plus(levelDetails.levelExpiration())
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
final ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
} catch (final VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
Metrics.counter(SubscriptionController.RECEIPT_ISSUED_COUNTER_NAME,
Tags.of(
Tag.of(SubscriptionController.PROCESSOR_TAG_NAME, request.processor.toString()),
Tag.of(SubscriptionController.TYPE_TAG_NAME, "boost"),
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
return Response.ok(
new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize()))
.build();
}
}
@@ -48,6 +48,8 @@ import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Instant;
@@ -311,7 +313,8 @@ public class SubscriptionController {
@PathParam("subscriberId") String subscriberId,
@NotNull @Valid CreatePayPalBillingAgreementRequest request,
@Context ContainerRequestContext containerRequestContext,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws SubscriptionException {
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString)
throws SubscriptionException, IOException {
final SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
@@ -321,10 +324,8 @@ public class SubscriptionController {
subscriberCredentials,
braintreeManager,
getClientPlatform(userAgentString),
(mgr, customerId) ->
mgr.createPayPalBillingAgreement(request.returnUrl, request.cancelUrl, locale.toLanguageTag()))
.join();
return new CreatePayPalBillingAgreementResponse(
(mgr, _) -> mgr.createPayPalBillingAgreement(request.returnUrl, request.cancelUrl, locale.toLanguageTag()));
return new CreatePayPalBillingAgreementResponse(
billingAgreementApprovalDetails.approvalUrl(),
billingAgreementApprovalDetails.billingAgreementToken());
}
@@ -346,7 +347,7 @@ public class SubscriptionController {
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("processor") PaymentProvider processor,
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws SubscriptionException {
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws SubscriptionException, IOException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
@@ -750,18 +751,18 @@ public class SubscriptionController {
public Response setDefaultPaymentMethodForIdeal(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws SubscriptionException {
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws SubscriptionException, IOException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
final String generatedSepaId = stripeManager.getGeneratedSepaIdFromSetupIntent(setupIntentId).join();
final String generatedSepaId = stripeManager.getGeneratedSepaIdFromSetupIntent(setupIntentId);
setDefaultPaymentMethod(stripeManager, generatedSepaId, subscriberCredentials);
return Response.ok().build();
}
private void setDefaultPaymentMethod(final CustomerAwareSubscriptionPaymentProcessor manager,
final String paymentMethodId,
final SubscriberCredentials requestData) throws SubscriptionException {
final SubscriberCredentials requestData) throws SubscriptionException, IOException {
try {
final Subscriptions.Record record = subscriptionManager.getSubscriber(requestData);
@@ -772,7 +773,7 @@ public class SubscriptionController {
manager
.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, record.subscriptionId);
} catch (SubscriptionInvalidArgumentsException e) {
} catch (final SubscriptionInvalidArgumentsException 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);
@@ -8,6 +8,7 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientP
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.toChargeFailure;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Instant;
@@ -53,6 +54,8 @@ 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.SubscriptionInvalidAmountException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneTimeDonationsImplBase {
@@ -91,7 +94,8 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
}
@Override
public CreateBoostResponse createBoost(final CreateBoostRequest request) throws RateLimitExceededException {
public CreateBoostResponse createBoost(final CreateBoostRequest request)
throws RateLimitExceededException {
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
try {
@@ -144,16 +148,23 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
.setAmountAboveSepaLimit(AmountAboveSepaLimitError.newBuilder()
.setMaximum(r.maximum().toString()).build()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent(
request.getCurrency(), request.getAmount(), request.getLevel(),
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))).join();
yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build();
try {
final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent(
request.getCurrency(), request.getAmount(), request.getLevel(),
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build();
} catch (final SubscriptionInvalidAmountException e) {
yield CreateBoostResponse.newBuilder()
.setInvalidAmount(FailedPrecondition.newBuilder()
.setDescription(e.getErrorCode()).build())
.build();
}
}
};
}
@Override
public CreatePayPalBoostResponse createPayPalBoost(final CreatePayPalBoostRequest request) {
public CreatePayPalBoostResponse createPayPalBoost(final CreatePayPalBoostRequest request) throws IOException {
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
OneTimeDonationUtil.validateOneTimeDonationRequest(
@@ -185,7 +196,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
braintreeManager.createOneTimePayment(
request.getCurrency().toUpperCase(Locale.ROOT), request.getAmount(),
localizedLineItem.locale().toLanguageTag(), request.getReturnUrl(), request.getCancelUrl(),
localizedLineItem.itemName()).join();
localizedLineItem.itemName());
yield CreatePayPalBoostResponse.newBuilder()
.setResult(CreatePayPalBoostResponse.CreatePayPalBoostResult.newBuilder()
.setApprovalUrl(approvalDetails.approvalUrl())
@@ -196,7 +207,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
@Override
public ConfirmPayPalBoostResponse confirmPayPalBoost(final ConfirmPayPalBoostRequest request)
throws RateLimitExceededException {
throws RateLimitExceededException, IOException {
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
@@ -222,33 +233,39 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails =
braintreeManager.captureOneTimePayment(
request.getPayerId(), request.getPaymentId(), request.getPaymentToken(),
request.getCurrency(), request.getAmount(), request.getLevel(),
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))).join();
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails;
try {
chargeSuccessDetails = braintreeManager.captureOneTimePayment(
request.getPayerId(), request.getPaymentId(), request.getPaymentToken(),
request.getCurrency(), request.getAmount(), request.getLevel(),
SubscriptionsUtil.getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), clock.instant());
yield ConfirmPayPalBoostResponse.newBuilder()
.setResult(ConfirmPayPalBoostResponse.ConfirmPayPalBoostResult.newBuilder()
.setPaymentId(chargeSuccessDetails.paymentId()).build()).build();
} catch (final SubscriptionProcessorException e) {
yield ConfirmPayPalBoostResponse.newBuilder()
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure()))
.build();
}
}
};
}
@Override
public CreateBoostReceiptCredentialsResponse createBoostReceiptCredentials(
final CreateBoostReceiptCredentialsRequest request) {
final CreateBoostReceiptCredentialsRequest request) throws IOException {
final PaymentProvider processor;
final Optional<PaymentDetails> maybePaymentDetails;
switch (request.getProcessor()) {
case PAYMENT_PROVIDER_STRIPE -> {
processor = PaymentProvider.STRIPE;
maybePaymentDetails = stripeManager.getPaymentDetails(request.getPaymentIntentId()).join();
maybePaymentDetails = stripeManager.getPaymentDetails(request.getPaymentIntentId());
}
case PAYMENT_PROVIDER_BRAINTREE -> {
processor = PaymentProvider.BRAINTREE;
maybePaymentDetails = braintreeManager.getPaymentDetails(request.getPaymentIntentId()).join();
maybePaymentDetails = braintreeManager.getPaymentDetails(request.getPaymentIntentId());
}
default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor");
}
@@ -5,12 +5,14 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getPayPalL
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Clock;
import java.util.Locale;
import java.util.Optional;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.FailedZkAuthentication;
@@ -216,7 +218,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
}
@Override
public CreatePayPalPaymentMethodResponse createPayPalPaymentMethod(final CreatePayPalPaymentMethodRequest request) {
public CreatePayPalPaymentMethodResponse createPayPalPaymentMethod(final CreatePayPalPaymentMethodRequest request)
throws IOException {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
final Locale locale = getPayPalLocale(RequestAttributesUtil.getAvailableAcceptedLocales());
@@ -224,7 +227,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
final BraintreeManager.PayPalBillingAgreementApprovalDetails details = subscriptionManager.addPaymentMethodToCustomer(
subscriberCredentials, braintreeManager, getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)),
(mgr, _) -> mgr.createPayPalBillingAgreement(request.getReturnUrl(), request.getCancelUrl(),
locale.toLanguageTag())).join();
locale.toLanguageTag()));
return CreatePayPalPaymentMethodResponse.newBuilder().setResult(
CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder()
.setApprovalUrl(details.approvalUrl()).setToken(details.billingAgreementToken()).build()).build();
@@ -241,27 +244,28 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
}
@Override
public SetDefaultPaymentMethodResponse setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest request) {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
final CustomerAwareSubscriptionPaymentProcessor manager;
final String paymentMethodId = switch (request.getRequestCase()) {
case STRIPE -> {
manager = stripeManager;
yield request.getStripe().getPaymentMethodToken();
}
case BRAINTREE -> {
manager = braintreeManager;
yield request.getBraintree().getPaymentMethodToken();
}
case SEPA -> {
manager = stripeManager;
yield stripeManager.getGeneratedSepaIdFromSetupIntent(request.getSepa().getSetupIntentId()).join();
}
default -> throw GrpcExceptions.fieldViolation("request", "No payment method specified");
};
public SetDefaultPaymentMethodResponse setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest request)
throws IOException {
try {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
final CustomerAwareSubscriptionPaymentProcessor manager;
final String paymentMethodId = switch (request.getRequestCase()) {
case STRIPE -> {
manager = stripeManager;
yield request.getStripe().getPaymentMethodToken();
}
case BRAINTREE -> {
manager = braintreeManager;
yield request.getBraintree().getPaymentMethodToken();
}
case SEPA -> {
manager = stripeManager;
yield stripeManager.getGeneratedSepaIdFromSetupIntent(request.getSepa().getSetupIntentId());
}
default -> throw GrpcExceptions.fieldViolation("request", "No payment method specified");
};
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
return record.getProcessorCustomer().map(
processorCustomer -> setDefaultPaymentMethodForCustomer(manager, processorCustomer, paymentMethodId,
@@ -275,6 +279,10 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
} catch (final SubscriptionForbiddenException e) {
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionProcessorConflictException e) {
return SetDefaultPaymentMethodResponse.newBuilder()
.setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
@@ -290,6 +298,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
return SetDefaultPaymentMethodResponse.newBuilder()
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
.build();
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
@@ -41,6 +41,7 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConfl
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.util.ThrowingBiFunction;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
/**
@@ -244,6 +245,7 @@ public class SubscriptionManager {
* @param <T> A payment processor that has a notion of server-managed customers
* @param <R> The return type of the paymentSetupFunction, which should be used by a client
* to configure the newly created payment method
* @param <E> 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 or did not have a subscription
@@ -251,12 +253,12 @@ public class SubscriptionManager {
* @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with
* the subscriberId
*/
public <T extends CustomerAwareSubscriptionPaymentProcessor, R> R addPaymentMethodToCustomer(
public <T extends CustomerAwareSubscriptionPaymentProcessor, R, E extends Exception> R addPaymentMethodToCustomer(
final SubscriberCredentials subscriberCredentials,
final T subscriptionPaymentProcessor,
final ClientPlatform clientPlatform,
final BiFunction<T, String, R> paymentSetupFunction)
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException {
final ThrowingBiFunction<T, String, R, E> paymentSetupFunction)
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException, E {
Subscriptions.Record record = this.getSubscriber(subscriberCredentials);
if (record.getProcessorCustomer().isEmpty()) {
@@ -36,7 +36,7 @@ import com.braintree.graphql.clientoperation.CreatePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.TokenizePayPalBillingAgreementMutation;
import com.braintree.graphql.clientoperation.TokenizePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.VaultPaymentMethodMutation;
import jakarta.ws.rs.ServiceUnavailableException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
@@ -44,7 +44,6 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -69,7 +68,7 @@ class BraintreeGraphqlClient {
this.httpClient = httpClient;
try {
this.graphqlUri = new URI(graphqlUri);
} catch (URISyntaxException e) {
} catch (final URISyntaxException e) {
throw new IllegalArgumentException("Invalid URI", e);
}
// “public”/“private” key is a bit of a misnomer, but we follow the upstream nomenclature
@@ -77,36 +76,32 @@ class BraintreeGraphqlClient {
this.authorizationHeader = "Basic " + Base64.getEncoder().encodeToString((publicKey + ":" + privateKey).getBytes());
}
CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> createPayPalOneTimePayment(
CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment createPayPalOneTimePayment(
final BigDecimal amount, final String currency, final String returnUrl,
final String cancelUrl, final String locale, final String localizedLineItemName) {
final String cancelUrl, final String locale, final String localizedLineItemName) throws IOException {
final CreatePayPalOneTimePaymentInput input = buildCreatePayPalOneTimePaymentInput(amount, currency, returnUrl,
cancelUrl, locale, localizedLineItemName);
final CreatePayPalOneTimePaymentMutation mutation = new CreatePayPalOneTimePaymentMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse ->
{
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final ApolloResponse<CreatePayPalOneTimePaymentMutation.Data> apolloResponse =
extractApolloResponse(httpResponse, mutation);
final CreatePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractDataFromApolloResponse(apolloResponse);
if (data.createPayPalOneTimePayment == null) {
logger.warn(
"createPayPalOneTimePayment requestId={} currency={} amount={} did not have any errors but data was null. response={}",
apolloResponse.extensions.getOrDefault("requestId", "<No-Request-Id>"),
currency, amount, httpResponse.body());
throw new ServiceUnavailableException();
}
return data.createPayPalOneTimePayment;
});
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
final ApolloResponse<CreatePayPalOneTimePaymentMutation.Data> apolloResponse =
extractApolloResponse(httpResponse, mutation);
final CreatePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractDataFromApolloResponse(apolloResponse);
if (data.createPayPalOneTimePayment == null) {
logger.warn(
"createPayPalOneTimePayment requestId={} currency={} amount={} did not have any errors but data was null. response={}",
apolloResponse.extensions.getOrDefault("requestId", "<No-Request-Id>"),
currency, amount, httpResponse.body());
throw new IOException();
}
return data.createPayPalOneTimePayment;
}
private static CreatePayPalOneTimePaymentInput buildCreatePayPalOneTimePaymentInput(BigDecimal amount,
String currency, String returnUrl, String cancelUrl, String locale, String localizedLineItemName) {
private static CreatePayPalOneTimePaymentInput buildCreatePayPalOneTimePaymentInput(final BigDecimal amount,
final String currency, final String returnUrl, final String cancelUrl, final String locale, final String localizedLineItemName) {
// Note locale and localizedLineItemName are a best-effort, and it's possible that they will not match.
// We could try to align with the locales PayPal documents <https://developer.paypal.com/reference/locale-codes/#supported-locale-codes>
@@ -148,8 +143,8 @@ class BraintreeGraphqlClient {
);
}
CompletableFuture<TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment> tokenizePayPalOneTimePayment(
final String payerId, final String paymentId, final String paymentToken) {
TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment tokenizePayPalOneTimePayment(
final String payerId, final String paymentId, final String paymentToken) throws IOException {
final TokenizePayPalOneTimePaymentInput input = new TokenizePayPalOneTimePaymentInput(
Optional.absent(),
@@ -159,18 +154,15 @@ class BraintreeGraphqlClient {
final TokenizePayPalOneTimePaymentMutation mutation = new TokenizePayPalOneTimePaymentMutation(input);
final HttpRequest request = buildRequest(mutation);
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final TokenizePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.tokenizePayPalOneTimePayment;
});
final TokenizePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.tokenizePayPalOneTimePayment;
}
CompletableFuture<ChargePayPalOneTimePaymentMutation.ChargePaymentMethod> chargeOneTimePayment(
final String paymentMethodId, final BigDecimal amount, final String merchantAccount, final long level) {
ChargePayPalOneTimePaymentMutation.ChargePaymentMethod chargeOneTimePayment(
final String paymentMethodId, final BigDecimal amount, final String merchantAccount, final long level)
throws IOException {
final List<CustomFieldInput> customFields = List.of(
new CustomFieldInput("level", Optional.present(Long.toString(level))));
@@ -180,18 +172,14 @@ class BraintreeGraphqlClient {
final ChargePayPalOneTimePaymentMutation mutation = new ChargePayPalOneTimePaymentMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final ChargePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse,
mutation);
return data.chargePaymentMethod;
});
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
final ChargePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse,
mutation);
return data.chargePaymentMethod;
}
private static ChargePaymentMethodInput buildChargePaymentMethodInput(String paymentMethodId, BigDecimal amount,
String merchantAccount, List<CustomFieldInput> customFields) {
private static ChargePaymentMethodInput buildChargePaymentMethodInput(final String paymentMethodId, final BigDecimal amount,
final String merchantAccount, final List<CustomFieldInput> customFields) {
return new ChargePaymentMethodInput(
Optional.absent(),
@@ -221,25 +209,21 @@ class BraintreeGraphqlClient {
);
}
public CompletableFuture<CreatePayPalBillingAgreementMutation.CreatePayPalBillingAgreement> createPayPalBillingAgreement(
final String returnUrl, final String cancelUrl, final String locale) {
public CreatePayPalBillingAgreementMutation.CreatePayPalBillingAgreement createPayPalBillingAgreement(
final String returnUrl, final String cancelUrl, final String locale) throws IOException {
final CreatePayPalBillingAgreementInput input = buildCreatePayPalBillingAgreementInput(returnUrl, cancelUrl,
locale);
final CreatePayPalBillingAgreementMutation mutation = new CreatePayPalBillingAgreementMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final CreatePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.createPayPalBillingAgreement;
});
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
final CreatePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.createPayPalBillingAgreement;
}
private static CreatePayPalBillingAgreementInput buildCreatePayPalBillingAgreementInput(String returnUrl,
String cancelUrl, String locale) {
private static CreatePayPalBillingAgreementInput buildCreatePayPalBillingAgreementInput(final String returnUrl,
final String cancelUrl, final String locale) {
return new CreatePayPalBillingAgreementInput(
Optional.absent(),
@@ -263,8 +247,8 @@ class BraintreeGraphqlClient {
);
}
public CompletableFuture<TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement> tokenizePayPalBillingAgreement(
final String billingAgreementToken) {
public TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement tokenizePayPalBillingAgreement(
final String billingAgreementToken) throws IOException {
final TokenizePayPalBillingAgreementInput input = new TokenizePayPalBillingAgreementInput(
Optional.absent(),
@@ -272,32 +256,24 @@ class BraintreeGraphqlClient {
final TokenizePayPalBillingAgreementMutation mutation = new TokenizePayPalBillingAgreementMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final TokenizePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.tokenizePayPalBillingAgreement;
});
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
final TokenizePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.tokenizePayPalBillingAgreement;
}
public CompletableFuture<VaultPaymentMethodMutation.VaultPaymentMethod> vaultPaymentMethod(final String customerId,
final String paymentMethodId) {
public VaultPaymentMethodMutation.VaultPaymentMethod vaultPaymentMethod(final String customerId,
final String paymentMethodId) throws IOException {
final VaultPaymentMethodInput input = buildVaultPaymentMethodInput(customerId, paymentMethodId);
final VaultPaymentMethodMutation mutation = new VaultPaymentMethodMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final VaultPaymentMethodMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.vaultPaymentMethod;
});
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
final VaultPaymentMethodMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.vaultPaymentMethod;
}
private static VaultPaymentMethodInput buildVaultPaymentMethodInput(String customerId, String paymentMethodId) {
private static VaultPaymentMethodInput buildVaultPaymentMethodInput(final String customerId, final String paymentMethodId) {
return new VaultPaymentMethodInput(
Optional.absent(),
paymentMethodId,
@@ -311,26 +287,28 @@ class BraintreeGraphqlClient {
/**
* Verifies that the HTTP response has a {@code 200} status code and the GraphQL response has no errors, otherwise
* throws a {@link ServiceUnavailableException}.
* throws a {@link IOException}.
*/
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractData(
HttpResponse<String> httpResponse, T operation) {
final HttpResponse<String> httpResponse, final T operation) throws IOException {
return assertSuccessAndExtractDataFromApolloResponse(extractApolloResponse(httpResponse, operation));
}
private static <T extends Operation<U>, U extends Operation.Data> ApolloResponse<U> extractApolloResponse(
HttpResponse<String> httpResponse, T operation) {
final HttpResponse<String> httpResponse, final T operation) throws IOException {
if (httpResponse.statusCode() != 200) {
logger.warn("Received HTTP response status {} ({})", httpResponse.statusCode(),
httpResponse.headers().firstValue("paypal-debug-id").orElse("<debug id absent>"));
throw new ServiceUnavailableException();
throw new IOException();
}
return Operations.parseJsonResponse(operation, httpResponse.body());
}
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractDataFromApolloResponse(final ApolloResponse<U> response) {
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractDataFromApolloResponse(
final ApolloResponse<U> response)
throws IOException {
if (response.hasErrors() || response.data == null) {
//noinspection ConstantConditions
response.errors.forEach(
@@ -342,7 +320,7 @@ class BraintreeGraphqlClient {
response.operation.name(), error.getMessage(), legacyCode);
});
throw new ServiceUnavailableException();
throw new IOException();
}
return response.data;
@@ -5,7 +5,11 @@
package org.whispersystems.textsecuregcm.subscriptions;
import com.braintree.graphql.clientoperation.ChargePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.CreatePayPalBillingAgreementMutation;
import com.braintree.graphql.clientoperation.CreatePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.TokenizePayPalBillingAgreementMutation;
import com.braintree.graphql.clientoperation.TokenizePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.VaultPaymentMethodMutation;
import com.braintreegateway.BraintreeGateway;
import com.braintreegateway.ClientTokenRequest;
@@ -36,7 +40,6 @@ import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import javax.annotation.Nullable;
import org.slf4j.Logger;
@@ -45,7 +48,6 @@ 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.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
import org.whispersystems.textsecuregcm.util.GoogleApiUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -128,92 +130,88 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return paymentMethod == PaymentMethod.PAYPAL;
}
public CompletableFuture<Optional<PaymentDetails>> getPaymentDetails(final String paymentId) {
return CompletableFuture.supplyAsync(() -> {
try {
final Transaction transaction = braintreeGateway.transaction().find(paymentId);
ChargeFailure chargeFailure = null;
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
chargeFailure = createChargeFailure(transaction);
}
return Optional.of(new PaymentDetails(transaction.getGraphQLId(),
transaction.getCustomFields(),
getPaymentStatus(transaction.getStatus()),
transaction.getCreatedAt().toInstant(),
chargeFailure));
} catch (final NotFoundException e) {
return Optional.empty();
public Optional<PaymentDetails> getPaymentDetails(final String paymentId) {
try {
final Transaction transaction = braintreeGateway.transaction().find(paymentId);
ChargeFailure chargeFailure = null;
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
chargeFailure = createChargeFailure(transaction);
}
}, executor);
return Optional.of(new PaymentDetails(transaction.getGraphQLId(),
transaction.getCustomFields(),
getPaymentStatus(transaction.getStatus()),
transaction.getCreatedAt().toInstant(),
chargeFailure));
} catch (final NotFoundException e) {
return Optional.empty();
}
}
public CompletableFuture<PayPalOneTimePaymentApprovalDetails> createOneTimePayment(String currency, long amount,
String locale, String returnUrl, String cancelUrl, String localizedLineItemname) {
return braintreeGraphqlClient.createPayPalOneTimePayment(convertApiAmountToBraintreeAmount(currency, amount),
currency.toUpperCase(Locale.ROOT), returnUrl,
cancelUrl, locale, localizedLineItemname)
.thenApply(result -> new PayPalOneTimePaymentApprovalDetails((String) result.approvalUrl, result.paymentId));
public PayPalOneTimePaymentApprovalDetails createOneTimePayment(final String currency, final long amount,
final String locale, final String returnUrl, final String cancelUrl, final String localizedLineItemName) throws IOException {
final CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment result = braintreeGraphqlClient.createPayPalOneTimePayment(
convertApiAmountToBraintreeAmount(currency, amount),
currency.toUpperCase(Locale.ROOT), returnUrl,
cancelUrl, locale, localizedLineItemName);
return new PayPalOneTimePaymentApprovalDetails((String) result.approvalUrl, result.paymentId);
}
public CompletableFuture<PayPalChargeSuccessDetails> captureOneTimePayment(String payerId, String paymentId,
String paymentToken, String currency, long amount, long level, @Nullable ClientPlatform clientPlatform) {
return braintreeGraphqlClient.tokenizePayPalOneTimePayment(payerId, paymentId, paymentToken)
.thenCompose(response -> braintreeGraphqlClient.chargeOneTimePayment(
response.paymentMethod.id,
convertApiAmountToBraintreeAmount(currency, amount),
currenciesToMerchantAccounts.get(currency.toLowerCase(Locale.ROOT)),
level)
.thenComposeAsync(chargeResponse -> {
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 {
final TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment response = braintreeGraphqlClient.tokenizePayPalOneTimePayment(
payerId, paymentId, paymentToken);
final ChargePayPalOneTimePaymentMutation.ChargePaymentMethod chargeResponse = braintreeGraphqlClient.chargeOneTimePayment(
response.paymentMethod.id,
convertApiAmountToBraintreeAmount(currency, amount),
currenciesToMerchantAccounts.get(currency.toLowerCase(Locale.ROOT)),
level);
final PaymentStatus paymentStatus = getPaymentStatus(chargeResponse.transaction.status);
if (paymentStatus == PaymentStatus.SUCCEEDED || paymentStatus == PaymentStatus.PROCESSING) {
publishDonationEvent(amount, currency, Instant.now(), clientPlatform);
return CompletableFuture.completedFuture(new PayPalChargeSuccessDetails(chargeResponse.transaction.id));
}
final PaymentStatus paymentStatus = getPaymentStatus(chargeResponse.transaction.status);
if (paymentStatus == PaymentStatus.SUCCEEDED || paymentStatus == PaymentStatus.PROCESSING) {
publishDonationEvent(amount, currency, Instant.now(), clientPlatform);
return new PayPalChargeSuccessDetails(chargeResponse.transaction.id);
}
// the GraphQL/Apollo interfaces are a tad unwieldy for this type of status checking
final Transaction unsuccessfulTx = braintreeGateway.transaction().find(chargeResponse.transaction.id);
// the GraphQL/Apollo interfaces are a tad unwieldy for this type of status checking
final Transaction unsuccessfulTx = braintreeGateway.transaction().find(chargeResponse.transaction.id);
if (PAYPAL_PAYMENT_ALREADY_COMPLETED_PROCESSOR_CODE.equals(unsuccessfulTx.getProcessorResponseCode())
|| Transaction.GatewayRejectionReason.DUPLICATE.equals(unsuccessfulTx.getGatewayRejectionReason())) {
// the payment has already been charged - maybe a previous call timed out or was interrupted -
// in any case, check for a successful transaction with the paymentId
final ResourceCollection<Transaction> search = braintreeGateway.transaction()
.search(new TransactionSearchRequest()
.paypalPaymentId().is(paymentId)
.status().in(
Transaction.Status.SETTLED,
Transaction.Status.SETTLING,
Transaction.Status.SUBMITTED_FOR_SETTLEMENT,
Transaction.Status.SETTLEMENT_PENDING
)
);
if (PAYPAL_PAYMENT_ALREADY_COMPLETED_PROCESSOR_CODE.equals(unsuccessfulTx.getProcessorResponseCode())
|| Transaction.GatewayRejectionReason.DUPLICATE.equals(unsuccessfulTx.getGatewayRejectionReason())) {
// the payment has already been charged - maybe a previous call timed out or was interrupted -
// in any case, check for a successful transaction with the paymentId
final ResourceCollection<Transaction> search = braintreeGateway.transaction()
.search(new TransactionSearchRequest()
.paypalPaymentId().is(paymentId)
.status().in(
Transaction.Status.SETTLED,
Transaction.Status.SETTLING,
Transaction.Status.SUBMITTED_FOR_SETTLEMENT,
Transaction.Status.SETTLEMENT_PENDING
)
);
if (search.getMaximumSize() == 0) {
return CompletableFuture.failedFuture(ExceptionUtils.wrap(new IOException()));
}
if (search.getMaximumSize() == 0) {
throw new IOException();
}
final Transaction successfulTx = search.getFirst();
final Transaction successfulTx = search.getFirst();
publishDonationEvent(amount, currency, successfulTx.getCreatedAt().toInstant(), clientPlatform);
publishDonationEvent(amount, currency, successfulTx.getCreatedAt().toInstant(), clientPlatform);
return CompletableFuture.completedFuture(
new PayPalChargeSuccessDetails(successfulTx.getGraphQLId()));
}
return new PayPalChargeSuccessDetails(successfulTx.getGraphQLId());
}
return switch (unsuccessfulTx.getProcessorResponseCode()) {
case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE ->
CompletableFuture.failedFuture(
new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx)));
switch (unsuccessfulTx.getProcessorResponseCode()) {
case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE ->
throw new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx));
default -> {
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
yield CompletableFuture.failedFuture(ExceptionUtils.wrap(new IOException()));
}
};
}, executor));
default -> {
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
throw new IOException();
}
}
}
private void publishDonationEvent(final long amount,
@@ -264,7 +262,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return amount.multiply(ONE_MILLION).longValueExact();
}
private static PaymentStatus getPaymentStatus(Transaction.Status status) {
private static PaymentStatus getPaymentStatus(final Transaction.Status status) {
return switch (status) {
case SETTLEMENT_CONFIRMED, SETTLING, SUBMITTED_FOR_SETTLEMENT, SETTLED -> PaymentStatus.SUCCEEDED;
case AUTHORIZATION_EXPIRED, GATEWAY_REJECTED, PROCESSOR_DECLINED, SETTLEMENT_DECLINED, VOIDED, FAILED ->
@@ -273,9 +271,9 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
};
}
private static PaymentStatus getPaymentStatus(com.braintree.graphql.client.type.PaymentStatus status) {
private static PaymentStatus getPaymentStatus(final com.braintree.graphql.client.type.PaymentStatus status) {
try {
Transaction.Status transactionStatus = Transaction.Status.valueOf(status.rawValue);
final Transaction.Status transactionStatus = Transaction.Status.valueOf(status.rawValue);
return getPaymentStatus(transactionStatus);
} catch (final Exception e) {
@@ -283,7 +281,8 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
}
}
private static SubscriptionStatus getSubscriptionStatus(final Subscription.Status status, final boolean latestTransactionFailed) {
private static SubscriptionStatus getSubscriptionStatus(final Subscription.Status status,
final boolean latestTransactionFailed) {
return switch (status) {
// Stripe returns a PAST_DUE status if the subscription's most recent payment failed.
// This check ensures that Braintree is consistent with Stripe.
@@ -316,7 +315,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
@Override
public ProcessorCustomer createCustomer(final byte[] subscriberUser, @Nullable final ClientPlatform clientPlatform) {
CustomerRequest request = new CustomerRequest()
final CustomerRequest request = new CustomerRequest()
.customField("subscriber_user", HexFormat.of().formatHex(subscriberUser));
if (clientPlatform != null) {
@@ -332,19 +331,19 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
@Override
public String createPaymentMethodSetupToken(final String customerId) {
ClientTokenRequest request = new ClientTokenRequest().customerId(customerId);
final ClientTokenRequest request = new ClientTokenRequest().customerId(customerId);
return braintreeGateway.clientToken().generate(request);
}
@Override
public void setDefaultPaymentMethodForCustomer(String customerId, String billingAgreementToken,
@Nullable String currentSubscriptionId) {
public void setDefaultPaymentMethodForCustomer(final String customerId, final String billingAgreementToken,
@Nullable final String currentSubscriptionId) throws IOException {
final Optional<String> maybeSubscriptionId = Optional.ofNullable(currentSubscriptionId);
final TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement tokenizePayPalBillingAgreement =
braintreeGraphqlClient.tokenizePayPalBillingAgreement(billingAgreementToken).join();
braintreeGraphqlClient.tokenizePayPalBillingAgreement(billingAgreementToken);
final VaultPaymentMethodMutation.VaultPaymentMethod vaultPaymentMethod =
braintreeGraphqlClient.vaultPaymentMethod(customerId, tokenizePayPalBillingAgreement.paymentMethod.id).join();
braintreeGraphqlClient.vaultPaymentMethod(customerId, tokenizePayPalBillingAgreement.paymentMethod.id);
final Result<Customer> result = braintreeGateway.customer()
.update(customerId, new CustomerRequest().defaultPaymentMethodToken(vaultPaymentMethod.paymentMethod.id));
maybeSubscriptionId.ifPresent(subscriptionId ->
@@ -353,13 +352,13 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
}
@Override
public Object getSubscription(String subscriptionId) {
public Object getSubscription(final String subscriptionId) {
return braintreeGateway.subscription().find(subscriptionId);
}
@Override
public SubscriptionId createSubscription(String customerId, String planId, long level,
long lastSubscriptionCreatedAt)
public SubscriptionId createSubscription(final String customerId, final String planId, final long level,
final long lastSubscriptionCreatedAt)
throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
final com.braintreegateway.PaymentMethod paymentMethod = getDefaultPaymentMethod(customerId);
@@ -406,14 +405,15 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return new SubscriptionId(result.getTarget().getId());
}
private com.braintreegateway.PaymentMethod getDefaultPaymentMethod(String customerId) {
private com.braintreegateway.PaymentMethod getDefaultPaymentMethod(final String customerId) {
return braintreeGateway.customer().find(customerId).getDefaultPaymentMethod();
}
@Override
public CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updateSubscription(Object subscriptionObj, String planId, long level,
String idempotencyKey) throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
public CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updateSubscription(final Object subscriptionObj,
final String planId, final long level,
final String idempotencyKey) throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
if (!(subscriptionObj instanceof final Subscription subscription)) {
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
@@ -425,7 +425,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
endSubscription(subscription);
final Transaction transaction = getLatestTransactionForSubscription(subscription)
.orElseThrow(() -> ExceptionUtils.wrap(new SubscriptionProcessorConflictException()));
.orElseThrow(SubscriptionProcessorConflictException::new);
final Customer customer = transaction.getCustomer();
@@ -434,13 +434,13 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
}
@Override
public LevelAndCurrency getLevelAndCurrencyForSubscription(Object subscriptionObj) {
public LevelAndCurrency getLevelAndCurrencyForSubscription(final Object subscriptionObj) {
final Subscription subscription = getSubscription(subscriptionObj);
final Plan plan = findPlan(subscription.getPlanId());
return new LevelAndCurrency(getLevelForPlan(plan), plan.getCurrencyIsoCode().toLowerCase(Locale.ROOT));
}
private Plan findPlan(String planId) {
private Plan findPlan(final String planId) {
return braintreeGateway.plan().find(planId);
}
@@ -449,7 +449,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
try {
metadata = SystemMapper.jsonMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
} catch (JsonProcessingException e) {
} catch (final JsonProcessingException e) {
throw new RuntimeException(e);
}
@@ -458,7 +458,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
@Override
public SubscriptionInformation getSubscriptionInformation(final String subscriptionId) {
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
final Plan plan = braintreeGateway.plan().find(subscription.getPlanId());
final long level = getLevelForPlan(plan);
@@ -500,11 +500,12 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return new TransactionInfo(paymentMethod, paymentProcessing, false, null);
}
private PaymentMethod getPaymentMethodFromTransaction(Transaction transaction) {
private PaymentMethod getPaymentMethodFromTransaction(final Transaction transaction) {
if (transaction.getPayPalDetails() != null) {
return PaymentMethod.PAYPAL;
}
logger.error("Unexpected payment method from Braintree: {}, transaction id {}", transaction.getPaymentInstrumentType(), transaction.getId());
logger.error("Unexpected payment method from Braintree: {}, transaction id {}",
transaction.getPaymentInstrumentType(), transaction.getId());
return PaymentMethod.UNKNOWN;
}
@@ -512,7 +513,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return status == Transaction.Status.SETTLEMENT_PENDING;
}
private ChargeFailure createChargeFailure(Transaction transaction) {
private ChargeFailure createChargeFailure(final Transaction transaction) {
final String code;
final String message;
@@ -539,7 +540,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
}
@Override
public void cancelAllActiveSubscriptions(String customerId) {
public void cancelAllActiveSubscriptions(final String customerId) {
final Customer customer = braintreeGateway.customer().find(customerId);
ExecutorUtil.runAll(executor, Optional.ofNullable(customer.getDefaultPaymentMethod())
.stream()
@@ -548,7 +549,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
.toList());
}
private void endSubscription(Subscription subscription) {
private void endSubscription(final Subscription subscription) {
final boolean latestTransactionFailed = getLatestTransactionForSubscription(subscription)
.map(this::getTransactionInfo)
.map(TransactionInfo::transactionFailed)
@@ -563,20 +564,20 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
}
}
private void cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
private void cancelSubscriptionAtEndOfCurrentPeriod(final Subscription subscription) {
braintreeGateway
.subscription()
.update(subscription.getId(),
new SubscriptionRequest().numberOfBillingCycles(subscription.getCurrentBillingCycle()));
}
private void cancelSubscriptionImmediately(Subscription subscription) {
private void cancelSubscriptionImmediately(final Subscription subscription) {
braintreeGateway.subscription().cancel(subscription.getId());
}
@Override
public ReceiptItem getReceiptItem(String subscriptionId)
public ReceiptItem getReceiptItem(final String subscriptionId)
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionChargeFailurePaymentRequiredException {
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
final Transaction transaction = getLatestTransactionForSubscription(subscription)
@@ -597,31 +598,31 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
try {
metadata = SystemMapper.jsonMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
} catch (JsonProcessingException e) {
} catch (final JsonProcessingException e) {
throw new RuntimeException(e);
}
return new ReceiptItem(transaction.getId(), PaymentTime.periodStart(paidAt), metadata.level());
}
private static Subscription getSubscription(Object subscriptionObj) {
private static Subscription getSubscription(final Object subscriptionObj) {
if (!(subscriptionObj instanceof final Subscription subscription)) {
throw new IllegalArgumentException("Invalid subscription object: " + subscriptionObj.getClass().getName());
}
return subscription;
}
private Optional<Transaction> getLatestTransactionForSubscription(Subscription subscription) {
private Optional<Transaction> getLatestTransactionForSubscription(final Subscription subscription) {
return subscription.getTransactions().stream()
.max(Comparator.comparing(Transaction::getCreatedAt));
.max(Comparator.comparing(Transaction::getCreatedAt));
}
public CompletableFuture<PayPalBillingAgreementApprovalDetails> createPayPalBillingAgreement(final String returnUrl,
final String cancelUrl, final String locale) {
return braintreeGraphqlClient.createPayPalBillingAgreement(returnUrl, cancelUrl, locale)
.thenApply(response ->
new PayPalBillingAgreementApprovalDetails((String) response.approvalUrl, response.billingAgreementToken)
);
public PayPalBillingAgreementApprovalDetails createPayPalBillingAgreement(final String returnUrl,
final String cancelUrl, final String locale)
throws IOException {
final CreatePayPalBillingAgreementMutation.CreatePayPalBillingAgreement response = braintreeGraphqlClient.createPayPalBillingAgreement(
returnUrl, cancelUrl, locale);
return new PayPalBillingAgreementApprovalDetails((String) response.approvalUrl, response.billingAgreementToken);
}
public record PayPalBillingAgreementApprovalDetails(String approvalUrl, String billingAgreementToken) {
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.subscriptions;
import java.io.IOException;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
@@ -41,10 +42,11 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
* {@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
* finished being set up
* 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;
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException, IOException;
Object getSubscription(String subscriptionId);
@@ -62,11 +62,8 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
@@ -76,11 +73,11 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.storage.PaymentTime;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor {
private static final Logger logger = LoggerFactory.getLogger(StripeManager.class);
private static final String METADATA_KEY_LEVEL = "level";
private static final String METADATA_KEY_CLIENT_PLATFORM = "clientPlatform";
@@ -93,11 +90,11 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
@VisibleForTesting
StripeManager(
@Nonnull StripeClient stripeClient,
@Nonnull Executor executor,
@Nonnull byte[] idempotencyKeyGenerator,
@Nonnull String boostDescription,
@Nonnull Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
final StripeClient stripeClient,
final Executor executor,
final byte[] idempotencyKeyGenerator,
final String boostDescription,
final Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
Stripe.setAppInfo("Signal-Server", WhisperServerVersion.getServerVersion());
this.stripeClient = Objects.requireNonNull(stripeClient);
@@ -109,13 +106,15 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
this.boostDescription = Objects.requireNonNull(boostDescription);
this.supportedCurrenciesByPaymentMethod = supportedCurrenciesByPaymentMethod;
}
public StripeManager(
@Nonnull String apiKey,
@Nonnull Executor executor,
@Nonnull byte[] idempotencyKeyGenerator,
@Nonnull String boostDescription,
@Nonnull Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
this(new StripeClient(apiKey), executor, idempotencyKeyGenerator, boostDescription, supportedCurrenciesByPaymentMethod);
final String apiKey,
final Executor executor,
final byte[] idempotencyKeyGenerator,
final String boostDescription,
final Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
this(new StripeClient(apiKey), executor, idempotencyKeyGenerator, boostDescription,
supportedCurrenciesByPaymentMethod);
if (StringUtils.isEmpty(apiKey)) {
throw new IllegalArgumentException("apiKey cannot be empty");
@@ -128,7 +127,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
@Override
public boolean supportsPaymentMethod(PaymentMethod paymentMethod) {
public boolean supportsPaymentMethod(final PaymentMethod paymentMethod) {
return paymentMethod == PaymentMethod.CARD
|| paymentMethod == PaymentMethod.SEPA_DEBIT
|| paymentMethod == PaymentMethod.IDEAL;
@@ -138,7 +137,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
return commonOptions(null);
}
private RequestOptions commonOptions(@Nullable String idempotencyKey) {
private RequestOptions commonOptions(@Nullable final String idempotencyKey) {
return RequestOptions.builder()
.setIdempotencyKey(idempotencyKey)
.build();
@@ -157,46 +156,46 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
final Customer customer = stripeClient.v1().customers()
.create(builder.build(), commonOptions(generateIdempotencyKeyForSubscriberUser(subscriberUser)));
return new ProcessorCustomer(customer.getId(), getProvider());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
public Customer getCustomer(String customerId) {
CustomerRetrieveParams params = CustomerRetrieveParams.builder().build();
public Customer getCustomer(final String customerId) {
final CustomerRetrieveParams params = CustomerRetrieveParams.builder().build();
try {
return stripeClient.v1().customers().retrieve(customerId, params, commonOptions());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
@Override
public void setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodId,
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException {
CustomerUpdateParams params = CustomerUpdateParams.builder()
.setInvoiceSettings(InvoiceSettings.builder()
.setDefaultPaymentMethod(paymentMethodId)
.build())
.build();
try {
stripeClient.v1().customers().update(customerId, params, commonOptions());
} catch (InvalidRequestException e) {
// Could happen if the paymentMethodId was bunk or the client didn't actually finish setting it up
throw new SubscriptionInvalidArgumentsException(e.getMessage());
} catch (StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
public void setDefaultPaymentMethodForCustomer(final String customerId, final String paymentMethodId,
@Nullable final String currentSubscriptionId) throws SubscriptionInvalidArgumentsException {
final CustomerUpdateParams params = CustomerUpdateParams.builder()
.setInvoiceSettings(InvoiceSettings.builder()
.setDefaultPaymentMethod(paymentMethodId)
.build())
.build();
try {
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());
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
@Override
public String createPaymentMethodSetupToken(String customerId) {
SetupIntentCreateParams params = SetupIntentCreateParams.builder()
public String createPaymentMethodSetupToken(final String customerId) {
final SetupIntentCreateParams params = SetupIntentCreateParams.builder()
.setCustomer(customerId)
.build();
try {
return stripeClient.v1().setupIntents().create(params, commonOptions()).getClientSecret();
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
@@ -207,70 +206,65 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
/**
* Creates a payment intent. May throw a {@link SubscriptionInvalidAmountException} if stripe rejects the
* attempt if the amount is too large or too small
* Creates a payment intent. May throw a {@link SubscriptionInvalidAmountException} if stripe rejects the attempt if
* the amount is too large or too small
*/
public CompletableFuture<PaymentIntent> createPaymentIntent(final String currency,
public PaymentIntent createPaymentIntent(final String currency,
final long amount,
final long level,
@Nullable final ClientPlatform clientPlatform) {
@Nullable final ClientPlatform clientPlatform) throws SubscriptionInvalidAmountException {
return CompletableFuture.supplyAsync(() -> {
final PaymentIntentCreateParams.Builder builder = PaymentIntentCreateParams.builder()
.setAmount(amount)
.setCurrency(currency.toLowerCase(Locale.ROOT))
.setDescription(boostDescription)
.setCaptureMethod(PaymentIntentCreateParams.CaptureMethod.AUTOMATIC)
.putMetadata("level", Long.toString(level));
final PaymentIntentCreateParams.Builder builder = PaymentIntentCreateParams.builder()
.setAmount(amount)
.setCurrency(currency.toLowerCase(Locale.ROOT))
.setDescription(boostDescription)
.setCaptureMethod(PaymentIntentCreateParams.CaptureMethod.AUTOMATIC)
.putMetadata("level", Long.toString(level));
if (clientPlatform != null) {
builder.putMetadata(METADATA_KEY_CLIENT_PLATFORM, clientPlatform.name().toLowerCase());
if (clientPlatform != null) {
builder.putMetadata(METADATA_KEY_CLIENT_PLATFORM, clientPlatform.name().toLowerCase());
}
try {
return stripeClient.v1().paymentIntents().create(builder.build(), commonOptions());
} catch (final StripeException e) {
final String errorCode = e.getCode() == null
? "unknown"
: e.getCode().toLowerCase(Locale.ROOT);
switch (errorCode) {
case "amount_too_small", "amount_too_large" -> throw new SubscriptionInvalidAmountException(errorCode);
default -> throw new RuntimeException(e);
}
try {
return stripeClient.v1().paymentIntents().create(builder.build(), commonOptions());
} catch (StripeException e) {
final String errorCode = e.getCode() == null
? "unknown"
: e.getCode().toLowerCase(Locale.ROOT);
switch (errorCode) {
case "amount_too_small","amount_too_large" ->
throw ExceptionUtils.wrap(new SubscriptionInvalidAmountException(errorCode));
default -> throw new CompletionException(e);
}
}
}, executor);
}
}
public CompletableFuture<Optional<PaymentDetails>> getPaymentDetails(final String paymentIntentId) {
return CompletableFuture.supplyAsync(() -> {
try {
final PaymentIntent paymentIntent = getPaymentIntent(paymentIntentId);
public Optional<PaymentDetails> getPaymentDetails(final String paymentIntentId) throws IOException {
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);
}
}
return Optional.of(new PaymentDetails(paymentIntent.getId(),
paymentIntent.getMetadata() == null ? Collections.emptyMap() : paymentIntent.getMetadata(),
getPaymentStatusForStatus(paymentIntent.getStatus()),
Instant.ofEpochSecond(paymentIntent.getCreated()),
chargeFailure));
} catch (StripeException e) {
if (e.getStatusCode() == 404) {
return Optional.empty();
} else {
throw new CompletionException(e);
ChargeFailure chargeFailure = null;
if (paymentIntent.getLatestChargeObject() != null) {
final Charge charge = paymentIntent.getLatestChargeObject();
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
chargeFailure = createChargeFailure(charge);
}
}
}, executor);
return Optional.of(new PaymentDetails(paymentIntent.getId(),
paymentIntent.getMetadata() == null ? Collections.emptyMap() : paymentIntent.getMetadata(),
getPaymentStatusForStatus(paymentIntent.getStatus()),
Instant.ofEpochSecond(paymentIntent.getCreated()),
chargeFailure));
} catch (final StripeException e) {
if (e.getStatusCode() == 404) {
return Optional.empty();
} else {
throw new IOException(e);
}
}
}
private static PaymentStatus getPaymentStatusForStatus(String status) {
private static PaymentStatus getPaymentStatusForStatus(final String status) {
return switch (status.toLowerCase(Locale.ROOT)) {
case "processing" -> PaymentStatus.PROCESSING;
case "succeeded" -> PaymentStatus.SUCCEEDED;
@@ -283,13 +277,13 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
@Override
public SubscriptionId createSubscription(String customerId, String priceId, long level,
long lastSubscriptionCreatedAt)
public SubscriptionId createSubscription(final String customerId, final String priceId, final long level,
final long lastSubscriptionCreatedAt)
throws SubscriptionProcessorException, SubscriptionInvalidIdempotencyKeyException,
SubscriptionPaymentRequiresActionException {
// this relies on Stripe's idempotency key to avoid creating more than one subscription if the client
// retries this request
SubscriptionCreateParams params = SubscriptionCreateParams.builder()
final SubscriptionCreateParams params = SubscriptionCreateParams.builder()
.setCustomer(customerId)
.setOffSession(true)
.setPaymentBehavior(SubscriptionCreateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
@@ -307,11 +301,11 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
params,
commonOptions(generateIdempotencyKeyForCreateSubscription(customerId, lastSubscriptionCreatedAt)));
return new SubscriptionId(subscription.getId());
} catch (IdempotencyException e) {
} catch (final IdempotencyException e) {
throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage());
} catch (CardException e) {
} catch (final CardException e) {
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
} catch (StripeException e) {
} catch (final StripeException e) {
if ("subscription_payment_intent_requires_action".equals(e.getCode())) {
throw new SubscriptionPaymentRequiresActionException();
}
@@ -320,7 +314,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
@Override
public SubscriptionId updateSubscription(Object subscriptionObj, String priceId, long level, String idempotencyKey)
public SubscriptionId updateSubscription(final Object subscriptionObj, final String priceId, final long level, final String idempotencyKey)
throws SubscriptionInvalidIdempotencyKeyException, SubscriptionPaymentRequiresActionException,
SubscriptionProcessorException {
@@ -332,7 +326,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
return createSubscription(subscription.getCustomer(), priceId, level, subscription.getCreated());
}
List<SubscriptionUpdateParams.Item> items = new ArrayList<>();
final List<SubscriptionUpdateParams.Item> items = new ArrayList<>();
try {
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.v1().subscriptionItems()
.list(SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(),
@@ -346,7 +340,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
items.add(SubscriptionUpdateParams.Item.builder()
.setPrice(priceId)
.build());
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
final SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
.putMetadata(METADATA_KEY_LEVEL, Long.toString(level))
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
@@ -360,56 +354,57 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
final Subscription subscription1 = stripeClient.v1().subscriptions().update(subscription.getId(), params,
commonOptions(generateIdempotencyKeyForSubscriptionUpdate(subscription.getCustomer(), idempotencyKey)));
return new SubscriptionId(subscription1.getId());
} catch (IdempotencyException e) {
} catch (final IdempotencyException e) {
throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage());
} catch (CardException e) {
} catch (final CardException e) {
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
/// Retrieves the subscription object with `latest_invoice.payments` expanded
@Override
public Object getSubscription(String subscriptionId) {
SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
public Object getSubscription(final String subscriptionId) {
final SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
.addExpand("latest_invoice.payments")
.build();
try {
return stripeClient.v1().subscriptions().retrieve(subscriptionId, params, commonOptions());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
/// Retrieves the payment intent object with `latest_charge` expanded
public PaymentIntent getPaymentIntent(String paymentIntentId) throws StripeException {
PaymentIntentRetrieveParams params = PaymentIntentRetrieveParams.builder()
public PaymentIntent getPaymentIntent(final String paymentIntentId) throws StripeException {
final PaymentIntentRetrieveParams params = PaymentIntentRetrieveParams.builder()
.addExpand("latest_charge")
.build();
return stripeClient.v1().paymentIntents().retrieve(paymentIntentId, params, commonOptions());
}
public Charge getCharge(String chargeId) {
ChargeRetrieveParams params = ChargeRetrieveParams.builder()
public Charge getCharge(final String chargeId) {
final ChargeRetrieveParams params = ChargeRetrieveParams.builder()
.build();
try {
return stripeClient.v1().charges().retrieve(chargeId, params, commonOptions());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
@Override
public void cancelAllActiveSubscriptions(String customerId) {
public void cancelAllActiveSubscriptions(final String customerId) {
final Customer customer = getCustomer(customerId);
if (customer == null) {
throw new UncheckedIOException(new IOException("no customer record found for id " + customerId));
}
if (StringUtils.isBlank(customer.getId()) || (!customer.getId().equals(customerId))) {
logger.error("customer ID returned by Stripe ({}) did not match query ({})", customerId, customer.getSubscriptions());
throw new UncheckedIOException(new IOException("unexpected customer ID returned by Stripe"));
}
if (customer == null) {
throw new UncheckedIOException(new IOException("no customer record found for id " + customerId));
}
if (StringUtils.isBlank(customer.getId()) || (!customer.getId().equals(customerId))) {
logger.error("customer ID returned by Stripe ({}) did not match query ({})", customerId,
customer.getSubscriptions());
throw new UncheckedIOException(new IOException("unexpected customer ID returned by Stripe"));
}
final Collection<Subscription> subscriptions = listNonCanceledSubscriptions(customer);
if (subscriptions.stream()
@@ -423,20 +418,20 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
.toList());
}
public Collection<Subscription> listNonCanceledSubscriptions(Customer customer) {
SubscriptionListParams params = SubscriptionListParams.builder()
public Collection<Subscription> listNonCanceledSubscriptions(final Customer customer) {
final SubscriptionListParams params = SubscriptionListParams.builder()
.setCustomer(customer.getId())
.build();
try {
return Lists.newArrayList(
stripeClient.v1().subscriptions().list(params, commonOptions()).autoPagingIterable());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
@VisibleForTesting
void endSubscription(Subscription subscription) {
void endSubscription(final Subscription subscription) {
final SubscriptionStatus status = SubscriptionStatus.forApiValue(subscription.getStatus());
switch (status) {
@@ -459,30 +454,30 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
cancelSubscriptionAtEndOfCurrentPeriod(subscription);
}
}
};
}
}
private void cancelSubscriptionImmediately(Subscription subscription) {
SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
private void cancelSubscriptionImmediately(final Subscription subscription) {
final SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
try {
stripeClient.v1().subscriptions().cancel(subscription.getId(), params, commonOptions());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
private void cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
private void cancelSubscriptionAtEndOfCurrentPeriod(final Subscription subscription) {
final SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
.setCancelAtPeriodEnd(true)
.build();
try {
stripeClient.v1().subscriptions().update(subscription.getId(), params, commonOptions());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
public Collection<SubscriptionItem> getItemsForSubscription(Subscription subscription) {
public Collection<SubscriptionItem> getItemsForSubscription(final Subscription subscription) {
try {
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.v1().subscriptionItems().list(
SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(), commonOptions());
@@ -493,7 +488,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
}
public Price getPriceForSubscription(Subscription subscription) {
public Price getPriceForSubscription(final Subscription subscription) {
final Collection<SubscriptionItem> subscriptionItems = getItemsForSubscription(subscription);
if (subscriptionItems.isEmpty()) {
throw new IllegalStateException("no items found in subscription " + subscription.getId());
@@ -505,12 +500,12 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
}
private Product getProductForSubscription(Subscription subscription) {
private Product getProductForSubscription(final Subscription subscription) {
return getProductForPrice(getPriceForSubscription(subscription).getId());
}
@Override
public LevelAndCurrency getLevelAndCurrencyForSubscription(Object subscriptionObj) {
public LevelAndCurrency getLevelAndCurrencyForSubscription(final Object subscriptionObj) {
final Subscription subscription = getSubscription(subscriptionObj);
final Product product = getProductForSubscription(subscription);
@@ -519,25 +514,25 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
subscription.getCurrency().toLowerCase(Locale.ROOT));
}
public long getLevelForPrice(Price price) {
public long getLevelForPrice(final Price price) {
return getLevelForProduct(getProductForPrice(price.getId()));
}
public Product getProductForPrice(String priceId) {
PriceRetrieveParams params = PriceRetrieveParams.builder().addExpand("product").build();
public Product getProductForPrice(final String priceId) {
final PriceRetrieveParams params = PriceRetrieveParams.builder().addExpand("product").build();
try {
return stripeClient.v1().prices().retrieve(priceId, params, commonOptions()).getProductObject();
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
public long getLevelForProduct(Product product) {
public long getLevelForProduct(final Product product) {
return Long.parseLong(product.getMetadata().get(METADATA_KEY_LEVEL));
}
private static ChargeFailure createChargeFailure(final Charge charge) {
Charge.Outcome outcome = charge.getOutcome();
final Charge.Outcome outcome = charge.getOutcome();
return new ChargeFailure(
charge.getFailureCode(),
charge.getFailureMessage(),
@@ -546,7 +541,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
outcome != null ? outcome.getType() : null);
}
private static ChargeFailure createChargeFailureFromCardException(CardException e) {
private static ChargeFailure createChargeFailureFromCardException(final CardException e) {
return new ChargeFailure(
StringUtils.defaultIfBlank(e.getDeclineCode(), e.getCode()),
e.getStripeError().getMessage(),
@@ -583,7 +578,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
if (charge.getPaymentMethodDetails() != null
&& charge.getPaymentMethodDetails().getType() != null) {
paymentMethod = getPaymentMethodFromStripeString(charge.getPaymentMethodDetails().getType(), invoice.getId());
paymentMethod = getPaymentMethodFromStripeString(charge.getPaymentMethodDetails().getType(),
invoice.getId());
}
}
}
@@ -604,7 +600,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
);
}
private static PaymentMethod getPaymentMethodFromStripeString(final String paymentMethodString, final String invoiceId) {
private static PaymentMethod getPaymentMethodFromStripeString(final String paymentMethodString,
final String invoiceId) {
return switch (paymentMethodString) {
case "sepa_debit" -> PaymentMethod.SEPA_DEBIT;
case "card" -> PaymentMethod.CARD;
@@ -615,7 +612,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
};
}
private Subscription getSubscription(Object subscriptionObj) {
private Subscription getSubscription(final Object subscriptionObj) {
if (!(subscriptionObj instanceof final Subscription subscription)) {
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
}
@@ -624,18 +621,19 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
@Override
public ReceiptItem getReceiptItem(String subscriptionId)
public ReceiptItem getReceiptItem(final String subscriptionId)
throws SubscriptionPaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException {
final Invoice invoice = getSubscription(getSubscription(subscriptionId)).getLatestInvoiceObject();
return convertInvoiceToReceipt(invoice, subscriptionId);
}
private ReceiptItem convertInvoiceToReceipt(Invoice latestSubscriptionInvoice, String subscriptionId)
private ReceiptItem convertInvoiceToReceipt(final Invoice latestSubscriptionInvoice, final String subscriptionId)
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionPaymentRequiredException {
if (latestSubscriptionInvoice == null) {
throw new SubscriptionReceiptRequestedForOpenPaymentException();
}
if ("open".equalsIgnoreCase(latestSubscriptionInvoice.getStatus()) || "draft".equalsIgnoreCase(latestSubscriptionInvoice.getStatus())) {
if ("open".equalsIgnoreCase(latestSubscriptionInvoice.getStatus()) || "draft".equalsIgnoreCase(
latestSubscriptionInvoice.getStatus())) {
throw new SubscriptionReceiptRequestedForOpenPaymentException();
}
if (!"paid".equalsIgnoreCase(latestSubscriptionInvoice.getStatus())) {
@@ -660,7 +658,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
final Collection<InvoiceLineItem> invoiceLineItems = getInvoiceLineItemsForInvoice(latestSubscriptionInvoice);
Collection<InvoiceLineItem> subscriptionLineItems = invoiceLineItems.stream()
final Collection<InvoiceLineItem> subscriptionLineItems = invoiceLineItems.stream()
.filter(invoiceLineItem -> "subscription_item_details".equalsIgnoreCase(invoiceLineItem.getParent().getType()))
.toList();
if (subscriptionLineItems.isEmpty()) {
@@ -673,11 +671,11 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
+ "; invoiceId=" + latestSubscriptionInvoice.getId() + "; count=" + subscriptionLineItems.size());
}
InvoiceLineItem subscriptionLineItem = subscriptionLineItems.stream().findAny().get();
final InvoiceLineItem subscriptionLineItem = subscriptionLineItems.stream().findAny().get();
return getReceiptForSubscription(subscriptionLineItem, latestSubscriptionInvoice);
}
private ReceiptItem getReceiptForSubscription(InvoiceLineItem subscriptionLineItem, Invoice invoice) {
private ReceiptItem getReceiptForSubscription(final InvoiceLineItem subscriptionLineItem, final Invoice invoice) {
final Instant paidAt;
if (invoice.getStatusTransitions().getPaidAt() != null) {
paidAt = Instant.ofEpochSecond(invoice.getStatusTransitions().getPaidAt());
@@ -693,7 +691,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
getLevelForProduct(product));
}
public Collection<InvoiceLineItem> getInvoiceLineItemsForInvoice(Invoice invoice) {
public Collection<InvoiceLineItem> getInvoiceLineItemsForInvoice(final Invoice invoice) {
try {
final StripeCollection<InvoiceLineItem> lineItems = stripeClient.v1().invoices().lineItems()
.list(invoice.getId(), commonOptions());
@@ -703,31 +701,31 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
}
public CompletableFuture<String> getGeneratedSepaIdFromSetupIntent(String setupIntentId) {
return CompletableFuture.supplyAsync(() -> {
SetupIntentRetrieveParams params = SetupIntentRetrieveParams.builder()
.addExpand("latest_attempt")
.build();
try {
final SetupIntent setupIntent = stripeClient.v1().setupIntents().retrieve(setupIntentId, params, commonOptions());
if (setupIntent.getLatestAttemptObject() == null
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails() == null
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal() == null
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit() == null) {
// 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 ExceptionUtils.wrap(new SubscriptionProcessorConflictException());
}
return setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit();
} catch (StripeException e) {
if (e.getStatusCode() == 404) {
throw ExceptionUtils.wrap(new SubscriptionNotFoundException());
}
logger.error("unexpected error from Stripe when retrieving setupIntent {}", setupIntentId, e);
throw ExceptionUtils.wrap(e);
public String getGeneratedSepaIdFromSetupIntent(final String setupIntentId)
throws SubscriptionNotFoundException, SubscriptionProcessorConflictException, IOException {
final SetupIntentRetrieveParams params = SetupIntentRetrieveParams.builder()
.addExpand("latest_attempt")
.build();
try {
final SetupIntent setupIntent = stripeClient.v1().setupIntents().retrieve(setupIntentId, params, commonOptions());
if (setupIntent.getLatestAttemptObject() == null
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails() == null
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal() == null
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit()
== null) {
// 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();
}
}, executor);
return setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit();
} catch (final StripeException e) {
if (e.getStatusCode() == 404) {
throw new SubscriptionNotFoundException();
}
logger.error("unexpected error from Stripe when retrieving setupIntent {}", setupIntentId, e);
throw new IOException(e);
}
}
private Optional<InvoicePayment> getMostRecentInvoicePayment(final Invoice invoice) {
@@ -757,32 +755,32 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
* it is intentionally sending a repeat of the update to level 2 request because user is changing again, so in this
* case we derive idempotency from the client.
*/
private String generateIdempotencyKeyForSubscriptionUpdate(String customerId, String idempotencyKey) {
private String generateIdempotencyKeyForSubscriptionUpdate(final String customerId, final String idempotencyKey) {
return generateIdempotencyKey("subscriptionUpdate", mac -> {
mac.update(customerId.getBytes(StandardCharsets.UTF_8));
mac.update(idempotencyKey.getBytes(StandardCharsets.UTF_8));
});
}
private String generateIdempotencyKeyForSubscriberUser(byte[] subscriberUser) {
private String generateIdempotencyKeyForSubscriberUser(final byte[] subscriberUser) {
return generateIdempotencyKey("subscriberUser", mac -> mac.update(subscriberUser));
}
private String generateIdempotencyKeyForCreateSubscription(String customerId, long lastSubscriptionCreatedAt) {
private String generateIdempotencyKeyForCreateSubscription(final String customerId, final long lastSubscriptionCreatedAt) {
return generateIdempotencyKey("customerId", mac -> {
mac.update(customerId.getBytes(StandardCharsets.UTF_8));
mac.update(Conversions.longToByteArray(lastSubscriptionCreatedAt));
});
}
private String generateIdempotencyKey(String type, Consumer<Mac> byteConsumer) {
private String generateIdempotencyKey(final String type, final Consumer<Mac> byteConsumer) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
final Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(idempotencyKeyGenerator, "HmacSHA256"));
mac.update(type.getBytes(StandardCharsets.UTF_8));
byteConsumer.accept(mac);
return Base64.getUrlEncoder().encodeToString(mac.doFinal());
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
} catch (final NoSuchAlgorithmException | InvalidKeyException e) {
throw new AssertionError(e);
}
}
@@ -0,0 +1,20 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
/// Represents an operation that two argument and returns a result, but may throw a checked exception. Unlike most other
/// functional interfaces, `ThrowingBiFunction` is expected to operate via side-effects.
@FunctionalInterface
public interface ThrowingBiFunction<T, U, R, E extends Exception> {
/// Performs this operation on the given arguments and returns a result.
///
/// @param t the first input argument
/// @param u the second input argument
/// @return the result of applying the function
/// @throws E at the implementation's discretion
R apply(T t, U u) throws E;
}
@@ -76,6 +76,8 @@ message CreateBoostResponse {
errors.FailedPrecondition unsupported_level = 5 [(tag.reason) = "unsupported_level"];
// Donation permit was invalid or already spent
errors.FailedZkAuthentication permit_rejected = 6 [(tag.reason) = "permit_rejected"];
// The amount in the specified currency is not supported by the payment provider
errors.FailedPrecondition invalid_amount = 7 [(tag.reason) = "invalid_amount"];
}
}
@@ -135,6 +137,8 @@ message ConfirmPayPalBoostResponse {
errors.FailedPrecondition unsupported_currency = 3 [(tag.reason) = "unsupported_currency"];
// The requested level is not a valid one-time donation level
errors.FailedPrecondition unsupported_level = 4 [(tag.reason) = "unsupported_level"];
// The payment failed; see charge failure details
ChargeFailure charge_failure = 5 [(tag.reason) = "charge_failure"];
}
}
@@ -251,6 +251,8 @@ message SetDefaultPaymentMethodResponse {
// subscriberId authentication failure
errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"];
errors.FailedPrecondition payment_method_not_set_up = 4 [(tag.reason) = "payment_method_not_set_up"];
// Payment processor does not match existing processor associated with the subscription
errors.FailedPrecondition subscription_processor_conflict = 5 [(tag.reason) = "subscription_processor_conflict"];
}
}
@@ -20,6 +20,7 @@ import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.time.Instant;
import java.util.Base64;
import java.util.Collections;
@@ -55,6 +56,7 @@ 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.SubscriptionInvalidAmountException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
@@ -179,13 +181,13 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) {
void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) throws SubscriptionInvalidAmountException {
when(DONATION_PERMITS.spend(any(byte[].class), any(Instant.class))).thenReturn(donationPermitSpendOk);
when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.CARD))
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
when(STRIPE_MANAGER.createPaymentIntent(anyString(), anyLong(), anyLong(), any()))
.thenReturn(CompletableFuture.completedFuture(PAYMENT_INTENT));
.thenReturn(PAYMENT_INTENT);
String clientSecret = "some_client_secret";
when(PAYMENT_INTENT.getClientSecret()).thenReturn(clientSecret);
@@ -202,13 +204,13 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
}
@Test
void testCreateBoostPayPal() {
void testCreateBoostPayPal() throws IOException {
final BraintreeManager.PayPalOneTimePaymentApprovalDetails payPalOneTimePaymentApprovalDetails = mock(
BraintreeManager.PayPalOneTimePaymentApprovalDetails.class);
when(BRAINTREE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.PAYPAL))
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
when(BRAINTREE_MANAGER.createOneTimePayment(anyString(), anyLong(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(CompletableFuture.completedFuture(payPalOneTimePaymentApprovalDetails));
.thenReturn(payPalOneTimePaymentApprovalDetails);
when(payPalOneTimePaymentApprovalDetails.approvalUrl()).thenReturn("approvalUrl");
when(payPalOneTimePaymentApprovalDetails.paymentId()).thenReturn("someId");
@@ -239,14 +241,15 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
@ParameterizedTest
@MethodSource
void createBoostReceiptPaymentRequired(final ChargeFailure chargeFailure, boolean expectChargeFailure) {
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(new PaymentDetails(
void createBoostReceiptPaymentRequired(final ChargeFailure chargeFailure, boolean expectChargeFailure)
throws IOException {
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(Optional.of(new PaymentDetails(
"id",
Collections.emptyMap(),
PaymentStatus.FAILED,
Instant.now(),
chargeFailure))
));
);
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
.request()
.post(Entity.json("""
@@ -281,13 +284,13 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
}
@Test
void confirmPaypalBoostProcessorError() {
void confirmPaypalBoostProcessorError() throws SubscriptionProcessorException, 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()))
.thenReturn(CompletableFuture.failedFuture(new SubscriptionProcessorException(PaymentProvider.BRAINTREE,
new ChargeFailure("2046", "Declined", null, null, null))));
.thenThrow(new SubscriptionProcessorException(PaymentProvider.BRAINTREE,
new ChargeFailure("2046", "Declined", null, null, null)));
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/confirm")
.request()
@@ -323,12 +326,12 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext(
new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest();
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(new PaymentDetails(
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(Optional.of(new PaymentDetails(
"id",
Collections.emptyMap(),
PaymentStatus.SUCCEEDED,
Instant.now(),
null))));
null)));
doThrow(WriteConflictException.class).when(ISSUED_RECEIPTS_MANAGER).recordIssuance(any(), any(), any(), any());
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
@@ -18,13 +18,13 @@ import com.google.common.net.InetAddresses;
import com.google.protobuf.ByteString;
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;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -66,6 +66,8 @@ import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
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.tests.util.SubscriptionConfigTestHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
@@ -135,14 +137,14 @@ public class OneTimeDonationsGrpcServiceTest extends
}
@Test
void createBoost() {
void createBoost() throws SubscriptionInvalidAmountException {
final PaymentIntent paymentIntent = mock(PaymentIntent.class);
when(paymentIntent.getClientSecret()).thenReturn("test-client-secret");
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD))
.thenReturn(Set.of("usd"));
when(stripeManager.createPaymentIntent(any(), anyLong(), anyLong(), any()))
.thenReturn(CompletableFuture.completedFuture(paymentIntent));
.thenReturn(paymentIntent);
final CreateBoostResponse response = unauthenticatedServiceStub().createBoost(
CreateBoostRequest.newBuilder()
@@ -212,7 +214,7 @@ public class OneTimeDonationsGrpcServiceTest extends
}
@Test
void createPayPalBoost() {
void createPayPalBoost() throws IOException {
final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails =
mock(BraintreeManager.PayPalOneTimePaymentApprovalDetails.class);
when(approvalDetails.approvalUrl()).thenReturn("test-approval-url");
@@ -224,7 +226,7 @@ public class OneTimeDonationsGrpcServiceTest extends
.thenReturn("Donation to Signal Technology Foundation");
when(braintreeManager.createOneTimePayment(anyString(), anyLong(), anyString(), anyString(), anyString(),
anyString()))
.thenReturn(CompletableFuture.completedFuture(approvalDetails));
.thenReturn(approvalDetails);
final CreatePayPalBoostResponse response = unauthenticatedServiceStub().createPayPalBoost(
CreatePayPalBoostRequest.newBuilder()
@@ -241,14 +243,14 @@ public class OneTimeDonationsGrpcServiceTest extends
}
@Test
void confirmPayPalBoost() {
void confirmPayPalBoost() throws SubscriptionProcessorException, IOException {
when(braintreeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL))
.thenReturn(Set.of("usd"));
when(braintreeManager.captureOneTimePayment(anyString(), anyString(), anyString(), anyString(), anyLong(),
anyLong(), any()))
.thenReturn(CompletableFuture.completedFuture(
new BraintreeManager.PayPalChargeSuccessDetails("test-id")));
.thenReturn(
new BraintreeManager.PayPalChargeSuccessDetails("test-id"));
final ConfirmPayPalBoostResponse response = unauthenticatedServiceStub().confirmPayPalBoost(
ConfirmPayPalBoostRequest.newBuilder()
@@ -268,10 +270,10 @@ public class OneTimeDonationsGrpcServiceTest extends
@MethodSource
void createBoostReceiptCredentialsPaymentRequired(
@Nullable final ChargeFailure chargeFailure,
final boolean expectChargeFailure) {
when(stripeManager.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(
final boolean expectChargeFailure) throws IOException {
when(stripeManager.getPaymentDetails(any())).thenReturn(
Optional.of(new PaymentDetails("id", Collections.emptyMap(), PaymentStatus.FAILED,
clock.instant(), chargeFailure))));
clock.instant(), chargeFailure)));
final CreateBoostReceiptCredentialsResponse response =
unauthenticatedServiceStub().createBoostReceiptCredentials(
@@ -303,9 +305,9 @@ public class OneTimeDonationsGrpcServiceTest extends
ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext(
new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest();
when(stripeManager.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(
when(stripeManager.getPaymentDetails(any())).thenReturn(
Optional.of(new PaymentDetails("id", Collections.emptyMap(), PaymentStatus.SUCCEEDED,
clock.instant(), null))));
clock.instant(), null)));
doThrow(WriteConflictException.class).when(issuedReceiptsManager)
.recordIssuance(any(), any(), any(), any());
@@ -19,6 +19,7 @@ import static org.mockito.Mockito.when;
import com.google.common.net.InetAddresses;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
@@ -310,7 +311,7 @@ public class SubscriptionsGrpcServiceTest extends
final BraintreeManager.PayPalBillingAgreementApprovalDetails details =
new BraintreeManager.PayPalBillingAgreementApprovalDetails("https://fake-approval", "test-billing-token");
when(subscriptionManager.addPaymentMethodToCustomer(any(), any(), any(), any()))
.thenReturn(CompletableFuture.completedFuture(details));
.thenReturn(details);
final CreatePayPalPaymentMethodResponse response = unauthenticatedServiceStub().createPayPalPaymentMethod(
CreatePayPalPaymentMethodRequest.newBuilder()
.setSubscriberId(SUBSCRIBER_ID)
@@ -340,7 +341,7 @@ public class SubscriptionsGrpcServiceTest extends
@ParameterizedTest
@EnumSource(value = SetDefaultPaymentMethodRequest.RequestCase.class, names = {"STRIPE", "BRAINTREE", "SEPA"})
void setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest.RequestCase requestCase)
throws SubscriptionNotFoundException, SubscriptionForbiddenException {
throws SubscriptionNotFoundException, SubscriptionForbiddenException, IOException, SubscriptionProcessorConflictException {
final PaymentProvider provider = requestCase == SetDefaultPaymentMethodRequest.RequestCase.BRAINTREE
? PaymentProvider.BRAINTREE : PaymentProvider.STRIPE;
final Subscriptions.Record record = mock(Subscriptions.Record.class);
@@ -348,7 +349,7 @@ public class SubscriptionsGrpcServiceTest extends
when(subscriptionManager.getSubscriber(any())).thenReturn(record);
if (requestCase == SetDefaultPaymentMethodRequest.RequestCase.SEPA) {
when(stripeManager.getGeneratedSepaIdFromSetupIntent(any()))
.thenReturn(CompletableFuture.completedFuture("sepa-id"));
.thenReturn("sepa-id");
}
final SetDefaultPaymentMethodRequest.Builder builder = SetDefaultPaymentMethodRequest.newBuilder()
.setSubscriberId(SUBSCRIBER_ID);
@@ -8,26 +8,26 @@ package org.whispersystems.textsecuregcm.subscriptions;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.braintree.graphql.clientoperation.CreatePayPalOneTimePaymentMutation;
import jakarta.ws.rs.ServiceUnavailableException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.http.HttpHeaders;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
@ExtendWith(MockitoExtension.class)
class BraintreeGraphqlClientTest {
private static final String CURRENCY = "xts";
@@ -36,49 +36,40 @@ class BraintreeGraphqlClientTest {
private static final String LOCALE = "xx";
private static final String LOCALIZED_LINE_ITEM_NAME = "Donation to Signal Technology Foundation";
@Mock
private FaultTolerantHttpClient httpClient;
@Mock
private HttpResponse<Object> response;
private BraintreeGraphqlClient braintreeGraphqlClient;
@BeforeEach
void setUp() {
httpClient = mock(FaultTolerantHttpClient.class);
void setUp() throws IOException {
lenient().when(httpClient.send(any(), any())).thenReturn(response);
braintreeGraphqlClient = new BraintreeGraphqlClient(httpClient, "https://example.com", "public", "super-secret");
}
@Test
void createPayPalOneTimePayment() {
final HttpResponse<Object> response = mock(HttpResponse.class);
when(httpClient.sendAsync(any(), any()))
.thenReturn(CompletableFuture.completedFuture(response));
void createPayPalOneTimePayment() throws IOException {
final String paymentId = "PAYID-AAA1AAAA1A11111AA111111A";
when(response.body())
.thenReturn(createPayPalOneTimePaymentResponse(paymentId));
when(response.statusCode())
.thenReturn(200);
final CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> future = braintreeGraphqlClient.createPayPalOneTimePayment(
final CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment result = braintreeGraphqlClient.createPayPalOneTimePayment(
BigDecimal.ONE, CURRENCY,
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME);
assertTimeoutPreemptively(Duration.ofSeconds(3), () -> {
final CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment result = future.get();
assertEquals(paymentId, result.paymentId);
assertNotNull(result.approvalUrl);
});
}
@Test
void createPayPalOneTimePaymentHttpError() {
final HttpResponse<Object> response = mock(HttpResponse.class);
when(httpClient.sendAsync(any(), any()))
.thenReturn(CompletableFuture.completedFuture(response));
void createPayPalOneTimePaymentHttpError() throws IOException {
when(response.statusCode())
.thenReturn(500);
final HttpHeaders httpheaders = mock(HttpHeaders.class);
@@ -86,39 +77,21 @@ class BraintreeGraphqlClientTest {
when(response.headers())
.thenReturn(httpheaders);
final CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> future = braintreeGraphqlClient.createPayPalOneTimePayment(
assertThrows(IOException.class, () -> braintreeGraphqlClient.createPayPalOneTimePayment(
BigDecimal.ONE, CURRENCY,
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME);
assertTimeoutPreemptively(Duration.ofSeconds(3), () -> {
final ExecutionException e = assertThrows(ExecutionException.class, future::get);
assertTrue(e.getCause() instanceof ServiceUnavailableException);
});
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME));
}
@Test
void createPayPalOneTimePaymentGraphQlError() {
final HttpResponse<Object> response = mock(HttpResponse.class);
when(httpClient.sendAsync(any(), any()))
.thenReturn(CompletableFuture.completedFuture(response));
when(response.body())
.thenReturn(createErrorResponse("createPayPalOneTimePayment", "12345"));
when(response.statusCode())
.thenReturn(200);
final CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> future = braintreeGraphqlClient.createPayPalOneTimePayment(
assertThrows(IOException.class, () -> braintreeGraphqlClient.createPayPalOneTimePayment(
BigDecimal.ONE, CURRENCY,
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME);
assertTimeoutPreemptively(Duration.ofSeconds(3), () -> {
final ExecutionException e = assertThrows(ExecutionException.class, future::get);
assertTrue(e.getCause() instanceof ServiceUnavailableException);
});
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME));
}
private String createPayPalOneTimePaymentResponse(final String paymentId) {