Search in sources :

Example 1 with TransactionRepository

use of alfio.repository.TransactionRepository in project alf.io by alfio-event.

the class MollieWebhookPaymentManager method initPayment.

private PaymentResult initPayment(TicketReservation reservation, PaymentSpecification spec, String baseUrl, Map<ConfigurationKeys, ConfigurationManager.MaybeConfiguration> configuration) throws IOException, InterruptedException {
    var purchaseContext = spec.getPurchaseContext();
    var purchaseContextUrlComponent = purchaseContext.getType().getUrlComponent();
    var publicIdentifier = purchaseContext.getPublicIdentifier();
    var reservationId = reservation.getId();
    String bookUrl = baseUrl + "/" + purchaseContextUrlComponent + "/" + publicIdentifier + "/reservation/" + reservationId + "/book";
    final int items;
    if (spec.getPurchaseContext().getType() == PurchaseContext.PurchaseContextType.event) {
        items = ticketRepository.countTicketsInReservation(spec.getReservationId());
    } else {
        items = 1;
    }
    Map<String, Object> payload = new HashMap<>();
    payload.put(AMOUNT, Map.of(VALUE, spec.getOrderSummary().getTotalPrice(), CURRENCY, spec.getPurchaseContext().getCurrency()));
    var description = purchaseContext.ofType(PurchaseContext.PurchaseContextType.event) ? "ticket(s) for event" : "x subscription";
    payload.put("description", String.format("%s - %d %s %s", configurationManager.getShortReservationID(spec.getPurchaseContext(), reservation), items, description, spec.getPurchaseContext().getDisplayName()));
    payload.put("redirectUrl", bookUrl);
    payload.put("webhookUrl", baseUrl + UriComponentsBuilder.fromPath(WEBHOOK_URL_TEMPLATE).buildAndExpand(reservationId).toUriString());
    payload.put("metadata", MetadataBuilder.buildMetadata(spec, Map.of()));
    if (configuration.get(PLATFORM_MODE_ENABLED).getValueAsBooleanOrDefault()) {
        payload.put("profileId", configuration.get(MOLLIE_CONNECT_PROFILE_ID).getRequiredValue());
        payload.put("testmode", !configuration.get(MOLLIE_CONNECT_LIVE_MODE).getValueAsBooleanOrDefault());
        String currencyCode = spec.getCurrencyCode();
        FeeCalculator.getCalculator(spec.getPurchaseContext(), configurationManager, currencyCode).apply(items, (long) spec.getPriceWithVAT()).filter(// minimum fee for Mollie is 0.01
        fee -> fee > 1L).map(fee -> MonetaryUtil.formatCents(fee, currencyCode)).ifPresent(fee -> payload.put("applicationFee", Map.of(AMOUNT, Map.of(CURRENCY, currencyCode, VALUE, fee), "description", "Reservation" + reservationId)));
    }
    HttpRequest request = requestFor(PAYMENTS_ENDPOINT, configuration, spec.getPurchaseContext().getConfigurationLevel()).header(HttpUtils.CONTENT_TYPE, HttpUtils.APPLICATION_JSON).POST(HttpRequest.BodyPublishers.ofString(Json.GSON.toJson(payload))).build();
    HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
    if (HttpUtils.callSuccessful(response)) {
        try (var responseReader = new InputStreamReader(response.body(), UTF_8)) {
            var body = new MolliePaymentDetails(JsonParser.parseReader(responseReader).getAsJsonObject());
            var paymentId = body.getPaymentId();
            var checkoutLink = body.getCheckoutLink();
            // we give an additional slack to process the payment
            var expiration = body.getExpiresAt().orElseThrow().plusMinutes(5);
            ticketReservationRepository.updateReservationStatus(reservationId, EXTERNAL_PROCESSING_PAYMENT.toString());
            ticketReservationRepository.updateValidity(reservationId, Date.from(expiration.toInstant()));
            invalidateExistingTransactions(reservationId, transactionRepository);
            transactionRepository.insert(paymentId, paymentId, reservationId, ZonedDateTime.now(clockProvider.withZone(spec.getPurchaseContext().getZoneId())), spec.getPriceWithVAT(), spec.getPurchaseContext().getCurrency(), "Mollie Payment", PaymentProxy.MOLLIE.name(), 0L, 0L, Transaction.Status.PENDING, Map.of());
            return PaymentResult.redirect(checkoutLink);
        }
    } else {
        log.warn("was not able to create a payment for reservation id " + reservationId);
        return PaymentResult.failed(ErrorsCode.STEP_2_PAYMENT_REQUEST_CREATION);
    }
}
Also used : JsonObject(com.google.gson.JsonObject) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) ZonedDateTime(java.time.ZonedDateTime) PaymentResult(alfio.manager.support.PaymentResult) PurchaseContext(alfio.model.PurchaseContext) StringUtils(org.apache.commons.lang3.StringUtils) PaymentInformation(alfio.model.PaymentInformation) MonetaryUtil.formatCents(alfio.util.MonetaryUtil.formatCents) PurchaseContextManager(alfio.manager.PurchaseContextManager) Duration(java.time.Duration) URI(java.net.URI) AccessTokenResponseDetails(alfio.util.oauth2.AccessTokenResponseDetails) RefundRequest(alfio.model.transaction.capabilities.RefundRequest) MollieToken(alfio.model.transaction.token.MollieToken) HttpResponse(java.net.http.HttpResponse) FeeCalculator(alfio.manager.support.FeeCalculator) EXTERNAL_PROCESSING_PAYMENT(alfio.model.TicketReservation.TicketReservationStatus.EXTERNAL_PROCESSING_PAYMENT) java.util(java.util) ConfigurationLevel(alfio.manager.system.ConfigurationLevel) MaybeConfiguration(alfio.manager.system.ConfigurationManager.MaybeConfiguration) TicketReservationRepository(alfio.repository.TicketReservationRepository) ConfigurationManager(alfio.manager.system.ConfigurationManager) Cache(com.github.benmanes.caffeine.cache.Cache) JsonParser(com.google.gson.JsonParser) alfio.util(alfio.util) HttpRequest(java.net.http.HttpRequest) MollieWebhookPayload(alfio.model.transaction.webhook.MollieWebhookPayload) alfio.model.transaction(alfio.model.transaction) TransactionRepository(alfio.repository.TransactionRepository) HttpClient(java.net.http.HttpClient) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) TicketRepository(alfio.repository.TicketRepository) UTF_8(java.nio.charset.StandardCharsets.UTF_8) IOException(java.io.IOException) PaymentInfo(alfio.model.transaction.capabilities.PaymentInfo) WebhookHandler(alfio.model.transaction.capabilities.WebhookHandler) InputStreamReader(java.io.InputStreamReader) Component(org.springframework.stereotype.Component) Validate(org.apache.commons.lang3.Validate) StringReader(java.io.StringReader) TicketReservation(alfio.model.TicketReservation) Data(lombok.Data) Log4j2(lombok.extern.log4j.Log4j2) PaymentWebhookResult(alfio.manager.support.PaymentWebhookResult) PaymentManagerUtils.invalidateExistingTransactions(alfio.manager.payment.PaymentManagerUtils.invalidateExistingTransactions) AllArgsConstructor(lombok.AllArgsConstructor) ConfigurationKeys(alfio.model.system.ConfigurationKeys) WAITING_EXTERNAL_CONFIRMATION(alfio.model.TicketReservation.TicketReservationStatus.WAITING_EXTERNAL_CONFIRMATION) InputStream(java.io.InputStream) HttpRequest(java.net.http.HttpRequest) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) JsonObject(com.google.gson.JsonObject)

