Search in sources :

Example 1 with APIContext

use of com.paypal.base.rest.APIContext in project alf.io by alfio-event.

the class PaypalManager method refund.

public boolean refund(alfio.model.transaction.Transaction transaction, Event event, Optional<Integer> amount) {
    String captureId = transaction.getTransactionId();
    try {
        APIContext apiContext = getApiContext(event);
        String amountOrFull = amount.map(MonetaryUtil::formatCents).orElse("full");
        log.info("Paypal: trying to do a refund for payment {} with amount: {}", captureId, amountOrFull);
        Capture capture = Capture.get(apiContext, captureId);
        RefundRequest refundRequest = new RefundRequest();
        amount.ifPresent(a -> refundRequest.setAmount(new Amount(capture.getAmount().getCurrency(), formatCents(a))));
        DetailedRefund res = capture.refund(apiContext, refundRequest);
        log.info("Paypal: refund for payment {} executed with success for amount: {}", captureId, amountOrFull);
        return true;
    } catch (PayPalRESTException ex) {
        log.warn("Paypal: was not able to refund payment with id " + captureId, ex);
        return false;
    }
}
Also used : APIContext(com.paypal.base.rest.APIContext) PayPalRESTException(com.paypal.base.rest.PayPalRESTException)

Example 2 with APIContext

use of com.paypal.base.rest.APIContext in project alf.io by alfio-event.

the class PaypalManager method getInfo.

Optional<PaymentInformation> getInfo(String paymentId, String transactionId, Event event, Supplier<String> platformFeeSupplier) {
    try {
        String refund = null;
        APIContext apiContext = getApiContext(event);
        // check for backward compatibility  reason...
        if (paymentId != null) {
            // navigate in all refund objects and sum their amount
            refund = Payment.get(apiContext, paymentId).getTransactions().stream().map(Transaction::getRelatedResources).flatMap(List::stream).filter(f -> f.getRefund() != null).map(RelatedResources::getRefund).map(Refund::getAmount).map(Amount::getTotal).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add).toPlainString();
        // 
        }
        Capture c = Capture.get(apiContext, transactionId);
        String gatewayFee = Optional.ofNullable(c.getTransactionFee()).map(Currency::getValue).map(BigDecimal::new).map(MonetaryUtil::unitToCents).map(String::valueOf).orElse(null);
        return Optional.of(new PaymentInformation(c.getAmount().getTotal(), refund, gatewayFee, platformFeeSupplier.get()));
    } catch (PayPalRESTException ex) {
        log.warn("Paypal: error while fetching information for payment id " + transactionId, ex);
        return Optional.empty();
    }
}
Also used : UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) java.util(java.util) MessageDigest(java.security.MessageDigest) TicketReservationRepository(alfio.repository.TicketReservationRepository) ConfigurationManager(alfio.manager.system.ConfigurationManager) Cache(com.github.benmanes.caffeine.cache.Cache) StringUtils(org.apache.commons.lang3.StringUtils) Supplier(java.util.function.Supplier) com.paypal.api.payments(com.paypal.api.payments) BigDecimal(java.math.BigDecimal) MonetaryUtil.formatCents(alfio.util.MonetaryUtil.formatCents) Pair(org.apache.commons.lang3.tuple.Pair) APIContext(com.paypal.base.rest.APIContext) HmacAlgorithms(org.apache.commons.codec.digest.HmacAlgorithms) MessageSource(org.springframework.context.MessageSource) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) TicketRepository(alfio.repository.TicketRepository) HmacUtils(org.apache.commons.codec.digest.HmacUtils) Currency(com.paypal.api.payments.Currency) FeeCalculator(alfio.manager.support.FeeCalculator) PayPalRESTException(com.paypal.base.rest.PayPalRESTException) StandardCharsets(java.nio.charset.StandardCharsets) DateUtils(org.apache.commons.lang3.time.DateUtils) TimeUnit(java.util.concurrent.TimeUnit) Component(org.springframework.stereotype.Component) MonetaryUtil(alfio.util.MonetaryUtil) alfio.model(alfio.model) Configuration(alfio.model.system.Configuration) Log4j2(lombok.extern.log4j.Log4j2) Event(alfio.model.Event) AllArgsConstructor(lombok.AllArgsConstructor) DigestUtils(org.apache.commons.codec.digest.DigestUtils) ConfigurationKeys(alfio.model.system.ConfigurationKeys) Currency(com.paypal.api.payments.Currency) MonetaryUtil(alfio.util.MonetaryUtil) APIContext(com.paypal.base.rest.APIContext) PayPalRESTException(com.paypal.base.rest.PayPalRESTException) BigDecimal(java.math.BigDecimal)

Example 3 with APIContext

use of com.paypal.base.rest.APIContext in project alf.io by alfio-event.

the class PaypalManager method createCheckoutRequest.

