use of com.salesmanager.core.modules.integration.IntegrationException in project shopizer by shopizer-ecommerce.
the class StorePickupShippingQuote method prePostProcessShippingQuotes.
@Override
public void prePostProcessShippingQuotes(ShippingQuote quote, List<PackageDetails> packages, BigDecimal orderTotal, Delivery delivery, ShippingOrigin origin, MerchantStore store, IntegrationConfiguration globalShippingConfiguration, IntegrationModule currentModule, ShippingConfiguration shippingConfiguration, List<IntegrationModule> allModules, Locale locale) throws IntegrationException {
Validate.notNull(globalShippingConfiguration, "IntegrationConfiguration must not be null for StorePickUp");
try {
if (!globalShippingConfiguration.isActive())
return;
String region = null;
String price = globalShippingConfiguration.getIntegrationKeys().get("price");
if (delivery.getZone() != null) {
region = delivery.getZone().getCode();
} else {
region = delivery.getState();
}
ShippingOption shippingOption = new ShippingOption();
shippingOption.setShippingModuleCode(MODULE_CODE);
shippingOption.setOptionCode(MODULE_CODE);
shippingOption.setOptionId(new StringBuilder().append(MODULE_CODE).append("_").append(region).toString());
shippingOption.setOptionPrice(productPriceUtils.getAmount(price));
shippingOption.setOptionPriceText(productPriceUtils.getStoreFormatedAmountWithCurrency(store, productPriceUtils.getAmount(price)));
List<ShippingOption> options = quote.getShippingOptions();
if (options == null) {
options = new ArrayList<ShippingOption>();
quote.setShippingOptions(options);
}
options.add(shippingOption);
if (quote.getSelectedShippingOption() == null) {
quote.setSelectedShippingOption(shippingOption);
}
} catch (Exception e) {
throw new IntegrationException(e);
}
}
use of com.salesmanager.core.modules.integration.IntegrationException in project shopizer by shopizer-ecommerce.
the class UPSParsedElements method validateModuleConfiguration.
@Override
public void validateModuleConfiguration(IntegrationConfiguration integrationConfiguration, MerchantStore store) throws IntegrationException {
List<String> errorFields = null;
// validate integrationKeys['accessKey']
Map<String, String> keys = integrationConfiguration.getIntegrationKeys();
if (keys == null || StringUtils.isBlank(keys.get("accessKey"))) {
errorFields = new ArrayList<String>();
errorFields.add("accessKey");
}
if (keys == null || StringUtils.isBlank(keys.get("userId"))) {
errorFields = new ArrayList<String>();
errorFields.add("userId");
}
if (keys == null || StringUtils.isBlank(keys.get("password"))) {
errorFields = new ArrayList<String>();
errorFields.add("password");
}
// validate at least one integrationOptions['packages']
Map<String, List<String>> options = integrationConfiguration.getIntegrationOptions();
if (options == null) {
errorFields = new ArrayList<String>();
errorFields.add("packages");
}
List<String> packages = options.get("packages");
if (packages == null || packages.size() == 0) {
if (errorFields == null) {
errorFields = new ArrayList<String>();
}
errorFields.add("packages");
}
if (errorFields != null) {
IntegrationException ex = new IntegrationException(IntegrationException.ERROR_VALIDATION_SAVE);
ex.setErrorFields(errorFields);
throw ex;
}
}
use of com.salesmanager.core.modules.integration.IntegrationException in project shopizer by shopizer-ecommerce.
the class USPSParsedElements method getShippingQuotes.
@Override
public List<ShippingOption> getShippingQuotes(ShippingQuote shippingQuote, List<PackageDetails> packages, BigDecimal orderTotal, Delivery delivery, ShippingOrigin origin, MerchantStore store, IntegrationConfiguration configuration, IntegrationModule module, ShippingConfiguration shippingConfiguration, Locale locale) throws IntegrationException {
if (packages == null) {
return null;
}
if (StringUtils.isBlank(delivery.getPostalCode())) {
return null;
}
// only applies to Canada and US
/* Country country = delivery.getCountry();
if(!country.getIsoCode().equals("US") || !country.getIsoCode().equals("US")){
throw new IntegrationException("USPS Not configured for shipping in country " + country.getIsoCode());
}*/
// supports en and fr
String language = locale.getLanguage();
if (!language.equals(Locale.FRENCH.getLanguage()) && !language.equals(Locale.ENGLISH.getLanguage())) {
language = Locale.ENGLISH.getLanguage();
}
// if store is not CAD /** maintained in the currency **/
/* if (!store.getCurrency().equals(Constants.CURRENCY_CODE_CAD)) {
total = CurrencyUtil.convertToCurrency(total, store.getCurrency(),
Constants.CURRENCY_CODE_CAD);
}*/
Language lang = store.getDefaultLanguage();
HttpGet httpget = null;
Reader xmlreader = null;
String pack = configuration.getIntegrationOptions().get("packages").get(0);
try {
Map<String, Country> countries = countryService.getCountriesMap(lang);
Country destination = countries.get(delivery.getCountry().getIsoCode());
Map<String, String> keys = configuration.getIntegrationKeys();
if (keys == null || StringUtils.isBlank(keys.get("account"))) {
// TODO can we return null
return null;
}
String host = null;
String protocol = null;
String port = null;
String url = null;
// against which environment are we using the service
String env = configuration.getEnvironment();
// must be US
if (!store.getCountry().getIsoCode().equals("US")) {
throw new IntegrationException("Can't use the service for store country code ");
}
Map<String, ModuleConfig> moduleConfigsMap = module.getModuleConfigs();
for (String key : moduleConfigsMap.keySet()) {
ModuleConfig moduleConfig = moduleConfigsMap.get(key);
if (moduleConfig.getEnv().equals(env)) {
host = moduleConfig.getHost();
protocol = moduleConfig.getScheme();
port = moduleConfig.getPort();
url = moduleConfig.getUri();
}
}
StringBuilder xmlheader = new StringBuilder();
if (store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
xmlheader.append("<RateV3Request USERID=\"").append(keys.get("account")).append("\">");
} else {
xmlheader.append("<IntlRateRequest USERID=\"").append(keys.get("account")).append("\">");
}
StringBuilder xmldatabuffer = new StringBuilder();
double totalW = 0;
double totalH = 0;
double totalL = 0;
double totalG = 0;
double totalP = 0;
for (PackageDetails detail : packages) {
// need size in inch
double w = DataUtils.getMeasure(detail.getShippingWidth(), store, MeasureUnit.IN.name());
double h = DataUtils.getMeasure(detail.getShippingHeight(), store, MeasureUnit.IN.name());
double l = DataUtils.getMeasure(detail.getShippingLength(), store, MeasureUnit.IN.name());
totalW = totalW + w;
totalH = totalH + h;
totalL = totalL + l;
// Girth = Length + (Width x 2) + (Height x 2)
double girth = l + (w * 2) + (h * 2);
totalG = totalG + girth;
// need weight in pounds
double p = DataUtils.getWeight(detail.getShippingWeight(), store, MeasureUnit.LB.name());
totalP = totalP + p;
}
/* BigDecimal convertedOrderTotal = CurrencyUtil.convertToCurrency(
orderTotal, store.getCurrency(),
Constants.CURRENCY_CODE_USD);*/
// calculate total shipping volume
// ship date is 3 days from here
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, 3);
Date newDate = c.getTime();
SimpleDateFormat format = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT);
String shipDate = format.format(newDate);
int i = 1;
// need pounds and ounces
int pounds = (int) totalP;
String ouncesString = String.valueOf(totalP - pounds);
int ouncesIndex = ouncesString.indexOf(".");
String ounces = "00";
if (ouncesIndex > -1) {
ounces = ouncesString.substring(ouncesIndex + 1);
}
String size = "REGULAR";
if (totalL + totalG <= 64) {
size = "REGULAR";
} else if (totalL + totalG <= 108) {
size = "LARGE";
} else {
size = "OVERSIZE";
}
/**
* Domestic <Package ID="1ST"> <Service>ALL</Service>
* <ZipOrigination>90210</ZipOrigination>
* <ZipDestination>96698</ZipDestination> <Pounds>8</Pounds>
* <Ounces>32</Ounces> <Container/> <Size>REGULAR</Size>
* <Machinable>true</Machinable> </Package>
*
* //MAXWEIGHT=70 lbs
*
* //domestic container default=VARIABLE whiteSpace=collapse
* enumeration=VARIABLE enumeration=FLAT RATE BOX enumeration=FLAT
* RATE ENVELOPE enumeration=LG FLAT RATE BOX
* enumeration=RECTANGULAR enumeration=NONRECTANGULAR
*
* //INTL enumeration=Package enumeration=Postcards or aerogrammes
* enumeration=Matter for the blind enumeration=Envelope
*
* Size May be left blank in situations that do not Size. Defined as
* follows: REGULAR: package plus girth is 84 inches or less; LARGE:
* package length plus girth measure more than 84 inches not more
* than 108 inches; OVERSIZE: package length plus girth is more than
* 108 but not 130 inches. For example: <Size>REGULAR</Size>
*
* International <Package ID="1ST"> <Machinable>true</Machinable>
* <MailType>Envelope</MailType> <Country>Canada</Country>
* <Length>0</Length> <Width>0</Width> <Height>0</Height>
* <ValueOfContents>250</ValueOfContents> </Package>
*
* <Package ID="2ND"> <Pounds>4</Pounds> <Ounces>3</Ounces>
* <MailType>Package</MailType> <GXG> <Length>46</Length>
* <Width>14</Width> <Height>15</Height> <POBoxFlag>N</POBoxFlag>
* <GiftFlag>N</GiftFlag> </GXG>
* <ValueOfContents>250</ValueOfContents> <Country>Japan</Country>
* </Package>
*/
xmldatabuffer.append("<Package ID=\"").append(i).append("\">");
if (store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
xmldatabuffer.append("<Service>");
xmldatabuffer.append("ALL");
xmldatabuffer.append("</Service>");
xmldatabuffer.append("<ZipOrigination>");
xmldatabuffer.append(DataUtils.trimPostalCode(store.getStorepostalcode()));
xmldatabuffer.append("</ZipOrigination>");
xmldatabuffer.append("<ZipDestination>");
xmldatabuffer.append(DataUtils.trimPostalCode(delivery.getPostalCode()));
xmldatabuffer.append("</ZipDestination>");
xmldatabuffer.append("<Pounds>");
xmldatabuffer.append(pounds);
xmldatabuffer.append("</Pounds>");
xmldatabuffer.append("<Ounces>");
xmldatabuffer.append(ounces);
xmldatabuffer.append("</Ounces>");
xmldatabuffer.append("<Container>");
xmldatabuffer.append(pack);
xmldatabuffer.append("</Container>");
xmldatabuffer.append("<Size>");
xmldatabuffer.append(size);
xmldatabuffer.append("</Size>");
// TODO must be changed if not machinable
xmldatabuffer.append("<Machinable>true</Machinable>");
xmldatabuffer.append("<ShipDate>");
xmldatabuffer.append(shipDate);
xmldatabuffer.append("</ShipDate>");
} else {
// if international
xmldatabuffer.append("<Pounds>");
xmldatabuffer.append(pounds);
xmldatabuffer.append("</Pounds>");
xmldatabuffer.append("<Ounces>");
xmldatabuffer.append(ounces);
xmldatabuffer.append("</Ounces>");
xmldatabuffer.append("<MailType>");
xmldatabuffer.append(pack);
xmldatabuffer.append("</MailType>");
xmldatabuffer.append("<ValueOfContents>");
xmldatabuffer.append(productPriceUtils.getAdminFormatedAmount(store, orderTotal));
xmldatabuffer.append("</ValueOfContents>");
xmldatabuffer.append("<Country>");
xmldatabuffer.append(destination.getName());
xmldatabuffer.append("</Country>");
}
// if international & CXG
/*
* xmldatabuffer.append("<CXG>"); xmldatabuffer.append("<Length>");
* xmldatabuffer.append(""); xmldatabuffer.append("</Length>");
* xmldatabuffer.append("<Width>"); xmldatabuffer.append("");
* xmldatabuffer.append("</Width>");
* xmldatabuffer.append("<Height>"); xmldatabuffer.append("");
* xmldatabuffer.append("</Height>");
* xmldatabuffer.append("<POBoxFlag>"); xmldatabuffer.append("");
* xmldatabuffer.append("</POBoxFlag>");
* xmldatabuffer.append("<GiftFlag>"); xmldatabuffer.append("");
* xmldatabuffer.append("</GiftFlag>");
* xmldatabuffer.append("</CXG>");
*/
/*
* xmldatabuffer.append("<Width>"); xmldatabuffer.append(totalW);
* xmldatabuffer.append("</Width>");
* xmldatabuffer.append("<Length>"); xmldatabuffer.append(totalL);
* xmldatabuffer.append("</Length>");
* xmldatabuffer.append("<Height>"); xmldatabuffer.append(totalH);
* xmldatabuffer.append("</Height>");
* xmldatabuffer.append("<Girth>"); xmldatabuffer.append(totalG);
* xmldatabuffer.append("</Girth>");
*/
xmldatabuffer.append("</Package>");
String xmlfooter = "</RateV3Request>";
if (!store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
xmlfooter = "</IntlRateRequest>";
}
StringBuilder xmlbuffer = new StringBuilder().append(xmlheader.toString()).append(xmldatabuffer.toString()).append(xmlfooter);
LOGGER.debug("USPS QUOTE REQUEST " + xmlbuffer.toString());
// HttpClient client = new HttpClient();
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
@SuppressWarnings("deprecation") String encoded = java.net.URLEncoder.encode(xmlbuffer.toString());
String completeUri = url + "?API=RateV3&XML=" + encoded;
if (!store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
completeUri = url + "?API=IntlRate&XML=" + encoded;
}
// ?API=RateV3
httpget = new HttpGet(protocol + "://" + host + ":" + port + completeUri);
// RequestEntity entity = new
// StringRequestEntity(xmlbuffer.toString(),"text/plain","UTF-8");
// httpget.setRequestEntity(entity);
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
LOGGER.error("Communication Error with ups quote " + status);
throw new ClientProtocolException("UPS quote communication error " + status);
}
};
String data = httpclient.execute(httpget, responseHandler);
/* int result = client.executeMethod(httpget);
if (result != 200) {
LOGGER.error("Communication Error with usps quote " + result + " "
+ protocol + "://" + host + ":" + port + url);
throw new Exception("USPS quote communication error " + result);
}*/
// data = httpget.getResponseBodyAsString();
LOGGER.debug("usps quote response " + data);
USPSParsedElements parsed = new USPSParsedElements();
/**
* <RateV3Response> <Package ID="1ST">
* <ZipOrigination>44106</ZipOrigination>
* <ZipDestination>20770</ZipDestination>
*/
Digester digester = new Digester();
digester.push(parsed);
if (store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
digester.addCallMethod("Error/Description", "setError", 0);
digester.addCallMethod("RateV3Response/Package/Error/Description", "setError", 0);
digester.addObjectCreate("RateV3Response/Package/Postage", ShippingOption.class);
digester.addSetProperties("RateV3Response/Package/Postage", "CLASSID", "optionId");
digester.addCallMethod("RateV3Response/Package/Postage/MailService", "setOptionName", 0);
digester.addCallMethod("RateV3Response/Package/Postage/MailService", "setOptionCode", 0);
digester.addCallMethod("RateV3Response/Package/Postage/Rate", "setOptionPriceText", 0);
// digester
// .addCallMethod(
// "RateV3Response/Package/Postage/Commitment/CommitmentDate",
// "estimatedNumberOfDays", 0);
digester.addSetNext("RateV3Response/Package/Postage", "addOption");
} else {
digester.addCallMethod("Error/Description", "setError", 0);
digester.addCallMethod("IntlRateResponse/Package/Error/Description", "setError", 0);
digester.addObjectCreate("IntlRateResponse/Package/Service", ShippingOption.class);
digester.addSetProperties("IntlRateResponse/Package/Service", "ID", "optionId");
digester.addCallMethod("IntlRateResponse/Package/Service/SvcDescription", "setOptionName", 0);
digester.addCallMethod("IntlRateResponse/Package/Service/SvcDescription", "setOptionCode", 0);
digester.addCallMethod("IntlRateResponse/Package/Service/Postage", "setOptionPriceText", 0);
// digester.addCallMethod(
// "IntlRateResponse/Package/Service/SvcCommitments",
// "setEstimatedNumberOfDays", 0);
digester.addSetNext("IntlRateResponse/Package/Service", "addOption");
}
// <?xml
// version="1.0"?><AddressValidationResponse><Response><TransactionReference><CustomerContext>SalesManager
// Data</CustomerContext><XpciVersion>1.0</XpciVersion></TransactionReference><ResponseStatusCode>0</ResponseStatusCode><ResponseStatusDescription>Failure</ResponseStatusDescription><Error><ErrorSeverity>Hard</ErrorSeverity><ErrorCode>10002</ErrorCode><ErrorDescription>The
// XML document is well formed but the document is not
// valid</ErrorDescription><ErrorLocation><ErrorLocationElementName>AddressValidationRequest</ErrorLocationElementName></ErrorLocation></Error></Response></AddressValidationResponse>
// <?xml version="1.0"?>
// <IntlRateResponse><Package ID="1"><Error><Number>-2147218046</Number>
// <Source>IntlPostage;clsIntlPostage.GetCountryAndRestirctedServiceId;clsIntlPostage.CalcAllPostageDimensionsXML;IntlRate.ProcessRequest</Source>
// <Description>Invalid Country Name</Description><HelpFile></HelpFile><HelpContext>1000440</HelpContext></Error></Package></IntlRateResponse>
xmlreader = new StringReader(data);
digester.parse(xmlreader);
if (!StringUtils.isBlank(parsed.getError())) {
LOGGER.error("Can't process USPS message= " + parsed.getError());
throw new IntegrationException(parsed.getError());
}
if (!StringUtils.isBlank(parsed.getStatusCode()) && !parsed.getStatusCode().equals("1")) {
LOGGER.error("Can't process USPS statusCode=" + parsed.getStatusCode() + " message= " + parsed.getError());
throw new IntegrationException(parsed.getError());
}
if (parsed.getOptions() == null || parsed.getOptions().size() == 0) {
LOGGER.warn("No options returned from USPS");
throw new IntegrationException(parsed.getError());
}
/* String carrier = getShippingMethodDescription(locale);
// cost is in USD, need to do conversion
MerchantConfiguration rtdetails = config
.getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_DISPLAY_REALTIME_QUOTES);
int displayQuoteDeliveryTime = ShippingConstants.NO_DISPLAY_RT_QUOTE_TIME;
if (rtdetails != null) {
if (!StringUtils.isBlank(rtdetails.getConfigurationValue1())) {// display
// or
// not
// quotes
try {
displayQuoteDeliveryTime = Integer.parseInt(rtdetails
.getConfigurationValue1());
} catch (Exception e) {
log.error("Display quote is not an integer value ["
+ rtdetails.getConfigurationValue1() + "]");
}
}
}
LabelUtil labelUtil = LabelUtil.getInstance();*/
// Map serviceMap =
// com.salesmanager.core.util.ShippingUtil.buildServiceMap("usps",locale);
@SuppressWarnings("unchecked") List<ShippingOption> shippingOptions = parsed.getOptions();
return shippingOptions;
}
} catch (Exception e1) {
LOGGER.error("Error in USPS shipping quote ", e1);
throw new IntegrationException(e1);
} finally {
if (xmlreader != null) {
try {
xmlreader.close();
} catch (Exception ignore) {
}
}
if (httpget != null) {
httpget.releaseConnection();
}
}
}
use of com.salesmanager.core.modules.integration.IntegrationException in project shopizer by shopizer-ecommerce.
the class BeanStreamPayment method sendTransaction.
private Transaction sendTransaction(String orderNumber, MerchantStore store, String transaction, String beanstreamType, TransactionType transactionType, PaymentType paymentType, BigDecimal amount, IntegrationConfiguration configuration, IntegrationModule module) throws IntegrationException {
String agent = "Mozilla/4.0";
String respText = "";
Map<String, String> nvp = null;
DataOutputStream output = null;
DataInputStream in = null;
BufferedReader is = null;
HttpURLConnection conn = null;
try {
// transaction = "requestType=BACKEND&merchant_id=300200260&trnType=P&username=carlito&password=shopizer001&orderNumber=caa71106-7e3f-4975-a657-a35904dc32a0&trnCardOwner=Carl Samson&trnCardNumber=5100000020002000&trnExpMonth=10&trnExpYear=14&trnCardCvd=123&trnAmount=77.01&ordName=Carl S&ordAddress1=358 Du Languedoc&ordCity=Victoria&ordProvince=BC&ordPostalCode=V8T2E7&ordCountry=CA&ordPhoneNumber=(444) 555-6666&ordEmailAddress=csamson777@yahoo.com";
/**
* requestType=BACKEND&merchant_id=300200260
* &trnType=P
* &username=carlito&password=shopizer001
* &orderNumber=caa71106-7e3f-4975-a657-a35904dc32a0
* &trnCardOwner=Carl Samson
* &trnCardNumber=5100000020002000
* &trnExpMonth=10
* &trnExpYear=14
* &trnCardCvd=123
* &trnAmount=77.01
* &ordName=Carl S
* &ordAddress1=378 Du Languedoc
* &ordCity=Boucherville
* &ordProvince=QC
* &ordPostalCode=J3B8J1
* &ordCountry=CA
* &ordPhoneNumber=(444) 555-6666
* &ordEmailAddress=test@yahoo.com
*/
/**
* merchant_id=123456789&requestType=BACKEND
* &trnType=P&trnOrderNumber=1234TEST&trnAmount=5.00&trnCardOwner=Joe+Test
* &trnCardNumber=4030000010001234
* &trnExpMonth=10
* &trnExpYear=16
* &ordName=Joe+Test
* &ordAddress1=123+Test+Street
* &ordCity=Victoria
* &ordProvince=BC
* &ordCountry=CA
* &ordPostalCode=V8T2E7
* &ordPhoneNumber=5555555555
* &ordEmailAddress=joe%40testemail.com
*/
boolean bSandbox = false;
if (configuration.getEnvironment().equals("TEST")) {
// sandbox
bSandbox = true;
}
String server = "";
ModuleConfig configs = module.getModuleConfigs().get("PROD");
if (bSandbox) {
configs = module.getModuleConfigs().get("TEST");
}
if (configs == null) {
throw new IntegrationException("Module not configured for TEST or PROD");
}
server = new StringBuffer().append(configs.getScheme()).append("://").append(configs.getHost()).append(":").append(configs.getPort()).append(configs.getUri()).toString();
URL postURL = new URL(server);
conn = (HttpURLConnection) postURL.openConnection();
// Set connection parameters. We need to perform input and output,
// so set both as true.
conn.setDoInput(true);
conn.setDoOutput(true);
// Set the content type we are POSTing. We impersonate it as
// encoded form data
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", agent);
conn.setRequestProperty("Content-Length", String.valueOf(transaction.length()));
conn.setRequestMethod("POST");
// get the output stream to POST to.
output = new DataOutputStream(conn.getOutputStream());
output.writeBytes(transaction);
output.flush();
// Read input from the input stream.
in = new DataInputStream(conn.getInputStream());
int rc = conn.getResponseCode();
if (rc != -1) {
is = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String _line = null;
while (((_line = is.readLine()) != null)) {
respText = respText + _line;
}
LOGGER.debug("BeanStream response -> " + respText.trim());
nvp = formatUrlResponse(respText.trim());
} else {
throw new IntegrationException("Invalid response from BeanStream, return code is " + rc);
}
// check
// trnApproved=1&trnId=10003067&messageId=1&messageText=Approved&trnOrderNumber=E40089&authCode=TEST&errorType=N&errorFields=
String transactionApproved = nvp.get("TRNAPPROVED");
String transactionId = nvp.get("TRNID");
String messageId = nvp.get("MESSAGEID");
String messageText = (String) nvp.get("MESSAGETEXT");
String orderId = (String) nvp.get("TRNORDERNUMBER");
String authCode = (String) nvp.get("AUTHCODE");
String errorType = (String) nvp.get("ERRORTYPE");
String errorFields = (String) nvp.get("ERRORFIELDS");
if (!StringUtils.isBlank(orderNumber)) {
nvp.put("INTERNALORDERID", orderNumber);
}
if (StringUtils.isBlank(transactionApproved)) {
throw new IntegrationException("Required field transactionApproved missing from BeanStream response");
}
// errors
if (transactionApproved.equals("0")) {
merchantLogService.save(new MerchantLog(store, "Can't process BeanStream message " + messageText + " return code id " + messageId));
IntegrationException te = new IntegrationException("Can't process BeanStream message " + messageText);
te.setExceptionType(IntegrationException.EXCEPTION_PAYMENT_DECLINED);
te.setMessageCode("message.payment.beanstream." + messageId);
te.setErrorCode(IntegrationException.TRANSACTION_EXCEPTION);
throw te;
}
// return parseResponse(type,transaction,respText,nvp,order);
return this.parseResponse(transactionType, paymentType, nvp, amount);
} catch (Exception e) {
if (e instanceof IntegrationException) {
throw (IntegrationException) e;
}
throw new IntegrationException("Error while processing BeanStream transaction", e);
} finally {
if (is != null) {
try {
is.close();
} catch (Exception ignore) {
// TODO: handle exception
}
}
if (in != null) {
try {
in.close();
} catch (Exception ignore) {
// TODO: handle exception
}
}
if (output != null) {
try {
output.close();
} catch (Exception ignore) {
// TODO: handle exception
}
}
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ignore) {
// TODO: handle exception
}
}
}
}
use of com.salesmanager.core.modules.integration.IntegrationException in project shopizer by shopizer-ecommerce.
the class BeanStreamPayment method processTransaction.
private Transaction processTransaction(MerchantStore store, Customer customer, TransactionType type, BigDecimal amount, Payment payment, IntegrationConfiguration configuration, IntegrationModule module) throws IntegrationException {
boolean bSandbox = false;
if (configuration.getEnvironment().equals("TEST")) {
// sandbox
bSandbox = true;
}
ModuleConfig configs = module.getModuleConfigs().get("PROD");
if (bSandbox) {
configs = module.getModuleConfigs().get("TEST");
}
if (configs == null) {
throw new IntegrationException("Module not configured for TEST or PROD");
}
String server = new StringBuffer().append(configs.getScheme()).append("://").append(configs.getHost()).append(":").append(configs.getPort()).append(configs.getUri()).toString();
HttpURLConnection conn = null;
try {
// TODO
String uniqueId = UUID.randomUUID().toString();
String orderNumber = uniqueId;
String amnt = productPriceUtils.getAdminFormatedAmount(store, amount);
StringBuilder messageString = new StringBuilder();
String transactionType = "P";
if (type == TransactionType.AUTHORIZE) {
transactionType = "PA";
} else if (type == TransactionType.AUTHORIZECAPTURE) {
transactionType = "P";
}
CreditCardPayment creditCardPayment = (CreditCardPayment) payment;
messageString.append("requestType=BACKEND&");
messageString.append("merchant_id=").append(configuration.getIntegrationKeys().get("merchantid")).append("&");
messageString.append("trnType=").append(transactionType).append("&");
messageString.append("username=").append(configuration.getIntegrationKeys().get("username")).append("&");
messageString.append("password=").append(configuration.getIntegrationKeys().get("password")).append("&");
messageString.append("orderNumber=").append(orderNumber).append("&");
messageString.append("trnCardOwner=").append(creditCardPayment.getCardOwner()).append("&");
messageString.append("trnCardNumber=").append(creditCardPayment.getCreditCardNumber()).append("&");
messageString.append("trnExpMonth=").append(creditCardPayment.getExpirationMonth()).append("&");
messageString.append("trnExpYear=").append(creditCardPayment.getExpirationYear().substring(2)).append("&");
messageString.append("trnCardCvd=").append(creditCardPayment.getCredidCardValidationNumber()).append("&");
messageString.append("trnAmount=").append(amnt).append("&");
StringBuilder nm = new StringBuilder();
nm.append(customer.getBilling().getFirstName()).append(" ").append(customer.getBilling().getLastName());
messageString.append("ordName=").append(nm.toString()).append("&");
messageString.append("ordAddress1=").append(customer.getBilling().getAddress()).append("&");
messageString.append("ordCity=").append(customer.getBilling().getCity()).append("&");
String stateProvince = customer.getBilling().getState();
if (customer.getBilling().getZone() != null) {
stateProvince = customer.getBilling().getZone().getCode();
}
String countryName = customer.getBilling().getCountry().getIsoCode();
messageString.append("ordProvince=").append(stateProvince).append("&");
messageString.append("ordPostalCode=").append(customer.getBilling().getPostalCode().replaceAll("\\s", "")).append("&");
messageString.append("ordCountry=").append(countryName).append("&");
messageString.append("ordPhoneNumber=").append(customer.getBilling().getTelephone()).append("&");
messageString.append("ordEmailAddress=").append(customer.getEmailAddress());
/**
* purchase (P)
* -----------
* REQUEST -> merchant_id=123456789&requestType=BACKEND&trnType=P&trnOrderNumber=1234TEST&trnAmount=5.00&trnCardOwner=Joe+Test&trnCardNumber=4030000010001234&trnExpMonth=10&trnExpYear=10&ordName=Joe+Test&ordAddress1=123+Test+Street&ordCity=Victoria&ordProvince=BC&ordCountry=CA&ordPostalCode=V8T2E7&ordPhoneNumber=5555555555&ordEmailAddress=joe%40testemail.com
* RESPONSE-> trnApproved=1&trnId=10003067&messageId=1&messageText=Approved&trnOrderNumber=E40089&authCode=TEST&errorType=N&errorFields=&responseType=T&trnAmount=10%2E00&trnDate=1%2F17%2F2008+11%3A36%3A34+AM&avsProcessed=0&avsId=0&avsResult=0&avsAddrMatch=0&avsPostalMatch=0&avsMessage=Address+Verification+not+performed+for+this+transaction%2E&rspCodeCav=0&rspCavResult=0&rspCodeCredit1=0&rspCodeCredit2=0&rspCodeCredit3=0&rspCodeCredit4=0&rspCodeAddr1=0&rspCodeAddr2=0&rspCodeAddr3=0&rspCodeAddr4=0&rspCodeDob=0&rspCustomerDec=&trnType=P&paymentMethod=CC&ref1=&ref2=&ref3=&ref4=&ref5=
*
* pre authorization (PA)
* ----------------------
*
* Prior to processing a pre-authorization through the API, you must modify the transaction settings in your Beanstream merchant member area to allow for this transaction type.
* - Log in to the Beanstream online member area at www.beanstream.com/admin/sDefault.asp.
* - Navigate to administration - account admin - order settings in the left menu.
* Under the heading �Restrict Internet Transaction Processing Types,� select either of the last two options. The �Purchases or Pre-Authorization Only� option will allow you to process both types of transaction through your web interface. De-selecting the �Restrict Internet Transaction Processing Types� checkbox will allow you to process all types of transactions including returns, voids and pre-auth completions.
*
* capture (PAC) -> requires trnId
* -------------
*
* refund (R)
* -------------
* REQUEST -> merchant_id=123456789&requestType=BACKEND&trnType=R&username=user1234&password=pass1234&trnOrderNumber=1234&trnAmount=1.00&adjId=10002115
* RESPONSE-> trnApproved=1&trnId=10002118&messageId=1&messageText=Approved&trnOrderNumber=1234R&authCode=TEST&errorType=N&errorFields=&responseType=T&trnAmount=1%2E00&trnDate=8%2F17%2F2009+1%3A44%3A56+PM&avsProcessed=0&avsId=0&avsResult=0&avsAddrMatch=0&avsPostalMatch=0&avsMessage=Address+Verification+not+performed+for+this+transaction%2E&cardType=VI&trnType=R&paymentMethod=CC&ref1=&ref2=&ref3=&ref4=&ref5=
*
* //notes
* //On receipt of the transaction response, the merchant must display order amount, transaction ID number, bank authorization code (authCode), currency, date and �messageText� to the customer on a confirmation page.
*/
// String agent = "Mozilla/4.0";
// String respText = "";
// Map nvp = null;
/**
* debug *
*/
StringBuilder messageLogString = new StringBuilder();
messageLogString.append("requestType=BACKEND&");
messageLogString.append("merchant_id=").append(configuration.getIntegrationKeys().get("merchantid")).append("&");
messageLogString.append("trnType=").append(type).append("&");
messageLogString.append("orderNumber=").append(orderNumber).append("&");
messageLogString.append("trnCardOwner=").append(creditCardPayment.getCardOwner()).append("&");
messageLogString.append("trnCardNumber=").append(CreditCardUtils.maskCardNumber(creditCardPayment.getCreditCardNumber())).append("&");
messageLogString.append("trnExpMonth=").append(creditCardPayment.getExpirationMonth()).append("&");
messageLogString.append("trnExpYear=").append(creditCardPayment.getExpirationYear()).append("&");
messageLogString.append("trnCardCvd=").append(creditCardPayment.getCredidCardValidationNumber()).append("&");
messageLogString.append("trnAmount=").append(amnt).append("&");
messageLogString.append("ordName=").append(nm.toString()).append("&");
messageLogString.append("ordAddress1=").append(customer.getBilling().getAddress()).append("&");
messageLogString.append("ordCity=").append(customer.getBilling().getCity()).append("&");
messageLogString.append("ordProvince=").append(stateProvince).append("&");
messageLogString.append("ordPostalCode=").append(customer.getBilling().getPostalCode()).append("&");
messageLogString.append("ordCountry=").append(customer.getBilling().getCountry().getName()).append("&");
messageLogString.append("ordPhoneNumber=").append(customer.getBilling().getTelephone()).append("&");
messageLogString.append("ordEmailAddress=").append(customer.getEmailAddress());
/**
* debug *
*/
LOGGER.debug("REQUEST SENT TO BEANSTREAM -> " + messageLogString.toString());
URL postURL = new URL(server);
conn = (HttpURLConnection) postURL.openConnection();
return sendTransaction(orderNumber, store, messageString.toString(), transactionType, type, payment.getPaymentType(), amount, configuration, module);
} catch (Exception e) {
if (e instanceof IntegrationException)
throw (IntegrationException) e;
throw new IntegrationException("Error while processing BeanStream transaction", e);
} finally {
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ignore) {
}
}
}
}
Aggregations