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

Mollie integration #861

Merged
merged 9 commits into from
Jan 21, 2020
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 gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ junitVersion=5.1.0
systemProp.jdk.tls.client.protocols="TLSv1,TLSv1.1,TLSv1.2"

# https://jitpack.io/#alfio-event/alf.io-public-frontend -> go to commit tab, set the version
alfioPublicFrontendVersion=c566584f29
alfioPublicFrontendVersion=d6fec23141
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,18 @@ public ResponseEntity<EventWithAdditionalInfo> getEvent(@PathVariable("eventName
.orElseGet(() -> ResponseEntity.notFound().headers(getCorsHeaders()).build());
}

private static Map<String, String> applyCommonMark(Map<String, String> in) {
if (in == null) {
return Collections.emptyMap();
}

var res = new HashMap<String, String>();
in.forEach((k, v) -> {
res.put(k, MustacheCustomTag.renderToHtmlCommonmarkEscaped(v));
});
return res;
}

@PostMapping("event/{eventName}/waiting-list/subscribe")
public ResponseEntity<ValidatedResponse<Boolean>> subscribeToWaitingList(@PathVariable("eventName") String eventName,
@RequestBody WaitingQueueSubscriptionForm subscription,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
import alfio.model.*;
import alfio.model.system.ConfigurationKeys;
import alfio.model.transaction.*;
import alfio.repository.AdditionalServiceItemRepository;
import alfio.repository.EventRepository;
import alfio.repository.TicketFieldRepository;
import alfio.repository.TicketReservationRepository;
Expand Down Expand Up @@ -183,18 +182,21 @@ public ResponseEntity<ReservationInfo> getReservationInfo(@PathVariable("eventNa
additionalInfo.getBillingDetails(),
//
containsCategoriesLinkedToGroups,
getActivePaymentMethods(event, ticketsByCategory.keySet())
getActivePaymentMethods(event, ticketsByCategory.keySet(), orderSummary, reservationId)
));
}));

//
return res.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
}

