Added: ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java?rev=882103&view=auto ============================================================================== --- ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java (added) +++ ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java Thu Nov 19 11:01:29 2009 @@ -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<String, String> buildSagePayProperties(Map<String, Object> context, Delegator delegator) { + + Map<String, String> sagePayConfig = new HashMap<String, String>(); + + 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<String, Object> tmp = sagePay.getAllFields(); + Set<String> 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<String, Object> paymentAuthentication(DispatchContext ctx, Map<String, Object> context) + { + Debug.logInfo("SagePay - Entered paymentAuthentication", module); + Debug.logInfo("SagePay paymentAuthentication context : " + context, module); + + Delegator delegator = ctx.getDelegator(); + Map<String, Object> resultMap = new HashMap<String, Object>(); + + Map<String, String> 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<String, String> parameters = new HashMap<String, String>(); + + 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<String, String> 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<String, Object> paymentAuthorisation(DispatchContext ctx, Map<String, Object> context) + { + Debug.logInfo("SagePay - Entered paymentAuthorisation", module); + Debug.logInfo("SagePay paymentAuthorisation context : " + context, module); + + Delegator delegator = ctx.getDelegator(); + Map<String, Object> resultMap = new HashMap<String, Object>(); + + Map<String, String> 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<String, String> parameters = new HashMap<String, String>(); + + 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<String, String> 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<String, Object> paymentRelease(DispatchContext ctx, Map<String, Object> context) + { + Debug.logInfo("SagePay - Entered paymentRelease", module); + Debug.logInfo("SagePay paymentRelease context : " + context, module); + + Delegator delegator = ctx.getDelegator(); + Map<String, Object> resultMap = new HashMap<String, Object>(); + + Map<String, String> 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<String, String> parameters = new HashMap<String, String>(); + + 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<String, String> 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<String, Object> paymentVoid(DispatchContext ctx, Map<String, Object> context) + { + Debug.logInfo("SagePay - Entered paymentVoid", module); + Debug.logInfo("SagePay paymentVoid context : " + context, module); + + Delegator delegator = ctx.getDelegator(); + Map<String, Object> resultMap = new HashMap<String, Object>(); + + Map<String, String> 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<String, String> parameters = new HashMap<String, String>(); + + 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<String, String> 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<String, Object> paymentRefund(DispatchContext ctx, Map<String, Object> context) + { + Debug.logInfo("SagePay - Entered paymentRefund", module); + Debug.logInfo("SagePay paymentRefund context : " + context, module); + + Delegator delegator = ctx.getDelegator(); + Map<String, Object> resultMap = new HashMap<String, Object>(); + + Map<String, String> 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<String, String> parameters = new HashMap<String, String>(); + + 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<String, String> 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; + } +} Propchange: ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java ------------------------------------------------------------------------------ svn:eol-style = native Propchange: ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java ------------------------------------------------------------------------------ svn:keywords = "Date Rev Author URL Id" Propchange: ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java ------------------------------------------------------------------------------ svn:mime-type = text/plain Added: ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java?rev=882103&view=auto ============================================================================== --- ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java (added) +++ ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java Thu Nov 19 11:01:29 2009 @@ -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<String, Object> buildCardAuthorisationPaymentResponse + (Boolean authResult, String authCode, String authFlag, BigDecimal processAmount, String authRefNum, String authAltRefNum, String authMessage) { + + Map<String, Object> 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<String, Object> buildCardCapturePaymentResponse + (Boolean captureResult, String captureCode, String captureFlag, BigDecimal captureAmount, String captureRefNum, String captureAltRefNum, String captureMessage) { + + Map<String, Object> 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<String, Object> buildCardReleasePaymentResponse + (Boolean releaseResult, String releaseCode, BigDecimal releaseAmount, String releaseRefNum, String releaseAltRefNum, String releaseMessage) { + + Map<String, Object> 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<String, Object> buildCardVoidPaymentResponse + (Boolean refundResult, BigDecimal refundAmount, String refundRefNum, String refundAltRefNum, String refundMessage) { + + Map<String, Object> 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<String, Object> buildCardRefundPaymentResponse + (Boolean refundResult, String refundCode, BigDecimal refundAmount, String refundRefNum, String refundAltRefNum, String refundMessage) { + + Map<String, Object> 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<String, String> 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<String, String> getResponseData(HttpResponse response) throws IOException { + + Map<String, String> responseData = new HashMap<String, String>(); + 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<String, String> 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<NameValuePair> postParameters = new ArrayList<NameValuePair>(); + Set<String> 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; + } +} Propchange: ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java ------------------------------------------------------------------------------ svn:eol-style = native Propchange: ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java ------------------------------------------------------------------------------ svn:keywords = "Date Rev Author URL Id" Propchange: ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java ------------------------------------------------------------------------------ svn:mime-type = text/plain Modified: ofbiz/trunk/applications/accounting/webapp/accounting/WEB-INF/controller.xml URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/accounting/webapp/accounting/WEB-INF/controller.xml?rev=882103&r1=882102&r2=882103&view=diff ============================================================================== --- ofbiz/trunk/applications/accounting/webapp/accounting/WEB-INF/controller.xml (original) +++ ofbiz/trunk/applications/accounting/webapp/accounting/WEB-INF/controller.xml Thu Nov 19 11:01:29 2009 @@ -499,6 +499,12 @@ <response name="success" type="view" value="EditPaymentGatewayConfig"/> <response name="error" type="view" value="EditPaymentGatewayConfig"/> </request-map> + <request-map uri="UpdatePaymentGatewayConfigSagePay"> + <security https="true" auth="true"/> + <event type="service" invoke="updatePaymentGatewayConfigSagePay"/> + <response name="success" type="view" value="EditPaymentGatewayConfig"/> + <response name="error" type="view" value="EditPaymentGatewayConfig"/> + </request-map> <request-map uri="UpdatePaymentGatewayConfigAuthorizeNet"> <security https="true" auth="true"/> <event type="service" invoke="updatePaymentGatewayConfigAuthorizeNet"/> Modified: ofbiz/trunk/applications/accounting/widget/PaymentGatewayConfigForms.xml URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/accounting/widget/PaymentGatewayConfigForms.xml?rev=882103&r1=882102&r2=882103&view=diff ============================================================================== --- ofbiz/trunk/applications/accounting/widget/PaymentGatewayConfigForms.xml (original) +++ ofbiz/trunk/applications/accounting/widget/PaymentGatewayConfigForms.xml Thu Nov 19 11:01:29 2009 @@ -68,6 +68,56 @@ </field> </form> + <form name="EditPaymentGatewayConfigSagePay" type="single" target="UpdatePaymentGatewayConfigSagePay" default-map-name="paymentGatewaySagePay" header-row-style="header-row" default-table-style="basic-table"> + <auto-fields-entity entity-name="PaymentGatewaySagePay" default-field-type="edit"/> + <field name="paymentGatewayConfigId"><hidden/></field> + <field name="vendor" title="${uiLabelMap.AccountingSagePayVendor}"> + <text size="60" maxlength="60"/> + </field> + <field name="productionHost" title="${uiLabelMap.AccountingSagePayProductionHost}"> + <text size="100" maxlength="100"/> + </field> + <field name="testingHost" title="${uiLabelMap.AccountingSagePayTestingHost}"> + <text size="100" maxlength="100"/> + </field> + <field name="mode" title="${uiLabelMap.AccountingSagePayMode}"> + <drop-down> + <option key="TEST" description="${uiLabelMap.AccountingSagePayTest}"/> + <option key="PRODUCTION" description="${uiLabelMap.AccountingSagePayProduction}"/> + </drop-down> + </field> + <field name="protocolVersion" title="${uiLabelMap.AccountingSagePayProtocolVersion}"> + <text size="10" maxlength="10"/> + </field> + <field name="authenticationTransType" title="${uiLabelMap.AccountingSagePayAuthenticationTransType}"> + <text size="100" maxlength="100"/> + </field> + <field name="authenticationUrl" title="${uiLabelMap.AccountingSagePayAuthenticationUrl}"> + <text size="100" maxlength="100"/> + </field> + <field name="authoriseTransType" title="${uiLabelMap.AccountingSagePayAuthorisationTransType}"> + <text size="100" maxlength="100"/> + </field> + <field name="authoriseUrl" title="${uiLabelMap.AccountingSagePayAuthorisationUrl}"> + <text size="100" maxlength="100"/> + </field> + <field name="releaseTransType" title="${uiLabelMap.AccountingSagePayReleaseTransType}"> + <text size="100" maxlength="100"/> + </field> + <field name="releaseUrl" title="${uiLabelMap.AccountingSagePayReleaseUrl}"> + <text size="100" maxlength="100"/> + </field> + <field name="voidUrl" title="${uiLabelMap.AccountingSagePayVoidUrl}"> + <text size="100" maxlength="100"/> + </field> + <field name="refundUrl" title="${uiLabelMap.AccountingSagePayRefundUrl}"> + <text size="100" maxlength="100"/> + </field> + <field name="submitButton" title="${uiLabelMap.CommonUpdate}" widget-style="smallSubmit"> + <submit button-type="button"/> + </field> + </form> + <form name="EditPaymentGatewayConfigAuthorizeNet" type="single" target="UpdatePaymentGatewayConfigAuthorizeNet" default-map-name="paymentGatewayAuthorizeNet" header-row-style="header-row" default-table-style="basic-table"> <auto-fields-entity entity-name="PaymentGatewayAuthorizeNet" default-field-type="edit"/> <field name="paymentGatewayConfigId"><hidden/></field> Modified: ofbiz/trunk/applications/accounting/widget/PaymentGatewayConfigScreens.xml URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/accounting/widget/PaymentGatewayConfigScreens.xml?rev=882103&r1=882102&r2=882103&view=diff ============================================================================== --- ofbiz/trunk/applications/accounting/widget/PaymentGatewayConfigScreens.xml (original) +++ ofbiz/trunk/applications/accounting/widget/PaymentGatewayConfigScreens.xml Thu Nov 19 11:01:29 2009 @@ -85,6 +85,9 @@ <set field="paymentGatewayConfigId" from-field="parameters.paymentGatewayConfigId"/> <entity-one entity-name="PaymentGatewayConfig" value-field="paymentGatewayConfig"/> + <entity-one entity-name="PaymentGatewaySagePay" value-field="paymentGatewaySagePay"> + <field-map field-name="paymentGatewayConfigId" from-field="parameters.paymentGatewayConfigId"/> + </entity-one> <entity-one entity-name="PaymentGatewayAuthorizeNet" value-field="paymentGatewayAuthorizeNet"> <field-map field-name="paymentGatewayConfigId" from-field="parameters.paymentGatewayConfigId"/> </entity-one> @@ -112,6 +115,27 @@ </screenlet> <section> <condition> + <not><if-empty field="paymentGatewaySagePay"/></not> + </condition> + <widgets> + <container style="screenlet"> + <container style="screenlet-title-bar"> + <container style="h3"> + <label text="${uiLabelMap.PageTitleUpdatePaymentGatewayConfigSagePay}"/> + </container> + </container> + <container style="screenlet-body"> + <section> + <widgets> + <include-form name="EditPaymentGatewayConfigSagePay" location="component://accounting/widget/PaymentGatewayConfigForms.xml"/> + </widgets> + </section> + </container> + </container> + </widgets> + </section> + <section> + <condition> <not><if-empty field="paymentGatewayAuthorizeNet"/></not> </condition> <widgets> Added: ofbiz/trunk/framework/base/lib/httpclient-4.0.jar URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/lib/httpclient-4.0.jar?rev=882103&view=auto ============================================================================== Binary file - no diff available. Propchange: ofbiz/trunk/framework/base/lib/httpclient-4.0.jar ------------------------------------------------------------------------------ svn:mime-type = application/octet-stream Added: ofbiz/trunk/framework/base/lib/httpcore-4.0.1.jar URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/lib/httpcore-4.0.1.jar?rev=882103&view=auto ============================================================================== Binary file - no diff available. Propchange: ofbiz/trunk/framework/base/lib/httpcore-4.0.1.jar ------------------------------------------------------------------------------ svn:mime-type = application/octet-stream Added: ofbiz/trunk/framework/base/lib/jcip-annotations-1.0.jar URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/lib/jcip-annotations-1.0.jar?rev=882103&view=auto ============================================================================== Binary file - no diff available. Propchange: ofbiz/trunk/framework/base/lib/jcip-annotations-1.0.jar ------------------------------------------------------------------------------ svn:mime-type = application/octet-stream |
Free forum by Nabble | Edit this page |