Search in sources :

Example 6 with PayPalException

use of com.paypal.sdk.exceptions.PayPalException in project ofbiz-framework by apache.

the class PayPalServices method sendNVPRequest.

private static NVPDecoder sendNVPRequest(GenericValue payPalConfig, NVPEncoder encoder) throws PayPalException {
    NVPCallerServices caller = new NVPCallerServices();
    try {
        APIProfile profile = ProfileFactory.createSignatureAPIProfile();
        profile.setAPIUsername(payPalConfig.getString("apiUserName"));
        profile.setAPIPassword(payPalConfig.getString("apiPassword"));
        profile.setSignature(payPalConfig.getString("apiSignature"));
        profile.setEnvironment(payPalConfig.getString("apiEnvironment"));
        caller.setAPIProfile(profile);
    } catch (PayPalException e) {
        Debug.logError(e.getMessage(), module);
    }
    String requestMessage = encoder.encode();
    String responseMessage = caller.call(requestMessage);
    NVPDecoder decoder = new NVPDecoder();
    decoder.decode(responseMessage);
    if (!"Success".equals(decoder.get("ACK"))) {
        Debug.logError("A response other than success was received from PayPal: " + responseMessage, module);
    }
    return decoder;
}
Also used : NVPCallerServices(com.paypal.sdk.services.NVPCallerServices) NVPDecoder(com.paypal.sdk.core.nvp.NVPDecoder) APIProfile(com.paypal.sdk.profiles.APIProfile) PayPalException(com.paypal.sdk.exceptions.PayPalException)

Example 7 with PayPalException

use of com.paypal.sdk.exceptions.PayPalException in project ofbiz-framework by apache.

the class PayPalServices method doRefund.

public static Map<String, Object> doRefund(DispatchContext dctx, Map<String, Object> context) {
    Locale locale = (Locale) context.get("locale");
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null);
    if (payPalConfig == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale));
    }
    GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
    GenericValue captureTrans = PaymentGatewayServices.getCaptureTransaction(orderPaymentPreference);
    BigDecimal refundAmount = (BigDecimal) context.get("refundAmount");
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "RefundTransaction");
    encoder.add("TRANSACTIONID", captureTrans.getString("referenceNum"));
    encoder.add("REFUNDTYPE", "Partial");
    encoder.add("CURRENCYCODE", captureTrans.getString("currencyUomId"));
    encoder.add("AMT", refundAmount.setScale(2, RoundingMode.HALF_UP).toPlainString());
    encoder.add("NOTE", "Order #" + orderPaymentPreference.getString("orderId"));
    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (decoder == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
        result.put("refundResult", false);
        result.put("refundRefNum", captureTrans.getString("referenceNum"));
        result.put("refundAmount", BigDecimal.ZERO);
        if (errors.size() == 1) {
            Map.Entry<String, String> error = errors.entrySet().iterator().next();
            result.put("refundCode", error.getKey());
            result.put("refundMessage", error.getValue());
        } else {
            result.put("refundMessage", "Multiple errors occurred, please refer to the gateway response messages");
            result.put("internalRespMsgs", errors);
        }
    } else {
        result.put("refundResult", true);
        result.put("refundAmount", new BigDecimal(decoder.get("GROSSREFUNDAMT")));
        result.put("refundRefNum", decoder.get("REFUNDTRANSACTIONID"));
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) NVPEncoder(com.paypal.sdk.core.nvp.NVPEncoder) NVPDecoder(com.paypal.sdk.core.nvp.NVPDecoder) PayPalException(com.paypal.sdk.exceptions.PayPalException) Map(java.util.Map) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) BigDecimal(java.math.BigDecimal)

Example 8 with PayPalException

use of com.paypal.sdk.exceptions.PayPalException in project ofbiz-framework by apache.

the class PayPalServices method payPalCheckoutUpdate.

