use of com.salesmanager.core.model.payments.Transaction in project shopizer by shopizer-ecommerce.
the class ShoppingOrderController method commitOrder.
private Order commitOrder(ShopOrder order, HttpServletRequest request, Locale locale) throws Exception, ServiceException {
LOGGER.info("Entering comitOrder");
MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
Language language = (Language) request.getAttribute("LANGUAGE");
String userName = null;
String password = null;
PersistableCustomer customer = order.getCustomer();
/**
* set username and password to persistable object *
*/
LOGGER.info("Set username and password to customer");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Customer authCustomer = null;
if (auth != null && request.isUserInRole("AUTH_CUSTOMER")) {
LOGGER.info("Customer authenticated");
authCustomer = customerFacade.getCustomerByUserName(auth.getName(), store);
// set id and authentication information
customer.setUserName(authCustomer.getNick());
// customer.setEncodedPassword(authCustomer.getPassword());
customer.setId(authCustomer.getId());
} else {
// set customer id to null
customer.setId(null);
}
// if the customer is new, generate a password
LOGGER.info("New customer generate password");
if (customer.getId() == null || customer.getId() == 0) {
// new customer
// password = UserReset.generateRandomString();
// String encodedPassword = passwordEncoder.encode(password);
// customer.setEncodedPassword(encodedPassword);
}
if (order.isShipToBillingAdress()) {
customer.setDelivery(customer.getBilling());
}
LOGGER.info("Before creating new volatile");
Customer modelCustomer = null;
try {
// set groups
if (authCustomer == null) {
// not authenticated, create a new volatile user
modelCustomer = customerFacade.getCustomerModel(customer, store, language);
customerFacade.setCustomerModelDefaultProperties(modelCustomer, store);
userName = modelCustomer.getNick();
LOGGER.debug("About to persist volatile customer to database.");
if (modelCustomer.getDefaultLanguage() == null) {
modelCustomer.setDefaultLanguage(languageService.toLanguage(locale));
}
customerService.saveOrUpdate(modelCustomer);
} else {
// use existing customer
LOGGER.info("Populate customer model");
modelCustomer = customerFacade.populateCustomerModel(authCustomer, customer, store, language);
}
} catch (Exception e) {
throw new ServiceException(e);
}
LOGGER.debug("About to save transaction");
Order modelOrder = null;
Transaction initialTransaction = (Transaction) super.getSessionAttribute(Constants.INIT_TRANSACTION_KEY, request);
if (initialTransaction != null) {
modelOrder = orderFacade.processOrder(order, modelCustomer, initialTransaction, store, language);
} else {
modelOrder = orderFacade.processOrder(order, modelCustomer, store, language);
}
// save order id in session
super.setSessionAttribute(Constants.ORDER_ID, modelOrder.getId(), request);
// set a unique token for confirmation
super.setSessionAttribute(Constants.ORDER_ID_TOKEN, modelOrder.getId(), request);
LOGGER.debug("Transaction ended and order saved");
LOGGER.debug("Remove cart");
// get cart
String cartCode = super.getSessionAttribute(Constants.SHOPPING_CART, request);
if (StringUtils.isNotBlank(cartCode)) {
try {
shoppingCartFacade.setOrderId(cartCode, modelOrder.getId(), store);
} catch (Exception e) {
LOGGER.error("Cannot update cart " + cartCode, e);
throw new ServiceException(e);
}
}
// cleanup the order objects
super.removeAttribute(Constants.ORDER, request);
super.removeAttribute(Constants.ORDER_SUMMARY, request);
super.removeAttribute(Constants.INIT_TRANSACTION_KEY, request);
super.removeAttribute(Constants.SHIPPING_OPTIONS, request);
super.removeAttribute(Constants.SHIPPING_SUMMARY, request);
super.removeAttribute(Constants.SHOPPING_CART, request);
LOGGER.debug("Refresh customer");
try {
// refresh customer --
modelCustomer = customerFacade.getCustomerByUserName(modelCustomer.getNick(), store);
// if has downloads, authenticate
// check if any downloads exist for this order6
List<OrderProductDownload> orderProductDownloads = orderProdctDownloadService.getByOrderId(modelOrder.getId());
if (CollectionUtils.isNotEmpty(orderProductDownloads)) {
LOGGER.debug("Is user authenticated ? ", auth.isAuthenticated());
if (auth != null && request.isUserInRole("AUTH_CUSTOMER")) {
// already authenticated
} else {
// authenticate
customerFacade.authenticate(modelCustomer, userName, password);
super.setSessionAttribute(Constants.CUSTOMER, modelCustomer, request);
}
// send new user registration template
if (order.getCustomer().getId() == null || order.getCustomer().getId().longValue() == 0) {
// send email for new customer
// set clear password for email
customer.setPassword(password);
customer.setUserName(userName);
emailTemplatesUtils.sendRegistrationEmail(customer, store, locale, request.getContextPath());
}
}
// send order confirmation email to customer
emailTemplatesUtils.sendOrderEmail(modelCustomer.getEmailAddress(), modelCustomer, modelOrder, locale, language, store, request.getContextPath());
if (orderService.hasDownloadFiles(modelOrder)) {
emailTemplatesUtils.sendOrderDownloadEmail(modelCustomer, modelOrder, store, locale, request.getContextPath());
}
// send order confirmation email to merchant
emailTemplatesUtils.sendOrderEmail(store.getStoreEmailAddress(), modelCustomer, modelOrder, locale, language, store, request.getContextPath());
} catch (Exception e) {
LOGGER.error("Error while post processing order", e);
}
return modelOrder;
}
use of com.salesmanager.core.model.payments.Transaction in project shopizer by shopizer-ecommerce.
the class ShoppingOrderPaymentController method paymentAction.
/**
* Recalculates shipping and tax following a change in country or province
*
* @param order
* @param request
* @param response
* @param locale
* @return
* @throws Exception
*/
@RequestMapping(value = { "/order/payment/{action}/{paymentmethod}.html" }, method = RequestMethod.POST)
@ResponseBody
public String paymentAction(@Valid @ModelAttribute(value = "order") ShopOrder order, @PathVariable String action, @PathVariable String paymentmethod, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
Language language = (Language) request.getAttribute("LANGUAGE");
MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
String shoppingCartCode = getSessionAttribute(Constants.SHOPPING_CART, request);
Validate.notNull(shoppingCartCode, "shoppingCartCode does not exist in the session");
AjaxResponse ajaxResponse = new AjaxResponse();
try {
com.salesmanager.core.model.shoppingcart.ShoppingCart cart = shoppingCartFacade.getShoppingCartModel(shoppingCartCode, store);
Set<ShoppingCartItem> items = cart.getLineItems();
List<ShoppingCartItem> cartItems = new ArrayList<ShoppingCartItem>(items);
order.setShoppingCartItems(cartItems);
// validate order first
Map<String, String> messages = new TreeMap<String, String>();
orderFacade.validateOrder(order, new BeanPropertyBindingResult(order, "order"), messages, store, locale);
if (CollectionUtils.isNotEmpty(messages.values())) {
for (String key : messages.keySet()) {
String value = messages.get(key);
ajaxResponse.addValidationMessage(key, value);
}
ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_VALIDATION_FAILED);
return ajaxResponse.toJSONString();
}
IntegrationConfiguration config = paymentService.getPaymentConfiguration(order.getPaymentModule(), store);
IntegrationModule integrationModule = paymentService.getPaymentMethodByCode(store, order.getPaymentModule());
// OrderTotalSummary orderTotalSummary =
// orderFacade.calculateOrderTotal(store, order, language);
OrderTotalSummary orderTotalSummary = super.getSessionAttribute(Constants.ORDER_SUMMARY, request);
if (orderTotalSummary == null) {
orderTotalSummary = orderFacade.calculateOrderTotal(store, order, language);
super.setSessionAttribute(Constants.ORDER_SUMMARY, orderTotalSummary, request);
}
ShippingSummary summary = (ShippingSummary) request.getSession().getAttribute("SHIPPING_SUMMARY");
if (summary != null) {
order.setShippingSummary(summary);
}
if (action.equals(INIT_ACTION)) {
if (paymentmethod.equals("PAYPAL")) {
try {
PaymentModule module = paymentService.getPaymentModule("paypal-express-checkout");
PayPalExpressCheckoutPayment p = (PayPalExpressCheckoutPayment) module;
PaypalPayment payment = new PaypalPayment();
payment.setCurrency(store.getCurrency());
Transaction transaction = p.initPaypalTransaction(store, cartItems, orderTotalSummary, payment, config, integrationModule);
transactionService.create(transaction);
super.setSessionAttribute(Constants.INIT_TRANSACTION_KEY, transaction, request);
StringBuilder urlAppender = new StringBuilder();
urlAppender.append(coreConfiguration.getProperty("PAYPAL_EXPRESSCHECKOUT_REGULAR"));
urlAppender.append(transaction.getTransactionDetails().get("TOKEN"));
if (config.getEnvironment().equals(com.salesmanager.core.business.constants.Constants.PRODUCTION_ENVIRONMENT)) {
StringBuilder url = new StringBuilder().append(coreConfiguration.getProperty("PAYPAL_EXPRESSCHECKOUT_PRODUCTION")).append(urlAppender.toString());
ajaxResponse.addEntry("url", url.toString());
} else {
StringBuilder url = new StringBuilder().append(coreConfiguration.getProperty("PAYPAL_EXPRESSCHECKOUT_SANDBOX")).append(urlAppender.toString());
ajaxResponse.addEntry("url", url.toString());
}
// keep order in session when user comes back from pp
super.setSessionAttribute(Constants.ORDER, order, request);
ajaxResponse.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED);
} catch (Exception e) {
ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
}
} else if (paymentmethod.equals("stripe3")) {
try {
PaymentModule module = paymentService.getPaymentModule(paymentmethod);
Stripe3Payment p = (Stripe3Payment) module;
PaypalPayment payment = new PaypalPayment();
payment.setCurrency(store.getCurrency());
Transaction transaction = p.initTransaction(store, null, orderTotalSummary.getTotal(), null, config, integrationModule);
transactionService.create(transaction);
super.setSessionAttribute(Constants.INIT_TRANSACTION_KEY, transaction, request);
// keep order in session when user comes back from pp
super.setSessionAttribute(Constants.ORDER, order, request);
ajaxResponse.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED);
ajaxResponse.setDataMap(transaction.getTransactionDetails());
} catch (Exception e) {
ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
}
}
}
} catch (Exception e) {
LOGGER.error("Error while performing payment action " + action + " for payment method " + paymentmethod, e);
ajaxResponse.setErrorMessage(e);
ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
}
return ajaxResponse.toJSONString();
}
use of com.salesmanager.core.model.payments.Transaction in project shopizer by shopizer-ecommerce.
the class PayPalExpressCheckoutPayment method initPaypalTransaction.
/* @Override
public Transaction capture(MerchantStore store, Customer customer,
List<ShoppingCartItem> items, BigDecimal amount, Payment payment, Transaction transaction,
IntegrationConfiguration configuration, IntegrationModule module)
throws IntegrationException {
com.salesmanager.core.business.payments.model.PaypalPayment paypalPayment = (com.salesmanager.core.business.payments.model.PaypalPayment)payment;
Validate.notNull(paypalPayment.getPaymentToken(), "A paypal payment token is required to process this transaction");
return processTransaction(store, customer, items, amount, paypalPayment, configuration, module);
}*/
public Transaction initPaypalTransaction(MerchantStore store, List<ShoppingCartItem> items, OrderTotalSummary summary, Payment payment, IntegrationConfiguration configuration, IntegrationModule module) throws IntegrationException {
Validate.notNull(configuration, "Configuration must not be null");
Validate.notNull(payment, "Payment must not be null");
Validate.notNull(summary, "OrderTotalSummary must not be null");
try {
PaymentDetailsType paymentDetails = new PaymentDetailsType();
if (configuration.getIntegrationKeys().get("transaction").equalsIgnoreCase(TransactionType.AUTHORIZECAPTURE.name())) {
paymentDetails.setPaymentAction(urn.ebay.apis.eBLBaseComponents.PaymentActionCodeType.SALE);
} else {
paymentDetails.setPaymentAction(urn.ebay.apis.eBLBaseComponents.PaymentActionCodeType.AUTHORIZATION);
}
List<PaymentDetailsItemType> lineItems = new ArrayList<PaymentDetailsItemType>();
for (ShoppingCartItem cartItem : items) {
PaymentDetailsItemType item = new PaymentDetailsItemType();
BasicAmountType amt = new BasicAmountType();
amt.setCurrencyID(urn.ebay.apis.eBLBaseComponents.CurrencyCodeType.fromValue(payment.getCurrency().getCode()));
amt.setValue(pricingService.getStringAmount(cartItem.getFinalPrice().getFinalPrice(), store));
// itemsTotal = itemsTotal.add(cartItem.getSubTotal());
int itemQuantity = cartItem.getQuantity();
item.setQuantity(itemQuantity);
item.setName(cartItem.getProduct().getProductDescription().getName());
item.setAmount(amt);
// System.out.println(pricingService.getStringAmount(cartItem.getSubTotal(), store));
lineItems.add(item);
}
List<OrderTotal> orderTotals = summary.getTotals();
BigDecimal tax = null;
for (OrderTotal total : orderTotals) {
if (total.getModule().equals(Constants.OT_SHIPPING_MODULE_CODE)) {
BasicAmountType shipping = new BasicAmountType();
shipping.setCurrencyID(urn.ebay.apis.eBLBaseComponents.CurrencyCodeType.fromValue(store.getCurrency().getCode()));
shipping.setValue(pricingService.getStringAmount(total.getValue(), store));
// System.out.println(pricingService.getStringAmount(total.getValue(), store));
paymentDetails.setShippingTotal(shipping);
}
if (total.getModule().equals(Constants.OT_HANDLING_MODULE_CODE)) {
BasicAmountType handling = new BasicAmountType();
handling.setCurrencyID(urn.ebay.apis.eBLBaseComponents.CurrencyCodeType.fromValue(store.getCurrency().getCode()));
handling.setValue(pricingService.getStringAmount(total.getValue(), store));
// System.out.println(pricingService.getStringAmount(total.getValue(), store));
paymentDetails.setHandlingTotal(handling);
}
if (total.getModule().equals(Constants.OT_TAX_MODULE_CODE)) {
if (tax == null) {
tax = new BigDecimal("0");
}
tax = tax.add(total.getValue());
}
}
if (tax != null) {
BasicAmountType taxAmnt = new BasicAmountType();
taxAmnt.setCurrencyID(urn.ebay.apis.eBLBaseComponents.CurrencyCodeType.fromValue(store.getCurrency().getCode()));
taxAmnt.setValue(pricingService.getStringAmount(tax, store));
// System.out.println(pricingService.getStringAmount(tax, store));
paymentDetails.setTaxTotal(taxAmnt);
}
BasicAmountType itemTotal = new BasicAmountType();
itemTotal.setCurrencyID(urn.ebay.apis.eBLBaseComponents.CurrencyCodeType.fromValue(store.getCurrency().getCode()));
itemTotal.setValue(pricingService.getStringAmount(summary.getSubTotal(), store));
paymentDetails.setItemTotal(itemTotal);
paymentDetails.setPaymentDetailsItem(lineItems);
BasicAmountType orderTotal = new BasicAmountType();
orderTotal.setCurrencyID(urn.ebay.apis.eBLBaseComponents.CurrencyCodeType.fromValue(store.getCurrency().getCode()));
orderTotal.setValue(pricingService.getStringAmount(summary.getTotal(), store));
// System.out.println(pricingService.getStringAmount(itemsTotal, store));
paymentDetails.setOrderTotal(orderTotal);
List<PaymentDetailsType> paymentDetailsList = new ArrayList<PaymentDetailsType>();
paymentDetailsList.add(paymentDetails);
String baseScheme = store.getDomainName();
String scheme = coreConfiguration.getProperty("SHOP_SCHEME");
if (!StringUtils.isBlank(scheme)) {
baseScheme = new StringBuilder().append(coreConfiguration.getProperty("SHOP_SCHEME", "http")).append("://").append(store.getDomainName()).toString();
}
StringBuilder RETURN_URL = new StringBuilder();
RETURN_URL.append(baseScheme);
if (!StringUtils.isBlank(baseScheme) && !baseScheme.endsWith(Constants.SLASH)) {
RETURN_URL.append(Constants.SLASH);
}
RETURN_URL.append(coreConfiguration.getProperty("CONTEXT_PATH", "sm-shop"));
SetExpressCheckoutRequestDetailsType setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
String returnUrl = RETURN_URL.toString() + new StringBuilder().append(Constants.SHOP_URI).append("/paypal/checkout").append(coreConfiguration.getProperty("URL_EXTENSION", ".html")).append("/success").toString();
String cancelUrl = RETURN_URL.toString() + new StringBuilder().append(Constants.SHOP_URI).append("/paypal/checkout").append(coreConfiguration.getProperty("URL_EXTENSION", ".html")).append("/cancel").toString();
setExpressCheckoutRequestDetails.setReturnURL(returnUrl);
setExpressCheckoutRequestDetails.setCancelURL(cancelUrl);
setExpressCheckoutRequestDetails.setPaymentDetails(paymentDetailsList);
SetExpressCheckoutRequestType setExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails);
setExpressCheckoutRequest.setVersion("104.0");
SetExpressCheckoutReq setExpressCheckoutReq = new SetExpressCheckoutReq();
setExpressCheckoutReq.setSetExpressCheckoutRequest(setExpressCheckoutRequest);
String mode = "sandbox";
String env = configuration.getEnvironment();
if (Constants.PRODUCTION_ENVIRONMENT.equals(env)) {
mode = "production";
}
Map<String, String> configurationMap = new HashMap<String, String>();
configurationMap.put("mode", mode);
configurationMap.put("acct1.UserName", configuration.getIntegrationKeys().get("username"));
configurationMap.put("acct1.Password", configuration.getIntegrationKeys().get("api"));
configurationMap.put("acct1.Signature", configuration.getIntegrationKeys().get("signature"));
PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap);
SetExpressCheckoutResponseType setExpressCheckoutResponse = service.setExpressCheckout(setExpressCheckoutReq);
String token = setExpressCheckoutResponse.getToken();
String correlationID = setExpressCheckoutResponse.getCorrelationID();
String ack = setExpressCheckoutResponse.getAck().getValue();
if (!"Success".equals(ack)) {
LOGGER.error("Wrong value from init transaction " + ack);
throw new IntegrationException("Wrong paypal ack from init transaction " + ack);
}
Transaction transaction = new Transaction();
transaction.setAmount(summary.getTotal());
// transaction.setOrder(order);
transaction.setTransactionDate(new Date());
transaction.setTransactionType(TransactionType.INIT);
transaction.setPaymentType(PaymentType.PAYPAL);
transaction.getTransactionDetails().put("TOKEN", token);
transaction.getTransactionDetails().put("CORRELATION", correlationID);
return transaction;
// redirect user to
// https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-5LL13394G30048922
} catch (Exception e) {
e.printStackTrace();
throw new IntegrationException(e);
}
}
use of com.salesmanager.core.model.payments.Transaction in project shopizer by shopizer-ecommerce.
the class PayPalExpressCheckoutPayment method refund.
@Override
public Transaction refund(boolean partial, MerchantStore store, Transaction transaction, Order order, BigDecimal amount, IntegrationConfiguration configuration, IntegrationModule module) throws IntegrationException {
try {
Validate.notNull(transaction, "Transaction cannot be null");
Validate.notNull(transaction.getTransactionDetails().get("TRANSACTIONID"), "Transaction details must contain a TRANSACTIONID");
Validate.notNull(order, "Order must not be null");
Validate.notNull(order.getCurrency(), "Order nust contain Currency object");
String mode = "sandbox";
String env = configuration.getEnvironment();
if (Constants.PRODUCTION_ENVIRONMENT.equals(env)) {
mode = "production";
}
RefundTransactionRequestType refundTransactionRequest = new RefundTransactionRequestType();
refundTransactionRequest.setVersion("104.0");
RefundTransactionReq refundRequest = new RefundTransactionReq();
refundRequest.setRefundTransactionRequest(refundTransactionRequest);
Map<String, String> configurationMap = new HashMap<String, String>();
configurationMap.put("mode", mode);
configurationMap.put("acct1.UserName", configuration.getIntegrationKeys().get("username"));
configurationMap.put("acct1.Password", configuration.getIntegrationKeys().get("api"));
configurationMap.put("acct1.Signature", configuration.getIntegrationKeys().get("signature"));
PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap);
RefundType refundType = RefundType.FULL;
if (partial) {
refundType = RefundType.PARTIAL;
}
refundTransactionRequest.setRefundType(refundType);
BasicAmountType refundAmount = new BasicAmountType();
refundAmount.setValue(pricingService.getStringAmount(amount, store));
refundAmount.setCurrencyID(urn.ebay.apis.eBLBaseComponents.CurrencyCodeType.fromValue(order.getCurrency().getCode()));
refundTransactionRequest.setAmount(refundAmount);
refundTransactionRequest.setTransactionID(transaction.getTransactionDetails().get("TRANSACTIONID"));
RefundTransactionResponseType refundTransactionResponse = service.refundTransaction(refundRequest);
String refundAck = refundTransactionResponse.getAck().getValue();
if (!"Success".equals(refundAck)) {
LOGGER.error("Wrong value from transaction commit " + refundAck);
throw new IntegrationException(ServiceException.EXCEPTION_TRANSACTION_DECLINED, "Paypal refund transaction code [" + refundTransactionResponse.getErrors().get(0).getErrorCode() + "], message-> " + refundTransactionResponse.getErrors().get(0).getShortMessage());
}
Transaction newTransaction = new Transaction();
newTransaction.setAmount(amount);
newTransaction.setTransactionDate(new Date());
newTransaction.setTransactionType(TransactionType.REFUND);
newTransaction.setPaymentType(PaymentType.PAYPAL);
newTransaction.getTransactionDetails().put("TRANSACTIONID", refundTransactionResponse.getRefundTransactionID());
transaction.getTransactionDetails().put("CORRELATION", refundTransactionResponse.getCorrelationID());
return newTransaction;
} catch (Exception e) {
if (e instanceof IntegrationException) {
throw (IntegrationException) e;
} else {
throw new IntegrationException(e);
}
}
}
use of com.salesmanager.core.model.payments.Transaction in project shopizer by shopizer-ecommerce.
the class Stripe3Payment method authorizeAndCapture.
@Override
public Transaction authorizeAndCapture(MerchantStore store, Customer customer, List<ShoppingCartItem> items, BigDecimal amount, Payment payment, IntegrationConfiguration configuration, IntegrationModule module) throws IntegrationException {
String apiKey = configuration.getIntegrationKeys().get("secretKey");
if (payment.getPaymentMetaData() == null || StringUtils.isBlank(apiKey)) {
IntegrationException te = new IntegrationException("Can't process Stripe, missing payment.metaData");
te.setExceptionType(IntegrationException.TRANSACTION_EXCEPTION);
te.setMessageCode("message.payment.error");
te.setErrorCode(IntegrationException.TRANSACTION_EXCEPTION);
throw te;
}
String token = payment.getPaymentMetaData().get("stripe_token");
if (StringUtils.isBlank(token)) {
// possibly from api
token = payment.getPaymentMetaData().get("paymentToken");
}
if (StringUtils.isBlank(token)) {
IntegrationException te = new IntegrationException("Can't process Stripe, missing stripe token");
te.setExceptionType(IntegrationException.TRANSACTION_EXCEPTION);
te.setMessageCode("message.payment.error");
te.setErrorCode(IntegrationException.TRANSACTION_EXCEPTION);
throw te;
}
Transaction transaction = new Transaction();
try {
String amnt = productPriceUtils.getAdminFormatedAmount(store, amount);
// stripe does not support floating point
// so amnt * 100 or remove floating point
// 553.47 = 55347
String strAmount = String.valueOf(amnt);
strAmount = strAmount.replace(".", "");
/*Map<String, Object> chargeParams = new HashMap<String, Object>();
chargeParams.put("amount", strAmount);
chargeParams.put("capture", true);
chargeParams.put("currency", store.getCurrency().getCode());
chargeParams.put("source", token); // obtained with Stripe.js
chargeParams.put("description", new StringBuilder().append(TRANSACTION).append(" - ").append(store.getStorename()).toString());
*/
Stripe.apiKey = apiKey;
PaymentIntent paymentIntent = PaymentIntent.retrieve(token);
PaymentIntentCaptureParams params = PaymentIntentCaptureParams.builder().setAmountToCapture(Long.parseLong(strAmount)).setStatementDescriptor(store.getStorename().length() > 22 ? store.getStorename().substring(0, 22) : store.getStorename()).build();
paymentIntent = paymentIntent.capture(params);
// Map<String,String> metadata = ch.getMetadata();
transaction.setAmount(amount);
// transaction.setOrder(order);
transaction.setTransactionDate(new Date());
transaction.setTransactionType(TransactionType.AUTHORIZECAPTURE);
transaction.setPaymentType(PaymentType.CREDITCARD);
transaction.getTransactionDetails().put("TRANSACTIONID", token);
transaction.getTransactionDetails().put("TRNAPPROVED", paymentIntent.getStatus());
transaction.getTransactionDetails().put("TRNORDERNUMBER", paymentIntent.getId());
transaction.getTransactionDetails().put("MESSAGETEXT", null);
} catch (Exception e) {
e.printStackTrace();
throw buildException(e);
}
return transaction;
}
Aggregations