CheckoutFiBean.java 15.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
/*
 * Copyright Codecrew Ry
 * 
 * All rights reserved.
 * 
 * This license applies to any software containing a notice placed by the 
 * copyright holder. Such software is herein referred to as the Software. 
 * This license covers modification, distribution and use of the Software. 
 * 
 * Any distribution and use in source and binary forms, with or without 
 * modification is not permitted without explicit written permission from the 
 * copyright owner. 
 * 
 * A non-exclusive royalty-free right is granted to the copyright owner of the 
 * Software to use, modify and distribute all modifications to the Software in 
 * future versions of the Software. 
 * 
 */
package fi.codecrew.moya.beans;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import fi.codecrew.moya.checkoutfi.CheckoutFiCheckParam;
import fi.codecrew.moya.checkoutfi.CheckoutFiPaymentParam;
import fi.codecrew.moya.checkoutfi.CheckoutQueryParam;
import fi.codecrew.moya.enums.apps.BillPermission;
import fi.codecrew.moya.facade.BillFacade;
import fi.codecrew.moya.model.Bill;
import fi.codecrew.moya.model.LanEventPrivateProperty;
import fi.codecrew.moya.model.LanEventPrivatePropertyKey;
import fi.codecrew.moya.util.CheckoutBank;
import fi.codecrew.moya.util.CheckoutReturnType;
import fi.codecrew.moya.utilities.PasswordFunctions;
import fi.codecrew.moya.utilities.moyamessage.MoyaEventType;

/**
 * Session Bean implementation class CheckoutFiBean
 */
@Stateless
@LocalBean
public class CheckoutFiBean implements CheckoutFiBeanLocal {

	private static final String STAMP_SPLITCHAR = "a";
	private static final String REMOTE_URL = "https://payment.checkout.fi";

	/**
	 * Default constructor.
	 */
	public CheckoutFiBean() {
		// TODO Auto-generated constructor stub
	}

	@EJB
	private EventBean eventbean;
	@EJB
	private PermissionBeanLocal permbean;
	@EJB
	private LoggingBeanLocal logbean;
	@EJB
	private BillFacade billfacade;
	@EJB
	private BillPBean billpbean;

	private static final Logger logger = LoggerFactory.getLogger(CheckoutFiBean.class);
	static final BigDecimal TO_CENTS = BigDecimal.valueOf(100);

	static final String DATEFORMAT = "yyyyMMdd";
	static final Set<String> DISCARD_BANKS = new HashSet<String>(Arrays.asList("ape", "tilisiirto", "neopay"));

	/**
	 * Notice! This is a long running function which creates a remote HTTP
	 * query.
	 * 
	 */