public static Map<String, Object> payPalCheckoutUpdate(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    HttpServletResponse response = (HttpServletResponse) context.get("response");
    Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
    String token = (String) paramMap.get("TOKEN");
    WeakReference<ShoppingCart> weakCart = tokenCartMap.get(new TokenWrapper(token));
    ShoppingCart cart = null;
    if (weakCart != null) {
        cart = weakCart.get();
    }
    if (cart == null) {
        Debug.logError("Could locate the ShoppingCart for token " + token, module);
        return ServiceUtil.returnSuccess();
    }
    // Since most if not all of the shipping estimate codes requires a persisted contactMechId we'll create one and
    // then delete once we're done, now is not the time to worry about updating everything
    String contactMechId = null;
    Map<String, Object> inMap = new HashMap<String, Object>();
    inMap.put("address1", paramMap.get("SHIPTOSTREET"));
    inMap.put("address2", paramMap.get("SHIPTOSTREET2"));
    inMap.put("city", paramMap.get("SHIPTOCITY"));
    String countryGeoCode = (String) paramMap.get("SHIPTOCOUNTRY");
    String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(countryGeoCode, delegator);
    if (countryGeoId == null) {
        return ServiceUtil.returnSuccess();
    }
    inMap.put("countryGeoId", countryGeoId);
    inMap.put("stateProvinceGeoId", parseStateProvinceGeoId((String) paramMap.get("SHIPTOSTATE"), countryGeoId, delegator));
    inMap.put("postalCode", paramMap.get("SHIPTOZIP"));
    try {
        GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").cache().queryOne();
        inMap.put("userLogin", userLogin);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    boolean beganTransaction = false;
    Transaction parentTransaction = null;
    try {
        parentTransaction = TransactionUtil.suspend();
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
        Debug.logError(e1, module);
    }
    try {
        Map<String, Object> outMap = dispatcher.runSync("createPostalAddress", inMap);
        contactMechId = (String) outMap.get("contactMechId");
    } catch (GenericServiceException e) {
        Debug.logError(e.getMessage(), module);
        return ServiceUtil.returnSuccess();
    }
    try {
        TransactionUtil.commit(beganTransaction);
        if (parentTransaction != null)
            TransactionUtil.resume(parentTransaction);
    } catch (GenericTransactionException e) {
        Debug.logError(e, module);
    }
    // clone the cart so we can modify it temporarily
    CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart);
    String oldShipAddress = cart.getShippingContactMechId();
    coh.setCheckOutShippingAddress(contactMechId);
    ShippingEstimateWrapper estWrapper = new ShippingEstimateWrapper(dispatcher, cart, 0);
    int line = 0;
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "CallbackResponse");
    for (GenericValue shipMethod : estWrapper.getShippingMethods()) {
        BigDecimal estimate = estWrapper.getShippingEstimate(shipMethod);
        // Check that we have a valid estimate (allowing zero value estimates for now)
        if (estimate == null || estimate.compareTo(BigDecimal.ZERO) < 0) {
            continue;
        }
        cart.setAllShipmentMethodTypeId(shipMethod.getString("shipmentMethodTypeId"));
        cart.setAllCarrierPartyId(shipMethod.getString("partyId"));
        try {
            coh.calcAndAddTax();
        } catch (GeneralException e) {
            Debug.logError(e, module);
            continue;
        }
        String estimateLabel = shipMethod.getString("partyId") + " - " + shipMethod.getString("description");
        encoder.add("L_SHIPINGPOPTIONLABEL" + line, estimateLabel);
        encoder.add("L_SHIPPINGOPTIONAMOUNT" + line, estimate.setScale(2, RoundingMode.HALF_UP).toPlainString());
        // Just make this first one default for now
        encoder.add("L_SHIPPINGOPTIONISDEFAULT" + line, line == 0 ? "true" : "false");
        encoder.add("L_TAXAMT" + line, cart.getTotalSalesTax().setScale(2, RoundingMode.HALF_UP).toPlainString());
        line++;
    }
    String responseMsg = null;
    try {
        responseMsg = encoder.encode();
    } catch (PayPalException e) {
        Debug.logError(e, module);
    }
    if (responseMsg != null) {
        try {
            response.setContentLength(responseMsg.getBytes("UTF-8").length);
        } catch (UnsupportedEncodingException e) {
            Debug.logError(e, module);
        }
        try (Writer writer = response.getWriter()) {
            writer.write(responseMsg);
        } catch (IOException e) {
            Debug.logError(e, module);
        }
    }
    // Remove the temporary ship address
    try {
        GenericValue postalAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", contactMechId).queryOne();
        postalAddress.remove();
        GenericValue contactMech = EntityQuery.use(delegator).from("ContactMech").where("contactMechId", contactMechId).queryOne();
        contactMech.remove();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    coh.setCheckOutShippingAddress(oldShipAddress);
    return ServiceUtil.returnSuccess();
}
Also used : LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) NVPEncoder(com.paypal.sdk.core.nvp.NVPEncoder) GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) HttpServletResponse(javax.servlet.http.HttpServletResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) PayPalException(com.paypal.sdk.exceptions.PayPalException) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) Transaction(javax.transaction.Transaction) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ShippingEstimateWrapper(org.apache.ofbiz.order.shoppingcart.shipping.ShippingEstimateWrapper) Writer(java.io.Writer)

