diff --git a/.classpath b/.classpath
index a577c9c460..09ad32b460 100644
--- a/.classpath
+++ b/.classpath
@@ -141,6 +141,9 @@
+
+
+
diff --git a/applications/accounting/config/AccountingUiLabels.xml b/applications/accounting/config/AccountingUiLabels.xml
index 22a31d5180..69bef900d1 100644
--- a/applications/accounting/config/AccountingUiLabels.xml
+++ b/applications/accounting/config/AccountingUiLabels.xml
@@ -13686,4 +13686,52 @@
Batch Payments
भुगतान का बैच
-
+
+ Update Payment Gateway Config SagePay
+
+
+ Vendor Name
+
+
+ Production Host
+
+
+ Testing Host
+
+
+ Mode
+
+
+ Protocol Version
+
+
+ Authentication Type
+
+
+ Authentication Url
+
+
+ Authorisation Type
+
+
+ Authorisation Url
+
+
+ Release Type
+
+
+ Release Url
+
+
+ Void Url
+
+
+ Refund Url
+
+
+ Production
+
+
+ Test
+
+
\ No newline at end of file
diff --git a/applications/accounting/data/AccountingTypeData.xml b/applications/accounting/data/AccountingTypeData.xml
index 9101ddac01..a674fb8533 100644
--- a/applications/accounting/data/AccountingTypeData.xml
+++ b/applications/accounting/data/AccountingTypeData.xml
@@ -694,6 +694,10 @@ under the License.
+
+
+
+
diff --git a/applications/accounting/entitydef/entitymodel.xml b/applications/accounting/entitydef/entitymodel.xml
index 32f78f77b9..54e9444c9a 100644
--- a/applications/accounting/entitydef/entitymodel.xml
+++ b/applications/accounting/entitydef/entitymodel.xml
@@ -3146,6 +3146,28 @@ under the License.
+
+
+ Vendor name
+ Production Host
+ Testing Host
+ Mode (PRODUCTION/TEST)
+ Protocol Version
+ Authentication type (PAYMENT/AUTHENTICATE/DEFERRED)
+ Authentication Url
+ Authorise type (AUTHORISE/RELEASE)
+ Authorise url
+ Release type (CANCEL/ABORT)
+ Release Url
+ Void Url
+ Refund Url
+
+
+
+
+
diff --git a/applications/accounting/ofbiz-component.xml b/applications/accounting/ofbiz-component.xml
index 064295ee96..f943008162 100644
--- a/applications/accounting/ofbiz-component.xml
+++ b/applications/accounting/ofbiz-component.xml
@@ -68,6 +68,7 @@ under the License.
+
diff --git a/applications/accounting/script/org/ofbiz/accounting/payment/PaymentGatewayConfigServices.xml b/applications/accounting/script/org/ofbiz/accounting/payment/PaymentGatewayConfigServices.xml
index 0936b4c0b5..81f4671eb8 100644
--- a/applications/accounting/script/org/ofbiz/accounting/payment/PaymentGatewayConfigServices.xml
+++ b/applications/accounting/script/org/ofbiz/accounting/payment/PaymentGatewayConfigServices.xml
@@ -25,7 +25,13 @@ under the License.
-
+
+
+
+
+
+
+
diff --git a/applications/accounting/servicedef/services_paymentgateway.xml b/applications/accounting/servicedef/services_paymentgateway.xml
index 030f4a6ef7..21dfdcd46c 100644
--- a/applications/accounting/servicedef/services_paymentgateway.xml
+++ b/applications/accounting/servicedef/services_paymentgateway.xml
@@ -30,7 +30,13 @@ under the License.
-
+
+
+ Update Payment Gateway Config SagePay
+
+
+
+
Update Payment Gateway Config Authorize Dot Net
diff --git a/applications/accounting/servicedef/services_sagepay.xml b/applications/accounting/servicedef/services_sagepay.xml
new file mode 100644
index 0000000000..9f6970295a
--- /dev/null
+++ b/applications/accounting/servicedef/services_sagepay.xml
@@ -0,0 +1,171 @@
+
+
+
+
+ Accounting Services
+ OFBiz
+ 1.0
+
+
+ SagePay Payment Authorization Service
+
+
+
+
+ SagePay Payment Capture Service
+
+
+
+
+ SagePay Payment Release
+
+
+
+
+ SagePay Payment Refund Service
+
+
+
+
+ For payment authentication
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ For capturing the payment
+
+
+
+
+
+
+
+
+
+
+
+ For releasing (cancel) the payment
+
+
+
+
+
+
+
+
+
+
+
+ For voiding the payment
+
+
+
+
+
+
+
+
+
+
+ For refunding the payment
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayPaymentServices.java b/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayPaymentServices.java
new file mode 100644
index 0000000000..dfcb9cfb76
--- /dev/null
+++ b/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayPaymentServices.java
@@ -0,0 +1,521 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+
+package org.ofbiz.accounting.thirdparty.sagepay;
+
+import java.math.BigDecimal;
+import java.sql.Timestamp;
+import java.util.Calendar;
+import java.util.List;
+import java.util.Map;
+
+import javolution.util.FastMap;
+
+import org.ofbiz.accounting.payment.PaymentGatewayServices;
+import org.ofbiz.base.util.Debug;
+import org.ofbiz.base.util.UtilDateTime;
+import org.ofbiz.base.util.UtilFormatOut;
+import org.ofbiz.base.util.UtilMisc;
+import org.ofbiz.entity.Delegator;
+import org.ofbiz.entity.GenericEntityException;
+import org.ofbiz.entity.GenericValue;
+import org.ofbiz.entity.condition.EntityCondition;
+import org.ofbiz.entity.util.EntityUtil;
+import org.ofbiz.service.DispatchContext;
+import org.ofbiz.service.GenericServiceException;
+import org.ofbiz.service.LocalDispatcher;
+import org.ofbiz.service.ServiceUtil;
+
+public class SagePayPaymentServices {
+
+ public static final String module = SagePayPaymentServices.class.getName();
+
+ private static Map buildCustomerBillingInfo(Map context) {
+
+ Debug.logInfo("SagePay - Entered buildCustomerBillingInfo", module);
+ Debug.logInfo("SagePay buildCustomerBillingInfo context : " + context, module);
+
+ Map billingInfo = FastMap.newInstance();
+
+ String orderId = null;
+ BigDecimal processAmount = null;
+ String currency = null;
+ String cardNumber = null;
+ String cardType = null;
+ String nameOnCard = null;
+ String expireDate = null;
+ String securityCode = null;
+ String postalCode = null;
+ String address = null;
+
+ try {
+
+ GenericValue opp = (GenericValue) context.get("orderPaymentPreference");
+ if (opp != null) {
+ if ("CREDIT_CARD".equals(opp.getString("paymentMethodTypeId"))) {
+
+ GenericValue creditCard = (GenericValue) context.get("creditCard");
+ if (creditCard == null || !(opp.get("paymentMethodId").equals(creditCard.get("paymentMethodId")))) {
+ creditCard = opp.getRelatedOne("CreditCard");
+ }
+
+ securityCode = opp.getString("securityCode");
+
+ //getting billing address
+ GenericValue billingAddress = (GenericValue) context.get("billingAddress");
+ postalCode = billingAddress.getString("postalCode");
+ String address2 = billingAddress.getString("address2");
+ if (address2 == null){
+ address2 = "";
+ }
+ address = billingAddress.getString("address1") + " " + address2;
+
+ //getting card details
+ cardNumber = creditCard.getString("cardNumber");
+ String firstName = creditCard.getString("firstNameOnCard");
+ String middleName = creditCard.getString("middleNameOnCard");
+ String lastName = creditCard.getString("lastNameOnCard");
+ if (middleName == null){
+ middleName = "";
+ }
+ nameOnCard = firstName + " " + middleName + " " + lastName;
+ cardType = creditCard.getString("cardType");
+ if (cardType != null) {
+ if (cardType.equals("MasterCard")) {
+ cardType = "MC";
+ }
+ if (cardType.equals("VisaElectron")) {
+ cardType = "UKE";
+ }
+ if (cardType.equals("DinersClub")) {
+ cardType = "DC";
+ }
+ if (cardType.equals("Switch")) {
+ cardType = "MAESTRO";
+ }
+ }
+ expireDate = creditCard.getString("expireDate");
+ String month = expireDate.substring(0,2);
+ String year = expireDate.substring(5);
+ expireDate = month + year;
+
+ //getting order details
+ orderId = UtilFormatOut.checkNull((String) context.get("orderId"));
+ processAmount = (BigDecimal) context.get("processAmount");
+ currency = (String) context.get("currency");
+
+ } else {
+ Debug.logWarning("Payment preference " + opp + " is not a credit card", module);
+ }
+ }
+ } catch (GenericEntityException ex) {
+ Debug.logError("Cannot build customer information for " + context + " due to error: " + ex.getMessage(), module);
+ return null;
+ }
+
+ billingInfo.put("orderId", orderId);
+ billingInfo.put("amount", processAmount.toString());
+ billingInfo.put("currency", currency);
+ billingInfo.put("description", orderId);
+ billingInfo.put("cardNumber", cardNumber);
+ billingInfo.put("cardHolder", nameOnCard);
+ billingInfo.put("expiryDate", expireDate);
+ billingInfo.put("cardType", cardType);
+ billingInfo.put("cv2", securityCode);
+ billingInfo.put("billingPostCode", postalCode);
+ billingInfo.put("billingAddress", address);
+
+ Debug.logInfo("SagePay billingInfo : " + billingInfo, module);
+ Debug.logInfo("SagePay - Exiting buildCustomerBillingInfo", module);
+
+ return billingInfo;
+ }
+
+ public static Map ccAuth(DispatchContext dctx, Map context) {
+ Debug.logInfo("SagePay - Entered ccAuth", module);
+ Debug.logInfo("SagePay ccAuth context : " + context, module);
+ Map response = null;
+
+ String orderId = (String) context.get("orderId");
+ GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
+ if (null == orderPaymentPreference) {
+ response = ServiceUtil.returnError("OrderPaymentPreference for order : " + orderId + " is null : " + orderPaymentPreference);
+ } else {
+ response = processCardAuthorisationPayment(dctx, context);
+ }
+ Debug.logInfo("SagePay ccAuth response : " + response, module);
+ Debug.logInfo("SagePay - Exiting ccAuth", module);
+ return response;
+ }
+
+
+ private static Map processCardAuthorisationPayment(DispatchContext ctx, Map context) {
+
+ Map result = ServiceUtil.returnSuccess();
+ LocalDispatcher dispatcher = ctx.getDispatcher();
+
+ Map billingInfo = buildCustomerBillingInfo(context);
+ String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId");
+
+ try {
+
+ Map paymentResult = dispatcher.runSync("SagePayPaymentAuthentication",
+ UtilMisc.toMap(
+ "paymentGatewayConfigId", paymentGatewayConfigId,
+ "vendorTxCode", billingInfo.get("orderId"),
+ "cardHolder", billingInfo.get("cardHolder"),
+ "cardNumber", billingInfo.get("cardNumber"),
+ "expiryDate", billingInfo.get("expiryDate"),
+ "cardType", billingInfo.get("cardType"),
+ "cv2", billingInfo.get("cv2"),
+ "description", billingInfo.get("description"),
+ "amount", billingInfo.get("amount"),
+ "currency", billingInfo.get("currency"),
+ "billingAddress", billingInfo.get("billingAddress"),
+ "billingPostCode", billingInfo.get("billingPostCode")
+ )
+ );
+
+ Debug.logInfo("SagePay - SagePayPaymentAuthentication result : " + paymentResult, module);
+
+ String transactionType = (String) paymentResult.get("transactionType");
+ String status = (String) paymentResult.get("status");
+ String statusDetail = (String) paymentResult.get("statusDetail");
+ String vpsTxId = (String) paymentResult.get("vpsTxId");
+ String securityKey = (String) paymentResult.get("securityKey");
+ String txAuthNo = (String) paymentResult.get("txAuthNo");
+ String vendorTxCode = (String) paymentResult.get("vendorTxCode");
+ String amount = (String) paymentResult.get("amount");
+
+ if (status != null && "OK".equals(status)) {
+ Debug.logInfo("SagePay - Payment authorized for order : " + vendorTxCode, module);
+ result = SagePayUtil.buildCardAuthorisationPaymentResponse(Boolean.TRUE, txAuthNo, securityKey, new BigDecimal(amount), vpsTxId, vendorTxCode, statusDetail);
+ if ("PAYMENT".equals(transactionType)) {
+ Map captureResult = SagePayUtil.buildCardCapturePaymentResponse(Boolean.TRUE, txAuthNo, securityKey, new BigDecimal(amount), vpsTxId, vendorTxCode, statusDetail);
+ result.putAll(captureResult);
+ }
+ } else if (status != null && "INVALID".equals(status)) {
+ Debug.logInfo("SagePay - Invalid authorisation request for order : " + vendorTxCode, module);
+ result = SagePayUtil.buildCardAuthorisationPaymentResponse(Boolean.FALSE, null, null, new BigDecimal("0.00"), "INVALID", vendorTxCode, statusDetail);
+ } else if (status != null && "MALFORMED".equals(status)) {
+ Debug.logInfo("SagePay - Malformed authorisation request for order : " + vendorTxCode, module);
+ result = SagePayUtil.buildCardAuthorisationPaymentResponse(Boolean.FALSE, null, null, new BigDecimal("0.00"), "MALFORMED", vendorTxCode, statusDetail);
+ } else if (status != null && "NOTAUTHED".equals(status)) {
+ Debug.logInfo("SagePay - NotAuthed authorisation request for order : " + vendorTxCode, module);
+ result = SagePayUtil.buildCardAuthorisationPaymentResponse(Boolean.FALSE, null, securityKey, new BigDecimal("0.00"), vpsTxId, vendorTxCode, statusDetail);
+ } else if (status != null && "REJECTED".equals(status)) {
+ Debug.logInfo("SagePay - Rejected authorisation request for order : " + vendorTxCode, module);
+ result = SagePayUtil.buildCardAuthorisationPaymentResponse(Boolean.FALSE, null, securityKey, new BigDecimal(amount), vpsTxId, vendorTxCode, statusDetail);
+ } else {
+ Debug.logInfo("SagePay - Invalid status " + status + " received for order : " + vendorTxCode, module);
+ result = SagePayUtil.buildCardAuthorisationPaymentResponse(Boolean.FALSE, null, null, new BigDecimal("0.00"), "ERROR", vendorTxCode, statusDetail);
+ }
+ } catch(GenericServiceException e) {
+ Debug.logError(e, "Error in calling SagePayPaymentAuthentication", module);
+ result = ServiceUtil.returnError("Exception in calling SagePayPaymentRegistration : " + e.getMessage());
+ }
+ return result;
+ }
+
+ public static Map ccCapture(DispatchContext ctx, Map context) {
+ Debug.logInfo("SagePay - Entered ccCapture", module);
+ Debug.logInfo("SagePay ccCapture context : " + context, module);
+
+ GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
+ GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference);
+ context.put("authTransaction", authTransaction);
+ Map response = processCardCapturePayment(ctx, context);
+
+ Debug.logInfo("SagePay ccCapture response : " + response, module);
+ Debug.logInfo("SagePay - Exiting ccCapture", module);
+
+ return response;
+ }
+
+
+ private static Map processCardCapturePayment(DispatchContext ctx, Map context) {
+
+ Map result = ServiceUtil.returnSuccess();
+ LocalDispatcher dispatcher = ctx.getDispatcher();
+
+ String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId");
+ GenericValue authTransaction = (GenericValue) context.get("authTransaction");
+ BigDecimal amount = (BigDecimal) context.get("captureAmount");
+ String vendorTxCode = (String) authTransaction.get("altReference");
+ String vpsTxId = (String) authTransaction.get("referenceNum");
+ String securityKey = (String) authTransaction.get("gatewayFlag");
+ String txAuthCode = (String) authTransaction.get("gatewayCode");
+
+ try {
+
+ Map paymentResult = dispatcher.runSync("SagePayPaymentAuthorisation",
+ UtilMisc.toMap(
+ "paymentGatewayConfigId", paymentGatewayConfigId,
+ "vendorTxCode", vendorTxCode,
+ "vpsTxId", vpsTxId,
+ "securityKey", securityKey,
+ "txAuthNo", txAuthCode,
+ "amount", amount.toString()
+ )
+ );
+ Debug.logInfo("SagePay - SagePayPaymentAuthorisation result : " + paymentResult, module);
+ String status = (String) paymentResult.get("status");
+ String statusDetail = (String) paymentResult.get("statusDetail");
+ if (status != null && "OK".equals(status)) {
+ Debug.logInfo("SagePay Payment Released for Order : " + vendorTxCode, module);
+ result = SagePayUtil.buildCardCapturePaymentResponse(Boolean.TRUE, txAuthCode, securityKey, amount, vpsTxId, vendorTxCode, statusDetail);
+ } else {
+ Debug.logInfo("SagePay - Invalid status " + status + " received for order : " + vendorTxCode, module);
+ result = SagePayUtil.buildCardCapturePaymentResponse(Boolean.FALSE, txAuthCode, securityKey, amount, vpsTxId, vendorTxCode, statusDetail);
+ }
+ } catch(GenericServiceException e) {
+ Debug.logError(e, "Error in calling SagePayPaymentAuthorisation", module);
+ result = ServiceUtil.returnError("Exception in calling SagePayPaymentRegistration : " + e.getMessage());
+ }
+ return result;
+ }
+
+
+ public static Map ccRefund(DispatchContext ctx, Map context) {
+ Debug.logInfo("SagePay - Entered ccRefund", module);
+ Debug.logInfo("SagePay ccRefund context : " + context, module);
+
+ Delegator delegator = ctx.getDelegator();
+ GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
+ GenericValue captureTransaction = PaymentGatewayServices.getCaptureTransaction(orderPaymentPreference);
+ if (captureTransaction == null) {
+ return ServiceUtil.returnError("No captured transaction found for the OrderPaymentPreference; cannot Refund");
+ }
+ Debug.logInfo("SagePay ccRefund captureTransaction : " + captureTransaction, module);
+ GenericValue creditCard = null;
+ try {
+ creditCard = delegator.getRelatedOne("CreditCard", orderPaymentPreference);
+ } catch (GenericEntityException e) {
+ Debug.logError(e, "Error getting CreditCard for OrderPaymentPreference : " + orderPaymentPreference, module);
+ return ServiceUtil.returnError("Unable to obtain cc information from payment preference");
+ }
+ context.put("creditCard",creditCard);
+ context.put("captureTransaction", captureTransaction);
+
+ List authTransactions = PaymentGatewayServices.getAuthTransactions(orderPaymentPreference);
+
+ EntityCondition authCondition = EntityCondition.makeCondition("paymentServiceTypeEnumId", "PRDS_PAY_AUTH");
+ List authTransactions1 = EntityUtil.filterByCondition(authTransactions, authCondition);
+
+ GenericValue authTransaction = EntityUtil.getFirst(authTransactions1);
+
+ Timestamp authTime = authTransaction.getTimestamp("transactionDate");
+ Calendar authCal = Calendar.getInstance();
+ authCal.setTimeInMillis(authTime.getTime());
+
+ Timestamp nowTime = UtilDateTime.nowTimestamp();
+ Calendar nowCal = Calendar.getInstance();
+ nowCal.setTimeInMillis(nowTime.getTime());
+
+ Calendar yesterday = Calendar.getInstance();
+ yesterday.set(nowCal.get(Calendar.YEAR), nowCal.get(Calendar.MONTH), nowCal.get(Calendar.DATE), 23, 59, 59);
+ yesterday.add(Calendar.DAY_OF_YEAR, -1);
+
+ Map response = null;
+
+ if (authCal.before(yesterday)) {
+ Debug.logInfo("SagePay - Calling Refund for Refund", module);
+ response = processCardRefundPayment(ctx, context);
+ } else {
+
+ Calendar cal = Calendar.getInstance();
+ cal.set(nowCal.get(Calendar.YEAR), nowCal.get(Calendar.MONTH), nowCal.get(Calendar.DATE), 23, 49, 59);
+
+ if (authCal.before(cal)) {
+ Debug.logInfo("SagePay - Calling Void for Refund", module);
+ response = processCardVoidPayment(ctx, context);
+ } else {
+ Debug.logInfo("SagePay - Calling Refund for Refund", module);
+ response = processCardRefundPayment(ctx, context);
+ }
+ }
+
+ Debug.logInfo("SagePay ccRefund response : " + response, module);
+ return response;
+ }
+
+ private static Map processCardRefundPayment(DispatchContext ctx, Map context) {
+
+ Map result = ServiceUtil.returnSuccess();
+ LocalDispatcher dispatcher = ctx.getDispatcher();
+
+ String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId");
+ GenericValue captureTransaction = (GenericValue) context.get("captureTransaction");
+ BigDecimal amount = (BigDecimal) context.get("refundAmount");
+
+ String orderId = (String) captureTransaction.get("altReference");
+ orderId = "R" + orderId;
+
+ try {
+
+ Map paymentResult = dispatcher.runSync("SagePayPaymentRefund",
+ UtilMisc.toMap(
+ "paymentGatewayConfigId", paymentGatewayConfigId,
+ "vendorTxCode", orderId,
+ "amount", amount.toString(),
+ "currency", "GBP",
+ "description", orderId,
+ "relatedVPSTxId", captureTransaction.get("referenceNum"),
+ "relatedVendorTxCode", captureTransaction.get("altReference"),
+ "relatedSecurityKey", captureTransaction.get("gatewayFlag"),
+ "relatedTxAuthNo", captureTransaction.get("gatewayCode")
+ )
+ );
+ Debug.logInfo("SagePay - SagePayPaymentRefund result : " + paymentResult, module);
+
+ String status = (String) paymentResult.get("status");
+ String statusDetail = (String) paymentResult.get("statusDetail");
+ String vpsTxId = (String) paymentResult.get("vpsTxId");
+ String txAuthNo = (String) paymentResult.get("txAuthNo");
+
+ if (status != null && "OK".equals(status)) {
+ Debug.logInfo("SagePay Payment Refunded for Order : " + orderId, module);
+ result = SagePayUtil.buildCardRefundPaymentResponse(Boolean.TRUE, txAuthNo, amount, vpsTxId, orderId, statusDetail);
+ } else {
+ Debug.logInfo("SagePay - Invalid status " + status + " received for order : " + orderId, module);
+ result = SagePayUtil.buildCardRefundPaymentResponse(Boolean.FALSE, null, new BigDecimal("0.00"), status, orderId, statusDetail);
+ }
+
+ } catch(GenericServiceException e) {
+ Debug.logError(e, "Error in calling SagePayPaymentRefund", module);
+ result = ServiceUtil.returnError("Exception in calling SagePayPaymentRefund : " + e.getMessage());
+ }
+
+ return result;
+ }
+
+ private static Map processCardVoidPayment(DispatchContext ctx, Map context) {
+
+ Map result = ServiceUtil.returnSuccess();
+ LocalDispatcher dispatcher = ctx.getDispatcher();
+
+ String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId");
+ GenericValue captureTransaction = (GenericValue) context.get("captureTransaction");
+ BigDecimal amount = (BigDecimal) context.get("refundAmount");
+ String orderId = (String) captureTransaction.get("altReference");
+
+ try {
+
+ Map paymentResult = dispatcher.runSync("SagePayPaymentVoid",
+ UtilMisc.toMap(
+ "paymentGatewayConfigId", paymentGatewayConfigId,
+ "vendorTxCode", captureTransaction.get("altReference"),
+ "vpsTxId", captureTransaction.get("referenceNum"),
+ "securityKey", captureTransaction.get("gatewayFlag"),
+ "txAuthNo", captureTransaction.get("gatewayCode")
+ )
+ );
+
+ Debug.logInfo("SagePay - SagePayPaymentVoid result : " + paymentResult, module);
+
+ String status = (String) paymentResult.get("status");
+ String statusDetail = (String) paymentResult.get("statusDetail");
+
+ if (status != null && "OK".equals(status)) {
+ Debug.logInfo("SagePay Payment Voided for Order : " + orderId, module);
+ result = SagePayUtil.buildCardVoidPaymentResponse(Boolean.TRUE, amount, "SUCCESS", orderId, statusDetail);
+ } else if (status != null && "MALFORMED".equals(status)) {
+ Debug.logInfo("SagePay - Malformed void request for order : " + orderId, module);
+ result = SagePayUtil.buildCardVoidPaymentResponse(Boolean.FALSE, new BigDecimal("0.00"), "MALFORMED", orderId, statusDetail);
+ } else if (status != null && "INVALID".equals(status)){
+ Debug.logInfo("SagePay - Invalid void request for order : " + orderId, module);
+ result = SagePayUtil.buildCardVoidPaymentResponse(Boolean.FALSE, new BigDecimal("0.00"), "INVALID", orderId, statusDetail);
+ } else if (status != null && "ERROR".equals(status)){
+ Debug.logInfo("SagePay - Error in void request for order : " + orderId, module);
+ result = SagePayUtil.buildCardVoidPaymentResponse(Boolean.FALSE, new BigDecimal("0.00"), "ERROR", orderId, statusDetail);
+ }
+
+ } catch(GenericServiceException e) {
+ Debug.logError(e, "Error in calling SagePayPaymentVoid", module);
+ result = ServiceUtil.returnError("Exception in calling SagePayPaymentVoid : " + e.getMessage());
+ }
+ return result;
+ }
+
+ public static Map ccRelease(DispatchContext ctx, Map context) {
+
+ Debug.logInfo("SagePay - Entered ccRelease", module);
+ Debug.logInfo("SagePay ccRelease context : " + context, module);
+
+ GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
+
+ GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference);
+ if (authTransaction == null) {
+ return ServiceUtil.returnError("No authorization transaction found for the OrderPaymentPreference; cannot Release");
+ }
+ context.put("authTransaction", authTransaction);
+
+ Map response = processCardReleasePayment(ctx, context);
+ Debug.logInfo("SagePay ccRelease response : " + response, module);
+ return response;
+ }
+
+ private static Map processCardReleasePayment(DispatchContext ctx, Map context) {
+
+ Map result = ServiceUtil.returnSuccess();
+
+ LocalDispatcher dispatcher = ctx.getDispatcher();
+
+ String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId");
+ BigDecimal amount = (BigDecimal) context.get("releaseAmount");
+
+ GenericValue authTransaction = (GenericValue) context.get("authTransaction");
+ String orderId = (String) authTransaction.get("altReference");
+ String refNum = (String) authTransaction.get("referenceNum");
+
+ try {
+
+ Map paymentResult = dispatcher.runSync("SagePayPaymentRelease",
+ UtilMisc.toMap(
+ "paymentGatewayConfigId", paymentGatewayConfigId,
+ "vendorTxCode", orderId,
+ "releaseAmount", amount.toString(),
+ "vpsTxId", refNum,
+ "securityKey", authTransaction.get("gatewayFlag"),
+ "txAuthNo", authTransaction.get("gatewayCode")
+ )
+ );
+
+ Debug.logInfo("SagePay - SagePayPaymentRelease result : " + paymentResult, module);
+
+ String status = (String) paymentResult.get("status");
+ String statusDetail = (String) paymentResult.get("statusDetail");
+
+ if (status != null && "OK".equals(status)) {
+ Debug.logInfo("SagePay Payment Released for Order : " + orderId, module);
+ result = SagePayUtil.buildCardReleasePaymentResponse(Boolean.TRUE, null, amount, refNum, orderId, statusDetail);
+ } else {
+ Debug.logInfo("SagePay - Invalid status " + status + " received for order : " + orderId, module);
+ result = SagePayUtil.buildCardReleasePaymentResponse(Boolean.FALSE, null, amount, refNum, orderId, statusDetail);
+ }
+
+ } catch(GenericServiceException e) {
+ Debug.logError(e, "Error in calling SagePayPaymentRelease", module);
+ result = ServiceUtil.returnError("Exception in calling SagePayPaymentRefund : " + e.getMessage());
+ }
+
+ return result;
+ }
+
+}
diff --git a/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java b/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java
new file mode 100644
index 0000000000..eeb5dfc164
--- /dev/null
+++ b/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java
@@ -0,0 +1,686 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+
+package org.ofbiz.accounting.thirdparty.sagepay;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.http.HttpHost;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpPost;
+import org.ofbiz.base.util.Debug;
+import org.ofbiz.base.util.UtilMisc;
+import org.ofbiz.base.util.UtilValidate;
+import org.ofbiz.entity.Delegator;
+import org.ofbiz.entity.GenericEntityException;
+import org.ofbiz.entity.GenericValue;
+import org.ofbiz.service.DispatchContext;
+import org.ofbiz.service.ModelService;
+import org.ofbiz.service.ServiceUtil;
+
+public class SagePayServices
+{
+ public static final String module = SagePayServices.class.getName();
+
+ private static Map buildSagePayProperties(Map context, Delegator delegator) {
+
+ Map sagePayConfig = new HashMap();
+
+ String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId");
+
+ if (UtilValidate.isNotEmpty(paymentGatewayConfigId)) {
+ try {
+ GenericValue sagePay = delegator.findOne("PaymentGatewaySagePay", UtilMisc.toMap("paymentGatewayConfigId", paymentGatewayConfigId), false);
+ if (UtilValidate.isNotEmpty(sagePay)) {
+ Map tmp = sagePay.getAllFields();
+ Set keys = tmp.keySet();
+ for (String key : keys) {
+ String value = tmp.get(key).toString();
+ sagePayConfig.put(key, value);
+ }
+ }
+ } catch (GenericEntityException e) {
+ Debug.logError(e, module);
+ }
+ }
+
+ Debug.logInfo("SagePay Configuration : " + sagePayConfig.toString(), module);
+ return sagePayConfig;
+ }
+
+ public static Map paymentAuthentication(DispatchContext ctx, Map context)
+ {
+ Debug.logInfo("SagePay - Entered paymentAuthentication", module);
+ Debug.logInfo("SagePay paymentAuthentication context : " + context, module);
+
+ Delegator delegator = ctx.getDelegator();
+ Map resultMap = new HashMap();
+
+ Map props = buildSagePayProperties(context, delegator);
+
+ String vendorTxCode = (String)context.get("vendorTxCode");
+ String cardHolder = (String) context.get("cardHolder");
+ String cardNumber = (String) context.get("cardNumber");
+ String expiryDate = (String) context.get("expiryDate");
+ String cardType = (String) context.get("cardType");
+ String cv2 = (String) context.get("cv2");
+ String amount = (String) context.get("amount");
+ String currency = (String) context.get("currency");
+ String description = (String) context.get("description");
+
+ String billingSurname = (String) context.get("billingSurname");
+ String billingFirstnames = (String) context.get("billingFirstnames");
+ String billingAddress = (String) context.get("billingAddress");
+ String billingAddress2 = (String) context.get("billingAddress2");
+ String billingCity = (String) context.get("billingCity");
+ String billingPostCode = (String) context.get("billingPostCode");
+ String billingCountry = (String) context.get("billingCountry");
+ String billingState = (String) context.get("billingState");
+ String billingPhone = (String) context.get("billingPhone");
+
+ Boolean isBillingSameAsDelivery = (Boolean) context.get("isBillingSameAsDelivery");
+
+ String deliverySurname = (String) context.get("deliverySurname");
+ String deliveryFirstnames = (String) context.get("deliveryFirstnames");
+ String deliveryAddress = (String) context.get("deliveryAddress");
+ String deliveryAddress2 = (String) context.get("deliveryAddress2");
+ String deliveryCity = (String) context.get("deliveryCity");
+ String deliveryPostCode = (String) context.get("deliveryPostCode");
+ String deliveryCountry = (String) context.get("deliveryCountry");
+ String deliveryState = (String) context.get("deliveryState");
+ String deliveryPhone = (String) context.get("deliveryPhone");
+
+ String startDate = (String) context.get("startDate");
+ String issueNumber = (String) context.get("issueNumber");
+ String basket = (String) context.get("basket");
+ String clientIPAddress = (String) context.get("clientIPAddress");
+
+ HttpClient httpClient = SagePayUtil.getHttpClient();
+ HttpHost host = SagePayUtil.getHost(props);
+
+ //start - authentication parameters
+ Map parameters = new HashMap();
+
+ String vpsProtocol = props.get("protocolVersion");
+ String vendor = props.get("vendor");
+ String txType = props.get("authenticationTransType");
+
+ //start - required parameters
+ parameters.put("VPSProtocol", vpsProtocol);
+ parameters.put("TxType", txType);
+ parameters.put("Vendor", vendor);
+
+ if (vendorTxCode != null) { parameters.put("VendorTxCode", vendorTxCode); }
+ if (amount != null) { parameters.put("Amount", amount); }
+ if (currency != null) { parameters.put("Currency", currency); } //GBP/USD
+ if (description != null) { parameters.put("Description", description); }
+ if (cardHolder != null) { parameters.put("CardHolder", cardHolder); }
+ if (cardNumber != null) { parameters.put("CardNumber", cardNumber); }
+ if (expiryDate != null) { parameters.put("ExpiryDate", expiryDate); }
+ if (cardType != null) { parameters.put("CardType", cardType); }
+
+ //start - billing details
+ if (billingSurname != null) { parameters.put("BillingSurname", billingSurname); }
+ if (billingFirstnames != null) { parameters.put("BillingFirstnames", billingFirstnames); }
+ if (billingAddress != null) { parameters.put("BillingAddress", billingAddress); }
+ if (billingAddress2 != null) { parameters.put("BillingAddress2", billingAddress2); }
+ if (billingCity != null) { parameters.put("BillingCity", billingCity); }
+ if (billingPostCode != null) { parameters.put("BillingPostCode", billingPostCode); }
+ if (billingCountry != null) { parameters.put("BillingCountry", billingCountry); }
+ if (billingState != null) { parameters.put("BillingState", billingState); }
+ if (billingPhone != null) { parameters.put("BillingPhone", billingPhone); }
+ //end - billing details
+
+ //start - delivery details
+ if (isBillingSameAsDelivery != null && isBillingSameAsDelivery) {
+ if (billingSurname != null) { parameters.put("DeliverySurname", billingSurname); }
+ if (billingFirstnames != null) { parameters.put("DeliveryFirstnames", billingFirstnames); }
+ if (billingAddress != null) { parameters.put("DeliveryAddress", billingAddress); }
+ if (billingAddress2 != null) { parameters.put("DeliveryAddress2", billingAddress2); }
+ if (billingCity != null) { parameters.put("DeliveryCity", billingCity); }
+ if (billingPostCode != null) { parameters.put("DeliveryPostCode", billingPostCode); }
+ if (billingCountry != null) { parameters.put("DeliveryCountry", billingCountry); }
+ if (billingState != null) { parameters.put("DeliveryState", billingState); }
+ if (billingPhone != null) { parameters.put("DeliveryPhone", billingPhone); }
+ } else {
+ if (deliverySurname != null) { parameters.put("DeliverySurname", deliverySurname); }
+ if (deliveryFirstnames != null) { parameters.put("DeliveryFirstnames", deliveryFirstnames); }
+ if (deliveryAddress != null) { parameters.put("DeliveryAddress", deliveryAddress); }
+ if (deliveryAddress2 != null) { parameters.put("DeliveryAddress2", deliveryAddress2); }
+ if (deliveryCity != null) { parameters.put("DeliveryCity", deliveryCity); }
+ if (deliveryPostCode != null) { parameters.put("DeliveryPostCode", deliveryPostCode); }
+ if (deliveryCountry != null) { parameters.put("DeliveryCountry", deliveryCountry); }
+ if (deliveryState != null) { parameters.put("DeliveryState", deliveryState); }
+ if (deliveryPhone != null) {parameters.put("DeliveryPhone", deliveryPhone); }
+ }
+ //end - delivery details
+ //end - required parameters
+
+ //start - optional parameters
+ if (cv2 != null) { parameters.put("CV2", cv2); }
+ if (startDate != null) { parameters.put("StartDate", startDate); }
+ if (issueNumber != null) { parameters.put("IssueNumber", issueNumber); }
+ if (basket != null) { parameters.put("Basket", basket); }
+ if (clientIPAddress != null) { parameters.put("ClientIPAddress", clientIPAddress); }
+ //end - optional parameters
+ //end - authentication parameters
+
+ try {
+
+ String successMessage = null;
+ HttpPost httpPost = SagePayUtil.getHttpPost(props.get("authenticationUrl"), parameters);
+ HttpResponse response = httpClient.execute(host, httpPost);
+ Map responseData = SagePayUtil.getResponseData(response);
+
+ String status = responseData.get("Status");
+ String statusDetail = responseData.get("StatusDetail");
+
+ resultMap.put("status", status);
+ resultMap.put("statusDetail", statusDetail);
+
+ //returning the below details back to the calling code, as it not returned back by the payment gateway
+ resultMap.put("vendorTxCode", vendorTxCode);
+ resultMap.put("amount", amount);
+ resultMap.put("transactionType", txType);
+
+ //start - transaction authorized
+ if ("OK".equals(status)) {
+ resultMap.put("vpsTxId", responseData.get("VPSTxId"));
+ resultMap.put("securityKey", responseData.get("SecurityKey"));
+ resultMap.put("txAuthNo", responseData.get("TxAuthNo"));
+ resultMap.put("avsCv2", responseData.get("AVSCV2"));
+ resultMap.put("addressResult", responseData.get("AddressResult"));
+ resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
+ resultMap.put("cv2Result", responseData.get("CV2Result"));
+ successMessage = "Payment authorized";
+ }
+ //end - transaction authorized
+
+ if ("NOTAUTHED".equals(status)) {
+ resultMap.put("vpsTxId", responseData.get("VPSTxId"));
+ resultMap.put("securityKey", responseData.get("SecurityKey"));
+ resultMap.put("avsCv2", responseData.get("AVSCV2"));
+ resultMap.put("addressResult", responseData.get("AddressResult"));
+ resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
+ resultMap.put("cv2Result", responseData.get("CV2Result"));
+ successMessage = "Payment not authorized";
+ }
+
+ if ("MALFORMED".equals(status)) {
+ //request not formed properly or parameters missing
+ resultMap.put("vpsTxId", responseData.get("VPSTxId"));
+ resultMap.put("securityKey", responseData.get("SecurityKey"));
+ resultMap.put("avsCv2", responseData.get("AVSCV2"));
+ resultMap.put("addressResult", responseData.get("AddressResult"));
+ resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
+ resultMap.put("cv2Result", responseData.get("CV2Result"));
+ }
+
+ if ("INVALID".equals(status)) {
+ //invalid information in request
+ resultMap.put("vpsTxId", responseData.get("VPSTxId"));
+ resultMap.put("securityKey", responseData.get("SecurityKey"));
+ resultMap.put("avsCv2", responseData.get("AVSCV2"));
+ resultMap.put("addressResult", responseData.get("AddressResult"));
+ resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
+ resultMap.put("cv2Result", responseData.get("CV2Result"));
+ }
+
+ if ("REJECTED".equals(status)) {
+ //invalid information in request
+ resultMap.put("vpsTxId", responseData.get("VPSTxId"));
+ resultMap.put("securityKey", responseData.get("SecurityKey"));
+ resultMap.put("avsCv2", responseData.get("AVSCV2"));
+ resultMap.put("addressResult", responseData.get("AddressResult"));
+ resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
+ resultMap.put("cv2Result", responseData.get("CV2Result"));
+ }
+
+ resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
+ resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage);
+
+ } catch(UnsupportedEncodingException uee) {
+ //exception in encoding parameters in httpPost
+ String errorMsg = "Error occured in encoding parameters for HttpPost (" + uee.getMessage() + ")";
+ Debug.logError(uee, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } catch(ClientProtocolException cpe) {
+ //from httpClient execute
+ String errorMsg = "Error occured in HttpClient execute(" + cpe.getMessage() + ")";
+ Debug.logError(cpe, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } catch(IOException ioe) {
+ //from httpClient execute or getResponsedata
+ String errorMsg = "Error occured in HttpClient execute or getting response (" + ioe.getMessage() + ")";
+ Debug.logError(ioe, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } finally {
+ httpClient.getConnectionManager().shutdown();
+ }
+ return resultMap;
+ }
+
+ public static Map paymentAuthorisation(DispatchContext ctx, Map context)
+ {
+ Debug.logInfo("SagePay - Entered paymentAuthorisation", module);
+ Debug.logInfo("SagePay paymentAuthorisation context : " + context, module);
+
+ Delegator delegator = ctx.getDelegator();
+ Map resultMap = new HashMap();
+
+ Map props = buildSagePayProperties(context, delegator);
+
+ String vendorTxCode = (String)context.get("vendorTxCode");
+ String vpsTxId = (String) context.get("vpsTxId");
+ String securityKey = (String) context.get("securityKey");
+ String txAuthNo = (String) context.get("txAuthNo");
+ String amount = (String) context.get("amount");
+
+ HttpClient httpClient = SagePayUtil.getHttpClient();
+ HttpHost host = SagePayUtil.getHost(props);
+
+ //start - authorization parameters
+ Map parameters = new HashMap();
+
+ String vpsProtocol = props.get("protocolVersion");
+ String vendor = props.get("vendor");
+ String txType = props.get("authoriseTransType");
+
+ parameters.put("VPSProtocol", vpsProtocol);
+ parameters.put("TxType", txType);
+ parameters.put("Vendor", vendor);
+ parameters.put("VendorTxCode", vendorTxCode);
+ parameters.put("VPSTxId", vpsTxId);
+ parameters.put("SecurityKey", securityKey);
+ parameters.put("TxAuthNo", txAuthNo);
+ parameters.put("ReleaseAmount", amount);
+
+ Debug.logInfo("authorization parameters -> " + parameters, module);
+ //end - authorization parameters
+
+ try {
+ String successMessage = null;
+ HttpPost httpPost = SagePayUtil.getHttpPost(props.get("authoriseUrl"), parameters);
+ HttpResponse response = httpClient.execute(host, httpPost);
+
+ Map responseData = SagePayUtil.getResponseData(response);
+ String status = responseData.get("Status");
+ String statusDetail = responseData.get("StatusDetail");
+
+ resultMap.put("status", status);
+ resultMap.put("statusDetail", statusDetail);
+
+ //start - payment refunded
+ if ("OK".equals(status)) {
+ successMessage = "Payment Released";
+ }
+ //end - payment refunded
+
+ //start - refund request not formed properly or parameters missing
+ if ("MALFORMED".equals(status)) {
+ successMessage = "Released request not formed properly or parameters missing";
+ }
+ //end - refund request not formed properly or parameters missing
+
+ //start - invalid information passed in parameters
+ if ("INVALID".equals(status)) {
+ successMessage = "Invalid information passed in parameters";
+ }
+ //end - invalid information passed in parameters
+
+ //start - problem at Sagepay
+ if ("ERROR".equals(status)) {
+ successMessage = "Problem at SagePay";
+ }
+ //end - problem at Sagepay
+
+ resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
+ resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage);
+
+ } catch(UnsupportedEncodingException uee) {
+ //exception in encoding parameters in httpPost
+ String errorMsg = "Error occured in encoding parameters for HttpPost (" + uee.getMessage() + ")";
+ Debug.logError(uee, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } catch(ClientProtocolException cpe) {
+ //from httpClient execute
+ String errorMsg = "Error occured in HttpClient execute(" + cpe.getMessage() + ")";
+ Debug.logError(cpe, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } catch(IOException ioe) {
+ //from httpClient execute or getResponsedata
+ String errorMsg = "Error occured in HttpClient execute or getting response (" + ioe.getMessage() + ")";
+ Debug.logError(ioe, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } finally {
+ httpClient.getConnectionManager().shutdown();
+ }
+ return resultMap;
+ }
+
+ public static Map paymentRelease(DispatchContext ctx, Map context)
+ {
+ Debug.logInfo("SagePay - Entered paymentRelease", module);
+ Debug.logInfo("SagePay paymentRelease context : " + context, module);
+
+ Delegator delegator = ctx.getDelegator();
+ Map resultMap = new HashMap();
+
+ Map props = buildSagePayProperties(context, delegator);
+
+ String vendorTxCode = (String)context.get("vendorTxCode");
+ String vpsTxId = (String) context.get("vpsTxId");
+ String securityKey = (String) context.get("securityKey");
+ String txAuthNo = (String) context.get("txAuthNo");
+
+ HttpClient httpClient = SagePayUtil.getHttpClient();
+ HttpHost host = SagePayUtil.getHost(props);
+
+ //start - release parameters
+ Map parameters = new HashMap();
+
+ String vpsProtocol = props.get("protocolVersion");
+ String vendor = props.get("vendor");
+ String txType = props.get("releaseTransType");
+
+ parameters.put("VPSProtocol", vpsProtocol);
+ parameters.put("TxType", txType);
+ parameters.put("Vendor", vendor);
+ parameters.put("VendorTxCode", vendorTxCode);
+ parameters.put("VPSTxId", vpsTxId);
+ parameters.put("SecurityKey", securityKey);
+ parameters.put("TxAuthNo", txAuthNo);
+ //end - release parameters
+
+ try {
+
+ String successMessage = null;
+ HttpPost httpPost = SagePayUtil.getHttpPost(props.get("releaseUrl"), parameters);
+ HttpResponse response = httpClient.execute(host, httpPost);
+
+ Map responseData = SagePayUtil.getResponseData(response);
+
+ String status = responseData.get("Status");
+ String statusDetail = responseData.get("StatusDetail");
+
+ resultMap.put("status", status);
+ resultMap.put("statusDetail", statusDetail);
+
+ //start - payment released
+ if ("OK".equals(status)) {
+ successMessage = "Payment Released";
+ }
+ //end - payment released
+
+ //start - release request not formed properly or parameters missing
+ if ("MALFORMED".equals(status)) {
+ successMessage = "Release request not formed properly or parameters missing";
+ }
+ //end - release request not formed properly or parameters missing
+
+ //start - invalid information passed in parameters
+ if ("INVALID".equals(status)) {
+ successMessage = "Invalid information passed in parameters";
+ }
+ //end - invalid information passed in parameters
+
+ //start - problem at Sagepay
+ if ("ERROR".equals(status)) {
+ successMessage = "Problem at SagePay";
+ }
+ //end - problem at Sagepay
+
+ resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
+ resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage);
+
+ } catch(UnsupportedEncodingException uee) {
+ //exception in encoding parameters in httpPost
+ String errorMsg = "Error occured in encoding parameters for HttpPost (" + uee.getMessage() + ")";
+ Debug.logError(uee, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } catch(ClientProtocolException cpe) {
+ //from httpClient execute
+ String errorMsg = "Error occured in HttpClient execute(" + cpe.getMessage() + ")";
+ Debug.logError(cpe, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } catch(IOException ioe) {
+ //from httpClient execute or getResponsedata
+ String errorMsg = "Error occured in HttpClient execute or getting response (" + ioe.getMessage() + ")";
+ Debug.logError(ioe, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } finally {
+ httpClient.getConnectionManager().shutdown();
+ }
+ return resultMap;
+ }
+
+ public static Map paymentVoid(DispatchContext ctx, Map context)
+ {
+ Debug.logInfo("SagePay - Entered paymentVoid", module);
+ Debug.logInfo("SagePay paymentVoid context : " + context, module);
+
+ Delegator delegator = ctx.getDelegator();
+ Map resultMap = new HashMap();
+
+ Map props = buildSagePayProperties(context, delegator);
+
+ String vendorTxCode = (String)context.get("vendorTxCode");
+ String vpsTxId = (String) context.get("vpsTxId");
+ String securityKey = (String) context.get("securityKey");
+ String txAuthNo = (String) context.get("txAuthNo");
+
+ HttpClient httpClient = SagePayUtil.getHttpClient();
+ HttpHost host = SagePayUtil.getHost(props);
+
+ //start - void parameters
+ Map parameters = new HashMap();
+
+ String vpsProtocol = props.get("protocolVersion");
+ String vendor = props.get("vendor");
+
+ parameters.put("VPSProtocol", vpsProtocol);
+ parameters.put("TxType", "VOID");
+ parameters.put("Vendor", vendor);
+ parameters.put("VendorTxCode", vendorTxCode);
+ parameters.put("VPSTxId", vpsTxId);
+ parameters.put("SecurityKey", securityKey);
+ parameters.put("TxAuthNo", txAuthNo);
+ //end - void parameters
+
+ try {
+ String successMessage = null;
+
+ HttpPost httpPost = SagePayUtil.getHttpPost(props.get("voidUrl"), parameters);
+ HttpResponse response = httpClient.execute(host, httpPost);
+ Map responseData = SagePayUtil.getResponseData(response);
+
+ String status = responseData.get("Status");
+ String statusDetail = responseData.get("StatusDetail");
+
+ resultMap.put("status", status);
+ resultMap.put("statusDetail", statusDetail);
+
+ //start - payment void
+ if ("OK".equals(status)) {
+ successMessage = "Payment Voided";
+ }
+ //end - payment void
+
+ //start - void request not formed properly or parameters missing
+ if ("MALFORMED".equals(status)) {
+ successMessage = "Void request not formed properly or parameters missing";
+ }
+ //end - void request not formed properly or parameters missing
+
+ //start - invalid information passed in parameters
+ if ("INVALID".equals(status)) {
+ successMessage = "Invalid information passed in parameters";
+ }
+ //end - invalid information passed in parameters
+
+ //start - problem at Sagepay
+ if ("ERROR".equals(status)) {
+ successMessage = "Problem at SagePay";
+ }
+ //end - problem at Sagepay
+
+ resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
+ resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage);
+
+ } catch(UnsupportedEncodingException uee) {
+ //exception in encoding parameters in httpPost
+ String errorMsg = "Error occured in encoding parameters for HttpPost (" + uee.getMessage() + ")";
+ Debug.logError(uee, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } catch(ClientProtocolException cpe) {
+ //from httpClient execute
+ String errorMsg = "Error occured in HttpClient execute(" + cpe.getMessage() + ")";
+ Debug.logError(cpe, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } catch(IOException ioe) {
+ //from httpClient execute or getResponsedata
+ String errorMsg = "Error occured in HttpClient execute or getting response (" + ioe.getMessage() + ")";
+ Debug.logError(ioe, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } finally {
+ httpClient.getConnectionManager().shutdown();
+ }
+ return resultMap;
+ }
+
+ public static Map paymentRefund(DispatchContext ctx, Map context)
+ {
+ Debug.logInfo("SagePay - Entered paymentRefund", module);
+ Debug.logInfo("SagePay paymentRefund context : " + context, module);
+
+ Delegator delegator = ctx.getDelegator();
+ Map resultMap = new HashMap();
+
+ Map props = buildSagePayProperties(context, delegator);
+
+ String vendorTxCode = (String)context.get("vendorTxCode");
+ String amount = (String)context.get("amount");
+ String currency = (String)context.get("currency");
+ String description = (String)context.get("description");
+
+ String relatedVPSTxId = (String) context.get("relatedVPSTxId");
+ String relatedVendorTxCode = (String) context.get("relatedVendorTxCode");
+ String relatedSecurityKey = (String) context.get("relatedSecurityKey");
+ String relatedTxAuthNo = (String) context.get("relatedTxAuthNo");
+
+ HttpClient httpClient = SagePayUtil.getHttpClient();
+ HttpHost host = SagePayUtil.getHost(props);
+
+ //start - refund parameters
+ Map parameters = new HashMap();
+
+ String vpsProtocol = props.get("protocolVersion");
+ String vendor = props.get("vendor");
+
+ parameters.put("VPSProtocol", vpsProtocol);
+ parameters.put("TxType", "REFUND");
+ parameters.put("Vendor", vendor);
+ parameters.put("VendorTxCode", vendorTxCode);
+ parameters.put("Amount", amount);
+ parameters.put("Currency", currency);
+ parameters.put("Description", description);
+ parameters.put("RelatedVPSTxId", relatedVPSTxId);
+ parameters.put("RelatedVendorTxCode", relatedVendorTxCode);
+ parameters.put("RelatedSecurityKey", relatedSecurityKey);
+ parameters.put("RelatedTxAuthNo", relatedTxAuthNo);
+ //end - refund parameters
+
+ try {
+ String successMessage = null;
+
+ HttpPost httpPost = SagePayUtil.getHttpPost(props.get("refundUrl"), parameters);
+ HttpResponse response = httpClient.execute(host, httpPost);
+ Map responseData = SagePayUtil.getResponseData(response);
+
+ Debug.logInfo("response data -> " + responseData, module);
+
+ String status = responseData.get("Status");
+ String statusDetail = responseData.get("StatusDetail");
+
+ resultMap.put("status", status);
+ resultMap.put("statusDetail", statusDetail);
+
+ //start - payment refunded
+ if ("OK".equals(status)) {
+ resultMap.put("vpsTxId", responseData.get("VPSTxId"));
+ resultMap.put("txAuthNo", responseData.get("TxAuthNo"));
+ successMessage = "Payment Refunded";
+ }
+ //end - payment refunded
+
+ //start - refund not authorized by the acquiring bank
+ if ("NOTAUTHED".equals(status)) {
+ successMessage = "Refund not authorized by the acquiring bank";
+ }
+ //end - refund not authorized by the acquiring bank
+
+ //start - refund request not formed properly or parameters missing
+ if ("MALFORMED".equals(status)) {
+ successMessage = "Refund request not formed properly or parameters missing";
+ }
+ //end - refund request not formed properly or parameters missing
+
+ //start - invalid information passed in parameters
+ if ("INVALID".equals(status)) {
+ successMessage = "Invalid information passed in parameters";
+ }
+ //end - invalid information passed in parameters
+
+ //start - problem at Sagepay
+ if ("ERROR".equals(status)) {
+ successMessage = "Problem at SagePay";
+ }
+ //end - problem at Sagepay
+
+ resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
+ resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage);
+
+ } catch(UnsupportedEncodingException uee) {
+ //exception in encoding parameters in httpPost
+ String errorMsg = "Error occured in encoding parameters for HttpPost (" + uee.getMessage() + ")";
+ Debug.logError(uee, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } catch(ClientProtocolException cpe) {
+ //from httpClient execute
+ String errorMsg = "Error occured in HttpClient execute(" + cpe.getMessage() + ")";
+ Debug.logError(cpe, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } catch(IOException ioe) {
+ //from httpClient execute or getResponsedata
+ String errorMsg = "Error occured in HttpClient execute or getting response (" + ioe.getMessage() + ")";
+ Debug.logError(ioe, errorMsg, module);
+ resultMap = ServiceUtil.returnError(errorMsg);
+ } finally {
+ httpClient.getConnectionManager().shutdown();
+ }
+
+ return resultMap;
+ }
+}
diff --git a/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java b/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java
new file mode 100644
index 0000000000..180c5bdebd
--- /dev/null
+++ b/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java
@@ -0,0 +1,187 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+
+package org.ofbiz.accounting.thirdparty.sagepay;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javolution.util.FastMap;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpHost;
+import org.apache.http.HttpResponse;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.params.BasicHttpParams;
+import org.apache.http.params.HttpParams;
+import org.ofbiz.base.util.Debug;
+
+
+public class SagePayUtil
+{
+ public static final String module = SagePayUtil.class.getName();
+
+ public static Map buildCardAuthorisationPaymentResponse
+ (Boolean authResult, String authCode, String authFlag, BigDecimal processAmount, String authRefNum, String authAltRefNum, String authMessage) {
+
+ Map result = FastMap.newInstance();
+ if(authResult != null) { result.put("authResult", authResult); }
+ if(authCode != null) { result.put("authCode", authCode); }
+ if(authFlag != null) { result.put("authFlag", authFlag); }
+ if(processAmount != null) { result.put("processAmount", processAmount); }
+ if(authRefNum != null) { result.put("authRefNum", authRefNum); }
+ if(authAltRefNum != null) { result.put("authAltRefNum", authAltRefNum); }
+ if(authMessage != null) { result.put("authMessage", authMessage); }
+ return result;
+ }
+
+ public static Map buildCardCapturePaymentResponse
+ (Boolean captureResult, String captureCode, String captureFlag, BigDecimal captureAmount, String captureRefNum, String captureAltRefNum, String captureMessage) {
+
+ Map result = FastMap.newInstance();
+ if(captureResult != null) { result.put("captureResult", captureResult); }
+ if(captureCode != null) { result.put("captureCode", captureCode); }
+ if(captureFlag != null) { result.put("captureFlag", captureFlag); }
+ if(captureAmount != null) { result.put("captureAmount", captureAmount); }
+ if(captureRefNum != null) { result.put("captureRefNum", captureRefNum); }
+ if(captureAltRefNum != null) { result.put("captureAltRefNum", captureAltRefNum); }
+ if(captureMessage != null) { result.put("captureMessage", captureMessage); }
+ return result;
+ }
+
+ public static Map buildCardReleasePaymentResponse
+ (Boolean releaseResult, String releaseCode, BigDecimal releaseAmount, String releaseRefNum, String releaseAltRefNum, String releaseMessage) {
+
+ Map result = FastMap.newInstance();
+ if(releaseResult != null) { result.put("releaseResult", releaseResult); }
+ if(releaseCode != null) { result.put("releaseCode", releaseCode); }
+ if(releaseAmount != null) { result.put("releaseAmount", releaseAmount); }
+ if(releaseRefNum != null) { result.put("releaseRefNum", releaseRefNum); }
+ if(releaseAltRefNum != null) { result.put("releaseAltRefNum", releaseAltRefNum); }
+ if(releaseMessage != null) { result.put("releaseMessage", releaseMessage); }
+ return result;
+ }
+
+ public static Map buildCardVoidPaymentResponse
+ (Boolean refundResult, BigDecimal refundAmount, String refundRefNum, String refundAltRefNum, String refundMessage) {
+
+ Map result = FastMap.newInstance();
+ if(refundResult != null) { result.put("refundResult", refundResult); }
+ if(refundAmount != null) { result.put("refundAmount", refundAmount); }
+ if(refundRefNum != null) { result.put("refundRefNum", refundRefNum); }
+ if(refundAltRefNum != null) { result.put("refundAltRefNum", refundAltRefNum); }
+ if(refundMessage != null) { result.put("refundMessage", refundMessage); }
+ return result;
+ }
+
+ public static Map buildCardRefundPaymentResponse
+ (Boolean refundResult, String refundCode, BigDecimal refundAmount, String refundRefNum, String refundAltRefNum, String refundMessage) {
+
+ Map result = FastMap.newInstance();
+ if(refundResult != null) { result.put("refundResult", refundResult); }
+ if(refundCode != null) { result.put("refundCode", refundCode); }
+ if(refundAmount != null) { result.put("refundAmount", refundAmount); }
+ if(refundRefNum != null) { result.put("refundRefNum", refundRefNum); }
+ if(refundAltRefNum != null) { result.put("refundAltRefNum", refundAltRefNum); }
+ if(refundMessage != null) { result.put("refundMessage", refundMessage); }
+ return result;
+ }
+
+ public static HttpHost getHost(Map props) {
+ String hostUrl = null;
+ if("PRODUCTION".equals(props.get("mode"))) {
+ hostUrl = props.get("productionHost");
+ } else if("TEST".equals(props.get("mode"))) {
+ hostUrl = props.get("testingHost");
+ }
+ String scheme = hostUrl.substring(0, 5);
+ String host = hostUrl.substring(8, hostUrl.lastIndexOf(":"));
+ String port = hostUrl.substring(hostUrl.lastIndexOf(":")+1);
+ return getHost(host, Integer.parseInt(port), scheme);
+ }
+
+ public static HttpHost getHost(String hostName, int port, String scheme) {
+ HttpHost host = new HttpHost(hostName, port, scheme);
+ return host;
+ }
+
+ public static Map getResponseData(HttpResponse response) throws IOException {
+
+ Map responseData = new HashMap();
+ HttpEntity httpEntity = response.getEntity();
+ if (httpEntity != null) {
+ InputStream inputStream = httpEntity.getContent();
+ BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
+
+ String data = null;
+ while( (data = reader.readLine()) != null ) {
+ if(data.indexOf("=") != -1) {
+ String name = data.substring(0, data.indexOf("="));
+ String value = data.substring(data.indexOf("=")+1);
+ responseData.put(name, value);
+ }
+ }
+ }
+ Debug.log("SagePay Response Data : " + responseData);
+ return responseData;
+ }
+
+ public static HttpPost getHttpPost(String uri, Map parameters) throws UnsupportedEncodingException {
+
+ HttpPost httpPost = new HttpPost(uri);
+ httpPost.addHeader("User-Agent", "HTTP Client");
+ httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
+ //postMethod.addHeader("Content-Length", "0");
+
+ HttpParams params = new BasicHttpParams();
+ httpPost.setParams(params);
+
+ List postParameters = new ArrayList();
+ Set keys = parameters.keySet();
+ for (String key : keys) {
+ String value = parameters.get(key);
+ postParameters.add(new BasicNameValuePair(key, value));
+ }
+
+ Debug.log("SagePay PostParameters - " + postParameters);
+
+ HttpEntity postEntity = new UrlEncodedFormEntity(postParameters);
+ httpPost.setEntity(postEntity);
+ return httpPost;
+ }
+
+ public static HttpClient getHttpClient() {
+ HttpClient httpClient = new DefaultHttpClient();
+ return httpClient;
+ }
+}
diff --git a/applications/accounting/webapp/accounting/WEB-INF/controller.xml b/applications/accounting/webapp/accounting/WEB-INF/controller.xml
index 3465cc2ef6..b28961b5fa 100644
--- a/applications/accounting/webapp/accounting/WEB-INF/controller.xml
+++ b/applications/accounting/webapp/accounting/WEB-INF/controller.xml
@@ -499,6 +499,12 @@ under the License.
+
+
+
+
+
+
diff --git a/applications/accounting/widget/PaymentGatewayConfigForms.xml b/applications/accounting/widget/PaymentGatewayConfigForms.xml
index 7e3e19a900..7b2f517451 100644
--- a/applications/accounting/widget/PaymentGatewayConfigForms.xml
+++ b/applications/accounting/widget/PaymentGatewayConfigForms.xml
@@ -68,6 +68,56 @@ under the License.
+
+