Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#1159 stripe api compatibility #1160

Merged
merged 4 commits into from
Dec 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ dependencies {
implementation "org.apache.logging.log4j:log4j-slf4j-impl:2.17.1"
/**/

implementation "com.stripe:stripe-java:20.50.0"
implementation "com.stripe:stripe-java:22.3.0"
implementation 'com.paypal.sdk:checkout-sdk:1.0.5'
implementation 'com.google.code.gson:gson:2.9.0'
implementation 'com.fatboyindustrial.gson-javatime-serialisers:gson-javatime-serialisers:1.1.1', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import alfio.util.RequestUtils;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
Expand All @@ -30,6 +31,8 @@
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static alfio.util.HttpUtils.APPLICATION_JSON_UTF8;

@RestController
@Log4j2
@AllArgsConstructor
Expand All @@ -40,17 +43,25 @@ public class StripePaymentWebhookController {
@PostMapping("/api/payment/webhook/stripe/payment")
public ResponseEntity<String> receivePaymentConfirmation(@RequestHeader(value = "Stripe-Signature") String stripeSignature,
HttpServletRequest request) {
var httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_UTF8);
return RequestUtils.readRequest(request)
.map(content -> {
var result = ticketReservationManager.processTransactionWebhook(content, stripeSignature, PaymentProxy.STRIPE, Map.of());
if(result.isSuccessful()) {
return ResponseEntity.ok("OK");
return ResponseEntity.status(HttpStatus.OK)
.headers(httpHeaders)
.body("OK");
} else if(result.isError()) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result.getReason());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.headers(httpHeaders)
.body(result.getReason());
}
return ResponseEntity.ok(result.getReason());
return ResponseEntity.status(HttpStatus.OK)
.headers(httpHeaders)
.body(result.getReason());
})
.orElseGet(() -> ResponseEntity.badRequest().body("NOK"));
.orElseGet(() -> ResponseEntity.badRequest().headers(httpHeaders).body("Malformed request."));

}
}
17 changes: 10 additions & 7 deletions src/main/java/alfio/manager/payment/BaseStripeManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,7 @@ Optional<Boolean> processWebhookEvent(String body, String signature) {
try {
com.stripe.model.Event event = Webhook.constructEvent(body, signature, getWebhookSignatureKey());
if("account.application.deauthorized".equals(event.getType())
&& event.getLivemode() != null
&& event.getLivemode() == environment.acceptsProfiles(Profiles.of("dev", "test", "demo"))) {
&& Boolean.TRUE.equals(event.getLivemode()) == environment.acceptsProfiles(Profiles.of("dev", "test", "demo"))) {
return Optional.of(revokeToken(event.getAccount()));
}
return Optional.of(true);
Expand Down Expand Up @@ -194,10 +193,14 @@ PaymentResult getToken(PaymentSpecification spec) {
return PaymentResult.failed(ErrorsCode.STEP_2_MISSING_STRIPE_TOKEN);
}

private BalanceTransaction retrieveBalanceTransaction(String balanceTransaction, RequestOptions options) throws StripeException {
BalanceTransaction retrieveBalanceTransaction(String balanceTransaction, RequestOptions options) throws StripeException {
return BalanceTransaction.retrieve(balanceTransaction, options);
}

Charge retrieveCharge(String chargeId, RequestOptions requestOptions) throws StripeException {
return Charge.retrieve(chargeId, requestOptions);
}

Optional<RequestOptions> options(PurchaseContext purchaseContext) {
return options(purchaseContext, UnaryOperator.identity());
}
Expand Down Expand Up @@ -227,10 +230,10 @@ Optional<PaymentInformation> getInfo(Transaction transaction, PurchaseContext pu
Optional<RequestOptions> requestOptionsOptional = options(purchaseContext);
if(requestOptionsOptional.isPresent()) {
RequestOptions options = requestOptionsOptional.get();
Charge charge = Charge.retrieve(transaction.getTransactionId(), options);
Charge charge = retrieveCharge(transaction.getTransactionId(), options);
String paidAmount = MonetaryUtil.formatCents(charge.getAmount(), charge.getCurrency());
String refundedAmount = MonetaryUtil.formatCents(charge.getAmountRefunded(), charge.getCurrency());
List<BalanceTransaction.Fee> fees = retrieveBalanceTransaction(charge.getBalanceTransaction(), options).getFeeDetails();
List<BalanceTransaction.FeeDetail> fees = retrieveBalanceTransaction(charge.getBalanceTransaction(), options).getFeeDetails();
return Optional.of(new PaymentInformation(paidAmount, refundedAmount, getFeeAmount(fees, "stripe_fee"), getFeeAmount(fees, "application_fee")));
}
return Optional.empty();
Expand All @@ -239,11 +242,11 @@ Optional<PaymentInformation> getInfo(Transaction transaction, PurchaseContext pu
}
}

static String getFeeAmount(List<BalanceTransaction.Fee> fees, String feeType) {
static String getFeeAmount(List<BalanceTransaction.FeeDetail> fees, String feeType) {
return fees.stream()
.filter(f -> f.getType().equals(feeType))
.findFirst()
.map(BalanceTransaction.Fee::getAmount)
.map(BalanceTransaction.FeeDetail::getAmount)
.map(String::valueOf)
.orElse(null);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public class StripeCreditCardManager implements PaymentProvider, ClientServerTok

public static final String STRIPE_UNEXPECTED = "error.STEP2_STRIPE_unexpected";
private static final String STRIPE_MANAGER = StripeCreditCardManager.class.getName();
public static final EnumSet<ConfigurationKeys> OPTIONS_TO_LOAD = EnumSet.of(STRIPE_ENABLE_SCA, STRIPE_SECRET_KEY, STRIPE_PUBLIC_KEY);
protected static final EnumSet<ConfigurationKeys> OPTIONS_TO_LOAD = EnumSet.of(STRIPE_ENABLE_SCA, STRIPE_SECRET_KEY, STRIPE_PUBLIC_KEY);

private final TransactionRepository transactionRepository;
private final BaseStripeManager baseStripeManager;
Expand Down Expand Up @@ -151,7 +151,7 @@ public PaymentResult doPayment( PaymentSpecification spec ) {
return optionalCharge.map(charge -> {
log.info("transaction {} paid: {}", spec.getReservationId(), charge.getPaid());
Pair<Long, Long> fees = Optional.ofNullable(charge.getBalanceTransactionObject()).map( bt -> {
List<BalanceTransaction.Fee> feeDetails = bt.getFeeDetails();
List<BalanceTransaction.FeeDetail> feeDetails = bt.getFeeDetails();
return Pair.of(Optional.ofNullable( BaseStripeManager.getFeeAmount(feeDetails, "application_fee")).map(Long::parseLong).orElse(0L),
Optional.ofNullable( BaseStripeManager.getFeeAmount(feeDetails, "stripe_fee")).map(Long::parseLong).orElse(0L));
}).orElse(null);
Expand All @@ -162,10 +162,9 @@ public PaymentResult doPayment( PaymentSpecification spec ) {
fees != null ? fees.getLeft() : 0L, fees != null ? fees.getRight() : 0L, Transaction.Status.COMPLETE, Map.of(STRIPE_MANAGER_TYPE_KEY, STRIPE_MANAGER));
return PaymentResult.successful(charge.getId());
}).orElseGet(() -> PaymentResult.failed("error.STEP2_UNABLE_TO_TRANSITION"));
} catch (StripeException e) {
return PaymentResult.failed(baseStripeManager.handleException(e));
} catch (Exception e) {
if(e instanceof StripeException) {
return PaymentResult.failed( baseStripeManager.handleException((StripeException)e));
}
throw new IllegalStateException(e);
}
}
Expand Down
Loading