	@Override
	@RolesAllowed(BillPermission.S_READ_ALL)
	public boolean isBillPaid(Bill bill) {
		QueryBuilder cb = initQuerybuilder(CheckoutFiCheckParam.values());

		if (!cb.isCredentialsValid()) {
			throw new EJBException("Invalid Credentials");
		}

		final String priceInCents = Integer.toString(bill.totalPrice().multiply(TO_CENTS).intValue());

		cb.addParam(CheckoutFiCheckParam.STAMP, getStamp(bill));
		cb.addParam(CheckoutFiCheckParam.REFERENCE, bill.getReferenceNumber().toString());
		cb.addParam(CheckoutFiCheckParam.MERCHANT, cb.getMerchantId());
		cb.addParam(CheckoutFiCheckParam.AMOUNT, priceInCents);

		CloseableHttpResponse response = null;
		boolean ret = false;
		try {
			response = sendQuery(cb);
			InputStream queryContent = response.getEntity().getContent();

			String returnValue = parsePollXml(queryContent);
			int statusInt = Integer.parseInt(returnValue);
			// Verkkokauppaohjelmisto voi hyväksyä maksun suoritetuksi
			// kun maksun tila on 2,5,6,7,8,9 tai 10.
			switch (statusInt) {
			case 2:
			case 5:
			case 6:
			case 7:
			case 8:
			case 9:
			case 10:
				ret = true;
				break;
			default:

			}
		} catch (IOException e) {
			logger.warn("Error sending checkout.fi request", e);
		} finally {
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				logger.warn("Error closing checkout.fi request", e);
			}
		}
		return ret;
	}

	@Override
	public boolean isPaymentEnabled() {
		final LanEventPrivateProperty expire = eventbean.getPrivateProperty(LanEventPrivatePropertyKey.CHECKOUT_FI_KEY_EXPIRE);
		final String merchantid = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.CHECKOUT_FI_MERCHANT_ID);
		final String merchantPassword = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.CHECKOUT_FI_MERCHANT_PASSWORD);
		final boolean expired = (expire == null || expire.getDateValue() == null || new Date().after(expire.getDateValue()));

		boolean ret = !expired
				&& merchantid != null && !merchantid.isEmpty()
				&& merchantPassword != null && !merchantPassword.isEmpty();
		return ret;
	}

	protected QueryBuilder initQuerybuilder(CheckoutQueryParam[] params) {

		final LanEventPrivateProperty expire = eventbean.getPrivateProperty(LanEventPrivatePropertyKey.CHECKOUT_FI_KEY_EXPIRE);
		final String merchantid = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.CHECKOUT_FI_MERCHANT_ID);
		final String merchantPassword = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.CHECKOUT_FI_MERCHANT_PASSWORD);
		Date date = null;
		if (expire != null) {
			date = expire.getDateValue();
		}
		QueryBuilder ret = new QueryBuilder(params, date, merchantid, merchantPassword);
		return ret;

	}

	@Override
	@RolesAllowed(BillPermission.S_CREATE_VERKKOMAKSU)
	public List<CheckoutBank> getToken(Bill bill) {
		if (bill.isFoowavePaymentOver()) {
			return null;
		}
		QueryBuilder queryBuilder = initQuerybuilder(CheckoutFiPaymentParam.values());

		if (!queryBuilder.isCredentialsValid()) {
			return null;
		}

		final String returnUrl = new StringBuilder()
				.append("https://")
				.append(eventbean.getCurrentHostname())
				.append("/MoyaWeb/checkout/")
				.toString();

		final String priceInCents = Integer.toString(bill.totalPrice().multiply(TO_CENTS).intValue());

		queryBuilder.addParam(CheckoutFiPaymentParam.STAMP, getStamp(bill));
		queryBuilder.addParam(CheckoutFiPaymentParam.AMOUNT, priceInCents);
		queryBuilder.addParam(CheckoutFiPaymentParam.REFERENCE, bill.getReferenceNumber().toString());
		queryBuilder.addParam(CheckoutFiPaymentParam.MERCHANT, queryBuilder.getMerchantId());
		queryBuilder.addParam(CheckoutFiPaymentParam.RETURN, returnUrl + "return.jsf");
		queryBuilder.addParam(CheckoutFiPaymentParam.CANCEL, returnUrl + "cancel.jsf");
		queryBuilder.addParam(CheckoutFiPaymentParam.REJECT, returnUrl + "reject.jsf");
		queryBuilder.addParam(CheckoutFiPaymentParam.DELAYED, returnUrl + "delayed.jsf");
		queryBuilder.addParam(CheckoutFiPaymentParam.DELIVERY_DATE, new SimpleDateFormat(DATEFORMAT).format(new Date()));

		CloseableHttpResponse response = null;
		List<CheckoutBank> ret = null;
		InputStream queryContent = null;
		try {
			response = sendQuery(queryBuilder);
			queryContent = response.getEntity().getContent();
			ret = parseTokenXml(queryContent);
		} catch (IOException e) {
			logger.warn("Error sending checkout.fi request", e);
		} finally {
			try {
				if (queryContent != null)
					queryContent.close();
			} catch (IOException e1) {
				logger.warn("Error closing checkout.fi inputstream", e1);
			}
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				logger.warn("Error closing checkout.fi request", e);
			}
		}

		return ret;

	}

	private static CloseableHttpResponse sendQuery(QueryBuilder queryBuilder) throws ClientProtocolException, IOException {
		CloseableHttpResponse response = null;
		final HttpPost postRequest = new HttpPost(REMOTE_URL);
		postRequest.setEntity(new UrlEncodedFormEntity(queryBuilder.getNameValuePairs()));
		HttpClientBuilder cliBuilder = HttpClientBuilder.create();
		CloseableHttpClient cli = cliBuilder.build();
		response = cli.execute(postRequest);

		return response;
	}

	static final String getStamp(Bill bill) {
		final StringBuilder stamp = new StringBuilder();
		stamp.append(bill.getId());
		stamp.append(STAMP_SPLITCHAR);
		stamp.append(bill.getSentDate().getTime() / 1000);
		return stamp.toString();
	}

	protected static String parsePollXml(InputStream queryContent) {
		String ret = null;
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(queryContent);

			Element root = doc.getDocumentElement();
			//			root.normalize();
			Node status = root.getElementsByTagName("status").item(0);
			if (status != null) {
				ret = status.getTextContent();
				if (ret != null) {
					ret = ret.trim();
				}
			}
		} catch (SAXException | IOException | ParserConfigurationException e) {
			ret = null;
			logger.warn("Error parsing response from checkout response:", e);
		}
		return ret;
	}

	protected static List<CheckoutBank> parseTokenXml(InputStream inputStream) {
		try {

			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

			Document doc = dBuilder.parse(inputStream);

			Element root = doc.getDocumentElement();
			root.normalize();

			Node payments = root.getElementsByTagName("banks").item(0);

			NodeList paymentElements = payments.getChildNodes();
			List<CheckoutBank> retbanks = new ArrayList<CheckoutBank>();
			for (int i = 0; i < paymentElements.getLength(); ++i) {
				Node bank = paymentElements.item(i);
				if (bank.getNodeType() == 1) {
					CheckoutBank newBank = new CheckoutBank(bank);
					if (!DISCARD_BANKS.contains(newBank.getKey())) {
						retbanks.add(newBank);
					}
				}
			}
			return retbanks;
		} catch (SAXException | IOException | ParserConfigurationException e) {
			logger.warn("Error parsing response from checkout response:" + inputStream, e);
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				logger.warn("Error closing the input stream", e);
			}
		}

		return null;
	}

	@Override
	public boolean validateReturn(CheckoutReturnType returnType, String version, String stamp, String reference, String payment, String status, String algorithm, String mac) {
		if (returnType == null || mac == null || mac.isEmpty() || stamp == null || stamp.isEmpty()) {
			return false;
		}
		String merchantPass = eventbean.getPrivatePropertyString(LanEventPrivatePropertyKey.CHECKOUT_FI_MERCHANT_PASSWORD);

		boolean ret = false;
		String[] splittedStamp = stamp.split(STAMP_SPLITCHAR);
		if (splittedStamp.length != 2) {
			logbean.sendMessage(MoyaEventType.BANKING_ERROR, permbean.getCurrentUser(), "Unable to split stamp '", stamp, "' with splitchar ", STAMP_SPLITCHAR);
			return false;
		}

		// MD5(turva-avain&VERSION&STAMP&REFERENCE&PAYMENT&STATUS&ALGORITHM)
		String calculatedMac = PasswordFunctions.calculateMd5("&", merchantPass, version, stamp, reference, payment, status, algorithm);
		if (calculatedMac.equals(mac.toUpperCase())) {
			Bill bill = billfacade.find(Integer.parseInt(splittedStamp[0]));
			if (bill != null) {
				switch (returnType) {
				case CANCEL:
					logbean.sendMessage(MoyaEventType.BANKING_ERROR, permbean.getCurrentUser(), "received cancel for stamp ", stamp);
					// Return true when checksum was correct
					ret = true;
					break;
				case DELAYED:
					logbean.sendMessage(MoyaEventType.BANKING_ERROR, permbean.getCurrentUser(), "received delayed for stamp ", stamp);
					// Return true when checksum was correct
					ret = true;
					break;
				case REJECT:
					logbean.sendMessage(MoyaEventType.BANKING_ERROR, permbean.getCurrentUser(), "received reject for stamp ", stamp);
					// Return true when checksum was correct
					ret = true;
					break;
				case RETURN:
					int statusInt = Integer.parseInt(status);
					// Verkkokauppaohjelmisto voi hyväksyä maksun suoritetuksi
					// kun maksun tila on 2,5,6,7,8,9 tai 10.
					switch (statusInt) {
					case 2:
					case 5:
					case 6:
					case 7:
					case 8:
					case 9:
					case 10:
						ret = true;
						if (bill.getAccountEvent() == null
								&& bill.getPaidDate() == null) {
							logger.info("Trying to mark bill {} paid", bill);
							billpbean.markPaid(bill, Calendar.getInstance(), false);
							logbean.sendMessage(MoyaEventType.BANKING_MESSAGE, permbean.getCurrentUser(), "Marking bill paid from checkout. Received bill status ", statusInt, " for bill ", bill, " stamp ", stamp, " payment: ", payment, " reference ", reference);
						} else {
							logbean.sendMessage(MoyaEventType.BANKING_MESSAGE, permbean.getCurrentUser(), "Bill already marked paid: ", bill, " status ", status, " stamp ", stamp, " payment ", payment);
						}
						break;
					default:
						logbean.sendMessage(MoyaEventType.BANKING_MESSAGE, permbean.getCurrentUser(), "Not marking bill paid because of invalid status: Return status ", status, " for bill ", bill, " stamp ", stamp, " payment ", payment);

						break;
					}
					break;
				default:
					logbean.sendMessage(MoyaEventType.BANKING_ERROR, permbean.getCurrentUser(), "Valid mac, but Invalid return type: ", returnType, " for stamp ", stamp, " payment ", payment, " status ", status);
					throw new EJBException("Unknown return type!");
				}
			} else {
				logbean.sendMessage(MoyaEventType.BANKING_ERROR, permbean.getCurrentUser(), "Validated mac, but bill not found for id: ", splittedStamp[0], " stamp ", stamp, " mac: ", mac);
			}
		} else {

			logbean.sendMessage(MoyaEventType.BANKING_ERROR, permbean.getCurrentUser(), "Unable to validate order reference: ", reference, " calculated checksum: ", calculatedMac, " version ", version, " stamp ", stamp, " status ", status, " mac ", mac);

		}

		return ret;
	}

	static class QueryBuilder {
		private final Map<CheckoutQueryParam, String> values = new HashMap<>();;
		private final Date expireDate;
		private final String merchantId;
		private final String merchantPassword;
		private final CheckoutQueryParam[] types;

		QueryBuilder(CheckoutQueryParam[] types, Date expire, String merchantId, String merchantPassword) {
			this.expireDate = expire;
			this.merchantId = merchantId;
			this.merchantPassword = merchantPassword;
			this.types = types;

		}

		public boolean isCredentialsValid() {
			return expireDate != null && new Date().before(expireDate)
					&& getMerchantId() != null && !getMerchantId().isEmpty()
					&& merchantPassword != null && !merchantPassword.isEmpty();

		}

		public void addParam(CheckoutQueryParam key, String value) {
			values.put(key, value);
		}

		public List<NameValuePair> getNameValuePairs() {

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			StringBuilder mdString = new StringBuilder();

			for (CheckoutQueryParam v : types) {
				String value = null;
				if (values.containsKey(v)) {
					value = values.get(v);
				} else {
					value = v.getDefaultValue();
				}
				if (value != null) {
					mdString.append(value);
					nameValuePairs.add(new BasicNameValuePair(v.name(), value));
				}
				mdString.append("+");

			}
			mdString.append(merchantPassword);

			final String calculatedHash = PasswordFunctions.calculateMd5(mdString.toString());

			nameValuePairs.add(new BasicNameValuePair("MAC", calculatedHash));

			return nameValuePairs;
		}

		public String getMerchantId() {
			return merchantId;
		}

	}

}