Aggregations

PurchaseContextManager (alfio.manager.PurchaseContextManager)1 PaymentManagerUtils.invalidateExistingTransactions (alfio.manager.payment.PaymentManagerUtils.invalidateExistingTransactions)1 FeeCalculator (alfio.manager.support.FeeCalculator)1 PaymentResult (alfio.manager.support.PaymentResult)1 PaymentWebhookResult (alfio.manager.support.PaymentWebhookResult)1 ConfigurationLevel (alfio.manager.system.ConfigurationLevel)1 ConfigurationManager (alfio.manager.system.ConfigurationManager)1 MaybeConfiguration (alfio.manager.system.ConfigurationManager.MaybeConfiguration)1 PaymentInformation (alfio.model.PaymentInformation)1 PurchaseContext (alfio.model.PurchaseContext)1 TicketReservation (alfio.model.TicketReservation)1 EXTERNAL_PROCESSING_PAYMENT (alfio.model.TicketReservation.TicketReservationStatus.EXTERNAL_PROCESSING_PAYMENT)1 WAITING_EXTERNAL_CONFIRMATION (alfio.model.TicketReservation.TicketReservationStatus.WAITING_EXTERNAL_CONFIRMATION)1 ConfigurationKeys (alfio.model.system.ConfigurationKeys)1 alfio.model.transaction (alfio.model.transaction)1 PaymentInfo (alfio.model.transaction.capabilities.PaymentInfo)1 RefundRequest (alfio.model.transaction.capabilities.RefundRequest)1 WebhookHandler (alfio.model.transaction.capabilities.WebhookHandler)1 MollieToken (alfio.model.transaction.token.MollieToken)1 MollieWebhookPayload (alfio.model.transaction.webhook.MollieWebhookPayload)1