private Map<PaymentMethod, PaymentProxyWithParameters> getActivePaymentMethods(Event event, Collection<Integer> categoryIds) {
private Map<PaymentMethod, PaymentProxyWithParameters> getActivePaymentMethods(Event event,
Collection<Integer> categoryIds,
OrderSummary orderSummary,
String reservationId) {
if(!event.isFreeOfCharge()) {
var blacklistedMethodsForReservation = configurationManager.getBlacklistedMethodsForReservation(event, categoryIds);
return paymentManager.getPaymentMethods(event)
return paymentManager.getPaymentMethods(event, new TransactionRequest(orderSummary.getOriginalTotalPrice(), ticketReservationRepository.getBillingDetailsForReservation(reservationId)))
.stream()
.filter(p -> !blacklistedMethodsForReservation.contains(p.getPaymentMethod()))
.filter(p -> TicketReservationManager.isValidPaymentMethod(p, event, configurationManager))
Expand Down Expand Up @@ -264,7 +266,7 @@ public ResponseEntity<ValidatedResponse<ReservationPaymentResult>> confirmOvervi
return buildReservationPaymentStatus(bindingResult);
}

if(isCaptchaInvalid(reservationCost.getPriceWithVAT(), paymentForm.getPaymentMethod(), paymentForm.getCaptcha(), request, event)) {
if(isCaptchaInvalid(reservationCost.getPriceWithVAT(), paymentForm.getPaymentProxy(), paymentForm.getCaptcha(), request, event)) {
log.debug("captcha validation failed.");
bindingResult.reject(ErrorsCode.STEP_2_CAPTCHA_VALIDATION_FAILED);
}
Expand All @@ -283,16 +285,16 @@ public ResponseEntity<ValidatedResponse<ReservationPaymentResult>> confirmOvervi

PaymentToken paymentToken = paymentManager.getPaymentToken(reservationId).orElse(null);
if(paymentToken == null && StringUtils.isNotEmpty(paymentForm.getGatewayToken())) {
paymentToken = paymentManager.buildPaymentToken(paymentForm.getGatewayToken(), paymentForm.getPaymentMethod(), new PaymentContext(event, reservationId));
paymentToken = paymentManager.buildPaymentToken(paymentForm.getGatewayToken(), paymentForm.getPaymentProxy(),
new PaymentContext(event, reservationId));
}
PaymentSpecification spec = new PaymentSpecification(reservationId, paymentToken, reservationCost.getPriceWithVAT(),
event, ticketReservation.getEmail(), customerName, ticketReservation.getBillingAddress(), ticketReservation.getCustomerReference(),
locale, ticketReservation.isInvoiceRequested(), !ticketReservation.isDirectAssignmentRequested(),
orderSummary, ticketReservation.getVatCountryCode(), ticketReservation.getVatNr(), ticketReservation.getVatStatus(),
Boolean.TRUE.equals(paymentForm.getTermAndConditionsAccepted()), Boolean.TRUE.equals(paymentForm.getPrivacyPolicyAccepted()));

final PaymentResult status = ticketReservationManager.performPayment(spec, reservationCost, Optional.ofNullable(paymentForm.getPaymentMethod()));

final PaymentResult status = ticketReservationManager.performPayment(spec, reservationCost, paymentForm.getPaymentProxy(), paymentForm.getSelectedPaymentMethod());

if (status.isRedirect()) {
var body = ValidatedResponse.toResponse(bindingResult,
Expand Down
12 changes: 7 additions & 5 deletions src/main/java/alfio/controller/form/PaymentForm.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import alfio.model.Event;
import alfio.model.TotalPrice;
import alfio.model.transaction.PaymentMethod;
import alfio.model.transaction.PaymentProxy;
import alfio.util.ErrorsCode;
import lombok.Data;
Expand All @@ -33,20 +34,21 @@
public class PaymentForm implements Serializable {

private String gatewayToken;
private PaymentProxy paymentMethod;
private PaymentProxy paymentProxy;
private PaymentMethod selectedPaymentMethod;
private Boolean termAndConditionsAccepted;
private Boolean privacyPolicyAccepted;
private String hmac;
private String captcha;


public void validate(BindingResult bindingResult, Event event, TotalPrice reservationCost) {
List<PaymentProxy> allowedPaymentMethods = event.getAllowedPaymentProxies();
List<PaymentProxy> allowedProxies = event.getAllowedPaymentProxies();

Optional<PaymentProxy> paymentProxyOptional = Optional.ofNullable(paymentMethod);
Optional<PaymentProxy> paymentProxyOptional = Optional.ofNullable(paymentProxy);
boolean priceGreaterThanZero = reservationCost.getPriceWithVAT() > 0;
boolean multiplePaymentMethods = allowedPaymentMethods.size() > 1;
if (multiplePaymentMethods && priceGreaterThanZero && paymentProxyOptional.isEmpty()) {
boolean multipleProxies = allowedProxies.size() > 1;
if (multipleProxies && priceGreaterThanZero && paymentProxyOptional.isEmpty()) {
bindingResult.reject(ErrorsCode.STEP_2_MISSING_PAYMENT_METHOD);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* This file is part of alf.io.
*
* alf.io is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alf.io is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with alf.io. If not, see <http://www.gnu.org/licenses/>.
*/
package alfio.controller.payment.api.mollie;

import alfio.manager.TicketReservationManager;
import alfio.model.transaction.PaymentProxy;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Optional;

import static alfio.manager.payment.MollieWebhookPaymentManager.WEBHOOK_URL_TEMPLATE;

@RestController
@Log4j2
@AllArgsConstructor
public class MolliePaymentWebhookController {
private final TicketReservationManager ticketReservationManager;

@SuppressWarnings("MVCPathVariableInspection")
@PostMapping(WEBHOOK_URL_TEMPLATE)
public ResponseEntity<String> receivePaymentConfirmation(HttpServletRequest request,
@PathVariable("eventShortName") String eventName,
@PathVariable("reservationId") String reservationId) {
return Optional.ofNullable(StringUtils.trimToNull(request.getParameter("id")))
.map(id -> {
var content = "id="+id;
var result = ticketReservationManager.processTransactionWebhook(content, null, PaymentProxy.MOLLIE,
Map.of("eventName", eventName, "reservationId", reservationId));
if(result.isSuccessful()) {
return ResponseEntity.ok("OK");
} else if(result.isError()) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result.getReason());
}
return ResponseEntity.ok(result.getReason());
})
.orElseGet(() -> ResponseEntity.badRequest().body("NOK"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import alfio.manager.TicketReservationManager;
import alfio.model.transaction.PaymentMethod;
import alfio.model.transaction.PaymentProxy;
import alfio.util.RequestUtils;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
Expand All @@ -28,6 +29,7 @@
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@Log4j2
Expand All @@ -41,7 +43,7 @@ public ResponseEntity<String> receivePaymentConfirmation(@RequestHeader(value =
HttpServletRequest request) {
return RequestUtils.readRequest(request)
.map(content -> {
var result = ticketReservationManager.processTransactionWebhook(content, stripeSignature, PaymentMethod.CREDIT_CARD);
var result = ticketReservationManager.processTransactionWebhook(content, stripeSignature, PaymentProxy.STRIPE, Map.of());
if(result.isSuccessful()) {
return ResponseEntity.ok("OK");
} else if(result.isError()) {
Expand Down
16 changes: 14 additions & 2 deletions src/main/java/alfio/manager/EventManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
import ch.digitalfondue.npjt.AffectedRowCountAndKey;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
Expand Down Expand Up @@ -108,6 +109,7 @@ public class EventManager {
private final GroupRepository groupRepository;
private final NamedParameterJdbcTemplate jdbcTemplate;
private final ConfigurationRepository configurationRepository;
private final PaymentManager paymentManager;


public Event getSingleEvent(String eventName, String username) {
Expand Down Expand Up @@ -336,7 +338,7 @@ public void updateEventPrices(EventAndOrganizationId original, EventModification
throw new IllegalArgumentException(format("cannot reduce max tickets to %d. There are already %d tickets allocated. Try updating categories first.", em.getAvailableSeats(), allocatedSeats));
}
}

validatePaymentProxies(em.getAllowedPaymentProxies(), em.getOrganizationId());
String paymentProxies = collectPaymentProxies(em);
BigDecimal vat = em.isFreeOfCharge() ? BigDecimal.ZERO : em.getVatPercentage();
eventRepository.updatePrices(em.getCurrency(), em.getAvailableSeats(), em.isVatIncluded(), vat, paymentProxies, eventId, em.getVatStatus(), em.getPriceInCents());
Expand All @@ -354,6 +356,14 @@ public void updateEventPrices(EventAndOrganizationId original, EventModification
}
}

private void validatePaymentProxies(List<PaymentProxy> paymentProxies, int organizationId) {
var conflicts = paymentManager.validateSelection(paymentProxies, organizationId);
if(!conflicts.isEmpty()) {
var firstConflict = IterableUtils.get(conflicts, 0);
throw new IllegalStateException("Conflicting providers found: "+firstConflict.getValue());
}
}

public EventModification.AdditionalService insertAdditionalService(Event event, EventModification.AdditionalService additionalService) {
int eventId = event.getId();
AffectedRowCountAndKey<Integer> result = additionalServiceRepository.insert(eventId,
Expand Down Expand Up @@ -799,6 +809,7 @@ private void createAllTicketsForEvent(Event event, EventModification em) {

private int insertEvent(EventModification em) {
Validate.notNull(em.getAvailableSeats());
validatePaymentProxies(em.getAllowedPaymentProxies(), em.getOrganizationId());
String paymentProxies = collectPaymentProxies(em);
BigDecimal vat = !em.isInternal() || em.isFreeOfCharge() ? BigDecimal.ZERO : em.getVatPercentage();
String privateKey = UUID.randomUUID().toString();
Expand All @@ -814,6 +825,7 @@ private String collectPaymentProxies(EventModification em) {
return em.getAllowedPaymentProxies()
.stream()
.map(PaymentProxy::name)
.distinct()
.collect(joining(","));
}

Expand Down
Loading