public String createCheckoutRequest(Event event, String reservationId, OrderSummary orderSummary, CustomerName customerName, String email, String billingAddress, Locale locale, boolean postponeAssignment, boolean invoiceRequested) throws Exception {
    APIContext apiContext = getApiContext(event);
    Optional<String> experienceProfileId = getOrCreateWebProfile(event, locale, apiContext);
    List<Transaction> transactions = buildPaymentDetails(event, orderSummary, reservationId, locale);
    String eventName = event.getShortName();
    Payer payer = new Payer();
    payer.setPaymentMethod("paypal");
    Payment payment = new Payment();
    payment.setIntent("sale");
    payment.setPayer(payer);
    payment.setTransactions(transactions);
    RedirectUrls redirectUrls = new RedirectUrls();
    String baseUrl = StringUtils.removeEnd(configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.BASE_URL)), "/");
    String bookUrl = baseUrl + "/event/" + eventName + "/reservation/" + reservationId + "/book";
    UriComponentsBuilder bookUrlBuilder = UriComponentsBuilder.fromUriString(bookUrl).queryParam("fullName", customerName.getFullName()).queryParam("firstName", customerName.getFirstName()).queryParam("lastName", customerName.getLastName()).queryParam("email", email).queryParam("billingAddress", billingAddress).queryParam("postponeAssignment", postponeAssignment).queryParam("invoiceRequested", invoiceRequested).queryParam("hmac", computeHMAC(customerName, email, billingAddress, event));
    String finalUrl = bookUrlBuilder.toUriString();
    redirectUrls.setCancelUrl(finalUrl + "&paypal-cancel=true");
    redirectUrls.setReturnUrl(finalUrl + "&paypal-success=true");
    payment.setRedirectUrls(redirectUrls);
    experienceProfileId.ifPresent(payment::setExperienceProfileId);
    Payment createdPayment = payment.create(apiContext);
    TicketReservation reservation = ticketReservationRepository.findReservationById(reservationId);
    // add 15 minutes of validity in case the paypal flow is slow
    ticketReservationRepository.updateValidity(reservationId, DateUtils.addMinutes(reservation.getValidity(), 15));
    if (!"created".equals(createdPayment.getState())) {
        throw new Exception(createdPayment.getFailureReason());
    }
    // extract url for approval
    return createdPayment.getLinks().stream().filter(l -> "approval_url".equals(l.getRel())).findFirst().map(Links::getHref).orElseThrow(IllegalStateException::new);
}
Also used : UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) java.util(java.util) MessageDigest(java.security.MessageDigest) TicketReservationRepository(alfio.repository.TicketReservationRepository) ConfigurationManager(alfio.manager.system.ConfigurationManager) Cache(com.github.benmanes.caffeine.cache.Cache) StringUtils(org.apache.commons.lang3.StringUtils) Supplier(java.util.function.Supplier) com.paypal.api.payments(com.paypal.api.payments) BigDecimal(java.math.BigDecimal) MonetaryUtil.formatCents(alfio.util.MonetaryUtil.formatCents) Pair(org.apache.commons.lang3.tuple.Pair) APIContext(com.paypal.base.rest.APIContext) HmacAlgorithms(org.apache.commons.codec.digest.HmacAlgorithms) MessageSource(org.springframework.context.MessageSource) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) TicketRepository(alfio.repository.TicketRepository) HmacUtils(org.apache.commons.codec.digest.HmacUtils) Currency(com.paypal.api.payments.Currency) FeeCalculator(alfio.manager.support.FeeCalculator) PayPalRESTException(com.paypal.base.rest.PayPalRESTException) StandardCharsets(java.nio.charset.StandardCharsets) DateUtils(org.apache.commons.lang3.time.DateUtils) TimeUnit(java.util.concurrent.TimeUnit) Component(org.springframework.stereotype.Component) MonetaryUtil(alfio.util.MonetaryUtil) alfio.model(alfio.model) Configuration(alfio.model.system.Configuration) Log4j2(lombok.extern.log4j.Log4j2) Event(alfio.model.Event) AllArgsConstructor(lombok.AllArgsConstructor) DigestUtils(org.apache.commons.codec.digest.DigestUtils) ConfigurationKeys(alfio.model.system.ConfigurationKeys) PayPalRESTException(com.paypal.base.rest.PayPalRESTException) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) APIContext(com.paypal.base.rest.APIContext)

Aggregations

APIContext (com.paypal.base.rest.APIContext)3 PayPalRESTException (com.paypal.base.rest.PayPalRESTException)3 FeeCalculator (alfio.manager.support.FeeCalculator)2 ConfigurationManager (alfio.manager.system.ConfigurationManager)2 alfio.model (alfio.model)2 Event (alfio.model.Event)2 Configuration (alfio.model.system.Configuration)2 ConfigurationKeys (alfio.model.system.ConfigurationKeys)2 TicketRepository (alfio.repository.TicketRepository)2 TicketReservationRepository (alfio.repository.TicketReservationRepository)2 MonetaryUtil (alfio.util.MonetaryUtil)2 MonetaryUtil.formatCents (alfio.util.MonetaryUtil.formatCents)2 Cache (com.github.benmanes.caffeine.cache.Cache)2 Caffeine (com.github.benmanes.caffeine.cache.Caffeine)2 com.paypal.api.payments (com.paypal.api.payments)2 Currency (com.paypal.api.payments.Currency)2 BigDecimal (java.math.BigDecimal)2 StandardCharsets (java.nio.charset.StandardCharsets)2 MessageDigest (java.security.MessageDigest)2 java.util (java.util)2