Example 9 with PayPalException

use of com.paypal.sdk.exceptions.PayPalException in project ofbiz-framework by apache.

the class PayPalServices method doAuthorization.

public static Map<String, Object> doAuthorization(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    String orderId = (String) context.get("orderId");
    BigDecimal processAmount = (BigDecimal) context.get("processAmount");
    GenericValue payPalPaymentMethod = (GenericValue) context.get("payPalPaymentMethod");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE);
    Locale locale = (Locale) context.get("locale");
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoAuthorization");
    encoder.add("TRANSACTIONID", payPalPaymentMethod.getString("transactionId"));
    encoder.add("AMT", processAmount.setScale(2, RoundingMode.HALF_UP).toPlainString());
    encoder.add("TRANSACTIONENTITY", "Order");
    String currency = (String) context.get("currency");
    if (currency == null) {
        currency = orh.getCurrency();
    }
    encoder.add("CURRENCYCODE", currency);
    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (decoder == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
        result.put("authResult", false);
        result.put("authRefNum", "N/A");
        result.put("processAmount", BigDecimal.ZERO);
        if (errors.size() == 1) {
            Map.Entry<String, String> error = errors.entrySet().iterator().next();
            result.put("authCode", error.getKey());
            result.put("authMessage", error.getValue());
        } else {
            result.put("authMessage", "Multiple errors occurred, please refer to the gateway response messages");
            result.put("internalRespMsgs", errors);
        }
    } else {
        result.put("authResult", true);
        result.put("processAmount", new BigDecimal(decoder.get("AMT")));
        result.put("authRefNum", decoder.get("TRANSACTIONID"));
    }
    // TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what should be checked for this type of transaction
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) PayPalException(com.paypal.sdk.exceptions.PayPalException) BigDecimal(java.math.BigDecimal) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) NVPEncoder(com.paypal.sdk.core.nvp.NVPEncoder) Delegator(org.apache.ofbiz.entity.Delegator) NVPDecoder(com.paypal.sdk.core.nvp.NVPDecoder) Map(java.util.Map) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap)

Aggregations

PayPalException (com.paypal.sdk.exceptions.PayPalException)9 NVPDecoder (com.paypal.sdk.core.nvp.NVPDecoder)8 NVPEncoder (com.paypal.sdk.core.nvp.NVPEncoder)8 GenericValue (org.apache.ofbiz.entity.GenericValue)8 HashMap (java.util.HashMap)7 Locale (java.util.Locale)7 WeakHashMap (java.util.WeakHashMap)7 BigDecimal (java.math.BigDecimal)6 Map (java.util.Map)5 Delegator (org.apache.ofbiz.entity.Delegator)4 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)4 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)3 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)3 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)3 GeneralException (org.apache.ofbiz.base.util.GeneralException)2 OrderReadHelper (org.apache.ofbiz.order.order.OrderReadHelper)2 CheckOutHelper (org.apache.ofbiz.order.shoppingcart.CheckOutHelper)2 APIProfile (com.paypal.sdk.profiles.APIProfile)1 NVPCallerServices (com.paypal.sdk.services.NVPCallerServices)1 IOException (java.io.IOException)1