diff --git a/merchantsample/pom.xml b/merchantsample/pom.xml index 10fe2ad..72f10df 100644 --- a/merchantsample/pom.xml +++ b/merchantsample/pom.xml @@ -23,6 +23,27 @@ permissionssdk 2.2.101 + + junit + junit + 4.11 + test + + + org.seleniumhq.selenium + selenium-java + 2.33.0 + + + org.seleniumhq.selenium + selenium-server + 2.33.0 + + + com.github.detro.ghostdriver + phantomjsdriver + 1.0.3 + diff --git a/merchantsample/src/main/java/com/sample/ipn/IPNListenerServlet.java b/merchantsample/src/main/java/com/sample/ipn/IPNListenerServlet.java index a48938f..040d2a1 100644 --- a/merchantsample/src/main/java/com/sample/ipn/IPNListenerServlet.java +++ b/merchantsample/src/main/java/com/sample/ipn/IPNListenerServlet.java @@ -10,7 +10,7 @@ import com.paypal.core.LoggingManager; import com.paypal.ipn.IPNMessage; -import com.sample.merchant.Configuration; +import com.sample.util.Configuration; public class IPNListenerServlet extends HttpServlet { diff --git a/merchantsample/src/main/java/com/sample/merchant/CheckoutServlet.java b/merchantsample/src/main/java/com/sample/merchant/CheckoutServlet.java index 8207ea5..abdcf7b 100644 --- a/merchantsample/src/main/java/com/sample/merchant/CheckoutServlet.java +++ b/merchantsample/src/main/java/com/sample/merchant/CheckoutServlet.java @@ -73,6 +73,7 @@ import com.paypal.exception.MissingCredentialException; import com.paypal.exception.SSLConfigurationException; import com.paypal.sdk.exceptions.OAuthException; +import com.sample.util.Configuration; /** * Servlet implementation class CheckoutServlet diff --git a/merchantsample/src/main/java/com/sample/merchant/DoDirectPaymentServlet.java b/merchantsample/src/main/java/com/sample/merchant/DoDirectPaymentServlet.java index 0989301..ba11ee6 100644 --- a/merchantsample/src/main/java/com/sample/merchant/DoDirectPaymentServlet.java +++ b/merchantsample/src/main/java/com/sample/merchant/DoDirectPaymentServlet.java @@ -38,6 +38,7 @@ import com.paypal.exception.MissingCredentialException; import com.paypal.exception.SSLConfigurationException; import com.paypal.sdk.exceptions.OAuthException; +import com.sample.util.Configuration; public class DoDirectPaymentServlet extends HttpServlet { diff --git a/merchantsample/src/main/java/com/sample/merchant/GenerateAccessTokenServlet.java b/merchantsample/src/main/java/com/sample/merchant/GenerateAccessTokenServlet.java index 296ae4c..89ad61c 100644 --- a/merchantsample/src/main/java/com/sample/merchant/GenerateAccessTokenServlet.java +++ b/merchantsample/src/main/java/com/sample/merchant/GenerateAccessTokenServlet.java @@ -21,6 +21,7 @@ import com.paypal.svcs.types.common.RequestEnvelope; import com.paypal.svcs.types.perm.GetAccessTokenRequest; import com.paypal.svcs.types.perm.GetAccessTokenResponse; +import com.sample.util.Configuration; public class GenerateAccessTokenServlet extends HttpServlet { private static final long serialVersionUID = 1L; diff --git a/merchantsample/src/main/java/com/sample/merchant/MassPayServlet.java b/merchantsample/src/main/java/com/sample/merchant/MassPayServlet.java index b2d431c..cf18b1d 100644 --- a/merchantsample/src/main/java/com/sample/merchant/MassPayServlet.java +++ b/merchantsample/src/main/java/com/sample/merchant/MassPayServlet.java @@ -31,6 +31,7 @@ import com.paypal.exception.MissingCredentialException; import com.paypal.exception.SSLConfigurationException; import com.paypal.sdk.exceptions.OAuthException; +import com.sample.util.Configuration; /** * Servlet implementation class MassPayServlet diff --git a/merchantsample/src/main/java/com/sample/merchant/OnboardingServlet.java b/merchantsample/src/main/java/com/sample/merchant/OnboardingServlet.java index fbaf33b..454730b 100644 --- a/merchantsample/src/main/java/com/sample/merchant/OnboardingServlet.java +++ b/merchantsample/src/main/java/com/sample/merchant/OnboardingServlet.java @@ -15,14 +15,6 @@ import org.xml.sax.SAXException; -import com.paypal.exception.ClientActionRequiredException; -import com.paypal.exception.HttpErrorException; -import com.paypal.exception.InvalidCredentialException; -import com.paypal.exception.InvalidResponseDataException; -import com.paypal.exception.MissingCredentialException; -import com.paypal.exception.SSLConfigurationException; -import com.paypal.sdk.exceptions.OAuthException; - import urn.ebay.api.PayPalAPI.EnterBoardingReq; import urn.ebay.api.PayPalAPI.EnterBoardingRequestType; import urn.ebay.api.PayPalAPI.EnterBoardingResponseType; @@ -46,6 +38,15 @@ import urn.ebay.apis.eBLBaseComponents.PercentageRevenueFromOnlineSalesType; import urn.ebay.apis.eBLBaseComponents.PersonNameType; +import com.paypal.exception.ClientActionRequiredException; +import com.paypal.exception.HttpErrorException; +import com.paypal.exception.InvalidCredentialException; +import com.paypal.exception.InvalidResponseDataException; +import com.paypal.exception.MissingCredentialException; +import com.paypal.exception.SSLConfigurationException; +import com.paypal.sdk.exceptions.OAuthException; +import com.sample.util.Configuration; + /** * Servlet implementation class OnboardingServlet */ diff --git a/merchantsample/src/main/java/com/sample/merchant/PermissionServlet.java b/merchantsample/src/main/java/com/sample/merchant/PermissionServlet.java index cb45bce..b91a55b 100644 --- a/merchantsample/src/main/java/com/sample/merchant/PermissionServlet.java +++ b/merchantsample/src/main/java/com/sample/merchant/PermissionServlet.java @@ -23,6 +23,7 @@ import com.paypal.svcs.types.common.RequestEnvelope; import com.paypal.svcs.types.perm.RequestPermissionsRequest; import com.paypal.svcs.types.perm.RequestPermissionsResponse; +import com.sample.util.Configuration; public class PermissionServlet extends HttpServlet { /** diff --git a/merchantsample/src/main/java/com/sample/merchant/PermissionsMassPayServlet.java b/merchantsample/src/main/java/com/sample/merchant/PermissionsMassPayServlet.java index 7fd8103..c7e0711 100644 --- a/merchantsample/src/main/java/com/sample/merchant/PermissionsMassPayServlet.java +++ b/merchantsample/src/main/java/com/sample/merchant/PermissionsMassPayServlet.java @@ -34,6 +34,7 @@ import com.paypal.exception.MissingCredentialException; import com.paypal.exception.SSLConfigurationException; import com.paypal.sdk.exceptions.OAuthException; +import com.sample.util.Configuration; /** * Servlet implementation class MassPayServlet diff --git a/merchantsample/src/main/java/com/sample/merchant/RecurringPaymentsServlet.java b/merchantsample/src/main/java/com/sample/merchant/RecurringPaymentsServlet.java index 6447ffb..7deaf68 100644 --- a/merchantsample/src/main/java/com/sample/merchant/RecurringPaymentsServlet.java +++ b/merchantsample/src/main/java/com/sample/merchant/RecurringPaymentsServlet.java @@ -80,6 +80,7 @@ import com.paypal.exception.MissingCredentialException; import com.paypal.exception.SSLConfigurationException; import com.paypal.sdk.exceptions.OAuthException; +import com.sample.util.Configuration; /** * Servlet implementation class RecurringPaymentsServlet diff --git a/merchantsample/src/main/java/com/sample/merchant/ReportingServlet.java b/merchantsample/src/main/java/com/sample/merchant/ReportingServlet.java index ba9da77..73797da 100644 --- a/merchantsample/src/main/java/com/sample/merchant/ReportingServlet.java +++ b/merchantsample/src/main/java/com/sample/merchant/ReportingServlet.java @@ -41,6 +41,7 @@ import com.paypal.exception.MissingCredentialException; import com.paypal.exception.SSLConfigurationException; import com.paypal.sdk.exceptions.OAuthException; +import com.sample.util.Configuration; public class ReportingServlet extends HttpServlet { private static final long serialVersionUID = 2212442342452L; diff --git a/merchantsample/src/main/java/com/sample/merchant/SettlementServlet.java b/merchantsample/src/main/java/com/sample/merchant/SettlementServlet.java index a6b8b86..a2e0c02 100644 --- a/merchantsample/src/main/java/com/sample/merchant/SettlementServlet.java +++ b/merchantsample/src/main/java/com/sample/merchant/SettlementServlet.java @@ -64,6 +64,7 @@ import com.paypal.exception.MissingCredentialException; import com.paypal.exception.SSLConfigurationException; import com.paypal.sdk.exceptions.OAuthException; +import com.sample.util.Configuration; /** * Servlet implementation class CheckoutServlet diff --git a/merchantsample/src/main/java/com/sample/usecase/ParallelPaymentServlet.java b/merchantsample/src/main/java/com/sample/usecase/ParallelPaymentServlet.java new file mode 100644 index 0000000..2e0c6bc --- /dev/null +++ b/merchantsample/src/main/java/com/sample/usecase/ParallelPaymentServlet.java @@ -0,0 +1,303 @@ +package com.sample.usecase; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import urn.ebay.api.PayPalAPI.DoExpressCheckoutPaymentReq; +import urn.ebay.api.PayPalAPI.DoExpressCheckoutPaymentRequestType; +import urn.ebay.api.PayPalAPI.DoExpressCheckoutPaymentResponseType; +import urn.ebay.api.PayPalAPI.PayPalAPIInterfaceServiceService; +import urn.ebay.api.PayPalAPI.SetExpressCheckoutReq; +import urn.ebay.api.PayPalAPI.SetExpressCheckoutRequestType; +import urn.ebay.api.PayPalAPI.SetExpressCheckoutResponseType; +import urn.ebay.apis.CoreComponentTypes.BasicAmountType; +import urn.ebay.apis.eBLBaseComponents.CurrencyCodeType; +import urn.ebay.apis.eBLBaseComponents.DoExpressCheckoutPaymentRequestDetailsType; +import urn.ebay.apis.eBLBaseComponents.PaymentActionCodeType; +import urn.ebay.apis.eBLBaseComponents.PaymentDetailsType; +import urn.ebay.apis.eBLBaseComponents.PaymentInfoType; +import urn.ebay.apis.eBLBaseComponents.SellerDetailsType; +import urn.ebay.apis.eBLBaseComponents.SetExpressCheckoutRequestDetailsType; + +import com.sample.util.Configuration; + +public class ParallelPaymentServlet extends HttpServlet { + + private static final long serialVersionUID = 1239098098123L; + + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + + + if(request.getRequestURI().contains("SetExpressCheckoutForParallelPayment")){ + getServletConfig().getServletContext().getRequestDispatcher("/usecase_jsp/SetExpressCheckoutForParallelPayment.jsp") + .forward(request, response); + }else if(request.getRequestURI().contains("DoExpressCheckoutForParallelPayment")){ + getServletConfig().getServletContext().getRequestDispatcher("/usecase_jsp/DoExpressCheckoutForParallelPayment.jsp") + .forward(request, response); + } + } + + protected void doPost(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + + HttpSession session = request.getSession(); + session.setAttribute("url", request.getRequestURI()); + response.setContentType("text/html"); + + // Configuration map containing signature credentials and other required + // configuration. + // For a full list of configuration parameters refer at + // [https://github.com/paypal/merchant-sdk-java/wiki/SDK-Configuration-Parameters] + Map configurationMap = Configuration + .getSignatureConfig(); + + // Creating service wrapper object to make an API call by loading + // configuration map. + PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService( + configurationMap); + + // # SetExpressCheckout API + // The SetExpressCheckout API operation initiates an Express Checkout + // transaction. + // This sample code uses Merchant Java SDK to make API call. You can + // download the SDKs + // [here](https://github.com/paypal/sdk-packages/tree/gh-pages/merchant-sdk/java) + if (request.getRequestURI().contains("SetExpressCheckoutForParallelPayment")) { // *************** SetExpressCheckout for parallel payment ************************ + SetExpressCheckoutRequestType setExpressCheckoutReq = new SetExpressCheckoutRequestType(); + SetExpressCheckoutRequestDetailsType details = new SetExpressCheckoutRequestDetailsType(); + + StringBuffer url = new StringBuffer(); + url.append("http://"); + url.append(request.getServerName()); + url.append(":"); + url.append(request.getServerPort()); + url.append(request.getContextPath()); + + String returnURL = url.toString() + "/DoExpressCheckoutForParallelPayment"; + String cancelURL = url.toString() + "/SetExpressCheckoutForParallelPayment"; + + /* + * (Required) URL to which the buyer's browser is returned after + * choosing to pay with PayPal. For digital goods, you must add + * JavaScript to this page to close the in-context experience. Note: + * PayPal recommends that the value be the final review page on + * which the buyer confirms the order and payment or billing + * agreement. Character length and limitations: 2048 single-byte + * characters + */ + details.setReturnURL(returnURL + "?currencyCodeType=" + + request.getParameter("currencyCode")); + + details.setCancelURL(cancelURL); + /* + * (Optional) Email address of the buyer as entered during checkout. + * PayPal uses this value to pre-fill the PayPal membership sign-up + * portion on the PayPal pages. Character length and limitations: + * 127 single-byte alphanumeric characters + */ + details.setBuyerEmail(request.getParameter("buyerEmail")); + + SellerDetailsType seller_1 = new SellerDetailsType(); + seller_1.setPayPalAccountID(request.getParameter("receiverEmail_0")); + PaymentDetailsType paymentDetails_1 = new PaymentDetailsType(); + paymentDetails_1.setSellerDetails(seller_1); + paymentDetails_1.setPaymentRequestID(request + .getParameter("requestId_0")); + BasicAmountType orderTotal_1 = new BasicAmountType(); + orderTotal_1.setCurrencyID(CurrencyCodeType.fromValue(request + .getParameter("currencyCode"))); + orderTotal_1.setValue(request.getParameter("orderTotal")); + paymentDetails_1.setOrderTotal(orderTotal_1); + paymentDetails_1.setPaymentAction(PaymentActionCodeType + .fromValue(request.getParameter("paymentAction"))); + + SellerDetailsType seller_2 = new SellerDetailsType(); + seller_2.setPayPalAccountID(request.getParameter("receiverEmail_1")); + PaymentDetailsType paymentDetails_2 = new PaymentDetailsType(); + paymentDetails_2.setSellerDetails(seller_2); + paymentDetails_2.setPaymentRequestID(request + .getParameter("requestId_1")); + BasicAmountType orderTotal_2 = new BasicAmountType(); + orderTotal_2.setCurrencyID(CurrencyCodeType.fromValue(request + .getParameter("currencyCode"))); + orderTotal_2.setValue(request.getParameter("orderTotal")); + paymentDetails_2.setOrderTotal(orderTotal_2); + paymentDetails_2.setPaymentAction(PaymentActionCodeType + .fromValue(request.getParameter("paymentAction"))); + + List payDetails = new ArrayList(); + payDetails.add(paymentDetails_1); + payDetails.add(paymentDetails_2); + + details.setPaymentDetails(payDetails); + + setExpressCheckoutReq.setSetExpressCheckoutRequestDetails(details); + + SetExpressCheckoutReq expressCheckoutReq = new SetExpressCheckoutReq(); + expressCheckoutReq + .setSetExpressCheckoutRequest(setExpressCheckoutReq); + SetExpressCheckoutResponseType setExpressCheckoutResponse = null; + + try { + setExpressCheckoutResponse = service + .setExpressCheckout(expressCheckoutReq); + } catch (Exception e) { + e.printStackTrace(); + } + + if (setExpressCheckoutResponse != null) { + session.setAttribute("lastReq", service.getLastRequest()); + session.setAttribute("lastResp", service.getLastResponse()); + + if (setExpressCheckoutResponse.getAck().toString() + .equalsIgnoreCase("SUCCESS")) { + session.setAttribute("ecToken", + setExpressCheckoutResponse.getToken()); + response.sendRedirect("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + + setExpressCheckoutResponse.getToken()); + } else { + + session.setAttribute("Error", + setExpressCheckoutResponse.getErrors()); + response.sendRedirect(this.getServletContext() + .getContextPath() + "/Error.jsp"); + } + + } + }else if (request.getRequestURI().contains("DoExpressCheckoutForParallelPayment")) { // *************** DoExpressCheckout for parallel payment ************************ + + + DoExpressCheckoutPaymentRequestType doCheckoutPaymentRequestType = new DoExpressCheckoutPaymentRequestType(); + DoExpressCheckoutPaymentRequestDetailsType doEcdetails = new DoExpressCheckoutPaymentRequestDetailsType(); + /* + * A timestamped token by which you identify to PayPal that you + * are processing this payment with Express Checkout. The token + * expires after three hours. If you set the token in the + * SetExpressCheckout request, the value of the token in the + * response is identical to the value in the request. Character + * length and limitations: 20 single-byte characters + */ + doEcdetails.setToken(request.getParameter("token")); + /* + * Unique PayPal Customer Account identification number. + * Character length and limitations: 13 single-byte alphanumeric + * characters + */ + doEcdetails.setPayerID(request.getParameter("payerID")); + /* + * (Optional) How you want to obtain payment. If the transaction + * does not include a one-time purchase, this field is ignored. + * It is one of the following values: Sale – This is a final + * sale for which you are requesting payment (default). + * Authorization – This payment is a basic authorization subject + * to settlement with PayPal Authorization and Capture. Order – + * This payment is an order authorization subject to settlement + * with PayPal Authorization and Capture. Note: You cannot set + * this field to Sale in SetExpressCheckout request and then + * change this value to Authorization or Order in the + * DoExpressCheckoutPayment request. If you set the field to + * Authorization or Order in SetExpressCheckout, you may set the + * field to Sale. Character length and limitations: Up to 13 + * single-byte alphabetic characters This field is deprecated. + * Use PaymentAction in PaymentDetailsType instead. + */ + doEcdetails.setPaymentAction(PaymentActionCodeType.fromValue(request.getParameter("paymentAction"))); + + SellerDetailsType seller_1 = new SellerDetailsType(); + seller_1.setPayPalAccountID(request.getParameter("receiverEmail_0")); + PaymentDetailsType paymentDetails_1 = new PaymentDetailsType(); + paymentDetails_1.setSellerDetails(seller_1); + paymentDetails_1.setPaymentRequestID(request.getParameter("requestId_0")); + BasicAmountType orderTotal_1 = new BasicAmountType(); + orderTotal_1.setCurrencyID(CurrencyCodeType.fromValue(request.getParameter("currencyCode"))); + orderTotal_1.setValue(request.getParameter("orderTotal")); + paymentDetails_1.setOrderTotal(orderTotal_1); + paymentDetails_1.setPaymentAction(PaymentActionCodeType.fromValue(request.getParameter("paymentAction"))); + + SellerDetailsType seller_2 = new SellerDetailsType(); + seller_2.setPayPalAccountID(request.getParameter("receiverEmail_1")); + PaymentDetailsType paymentDetails_2 = new PaymentDetailsType(); + paymentDetails_2.setSellerDetails(seller_2); + paymentDetails_2.setPaymentRequestID(request.getParameter("requestId_1")); + BasicAmountType orderTotal_2 = new BasicAmountType(); + orderTotal_2.setCurrencyID(CurrencyCodeType.fromValue(request.getParameter("currencyCode"))); + orderTotal_2.setValue(request.getParameter("orderTotal")); + paymentDetails_2.setOrderTotal(orderTotal_2); + paymentDetails_2.setPaymentAction(PaymentActionCodeType.fromValue(request.getParameter("paymentAction"))); + + List payDetails = new ArrayList(); + payDetails.add(paymentDetails_1); + payDetails.add(paymentDetails_2); + + doEcdetails.setPaymentDetails(payDetails); + doCheckoutPaymentRequestType.setDoExpressCheckoutPaymentRequestDetails(doEcdetails); + DoExpressCheckoutPaymentReq doExpressCheckoutPaymentReq = new DoExpressCheckoutPaymentReq(); + doExpressCheckoutPaymentReq.setDoExpressCheckoutPaymentRequest(doCheckoutPaymentRequestType); + DoExpressCheckoutPaymentResponseType doCheckoutPaymentResponseType = null; + + try { + doCheckoutPaymentResponseType = service + .doExpressCheckoutPayment(doExpressCheckoutPaymentReq); + } catch (Exception e) { + e.printStackTrace(); + } + response.setContentType("text/html"); + + if (doCheckoutPaymentResponseType != null) { + //session.setAttribute("nextDescription"," \n Parallel Payment completed"); + session.setAttribute("lastReq", service.getLastRequest()); + session.setAttribute("lastResp", service.getLastResponse()); + if (doCheckoutPaymentResponseType.getAck().toString() + .equalsIgnoreCase("SUCCESS")) { + Map map = new LinkedHashMap(); + map.put("Ack", doCheckoutPaymentResponseType.getAck()); + Iterator iterator = doCheckoutPaymentResponseType + .getDoExpressCheckoutPaymentResponseDetails() + .getPaymentInfo().iterator(); + int index = 1; + /* + * Unique transaction ID of the payment. Note: If the + * PaymentAction of the request was Authorization or + * Order, this value is your AuthorizationID for use + * with the Authorization & Capture APIs. Character + * length and limitations: 19 single-byte characters + */ + while (iterator.hasNext()) { + PaymentInfoType result = (PaymentInfoType) iterator + .next(); + map.put("Transaction ID" + index, + result.getTransactionID()); + index++; + } + session.setAttribute( + "transactionId", + doCheckoutPaymentResponseType + .getDoExpressCheckoutPaymentResponseDetails() + .getPaymentInfo().get(0) + .getTransactionID()); + session.setAttribute("map", map); + response.sendRedirect(this.getServletContext() + .getContextPath() + "/Response.jsp"); + } else { + + session.setAttribute("Error", + doCheckoutPaymentResponseType.getErrors()); + response.sendRedirect(this.getServletContext() + .getContextPath() + "/Error.jsp"); + } + } + + } + } +} diff --git a/merchantsample/src/main/java/com/sample/usecase/PaymentCaptureServlet.java b/merchantsample/src/main/java/com/sample/usecase/PaymentCaptureServlet.java new file mode 100644 index 0000000..51e95fb --- /dev/null +++ b/merchantsample/src/main/java/com/sample/usecase/PaymentCaptureServlet.java @@ -0,0 +1,709 @@ +package com.sample.usecase; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import urn.ebay.api.PayPalAPI.DoAuthorizationReq; +import urn.ebay.api.PayPalAPI.DoAuthorizationRequestType; +import urn.ebay.api.PayPalAPI.DoAuthorizationResponseType; +import urn.ebay.api.PayPalAPI.DoCaptureReq; +import urn.ebay.api.PayPalAPI.DoCaptureRequestType; +import urn.ebay.api.PayPalAPI.DoCaptureResponseType; +import urn.ebay.api.PayPalAPI.DoExpressCheckoutPaymentReq; +import urn.ebay.api.PayPalAPI.DoExpressCheckoutPaymentRequestType; +import urn.ebay.api.PayPalAPI.DoExpressCheckoutPaymentResponseType; +import urn.ebay.api.PayPalAPI.PayPalAPIInterfaceServiceService; +import urn.ebay.api.PayPalAPI.SetExpressCheckoutReq; +import urn.ebay.api.PayPalAPI.SetExpressCheckoutRequestType; +import urn.ebay.api.PayPalAPI.SetExpressCheckoutResponseType; +import urn.ebay.apis.CoreComponentTypes.BasicAmountType; +import urn.ebay.apis.eBLBaseComponents.CompleteCodeType; +import urn.ebay.apis.eBLBaseComponents.CurrencyCodeType; +import urn.ebay.apis.eBLBaseComponents.DoExpressCheckoutPaymentRequestDetailsType; +import urn.ebay.apis.eBLBaseComponents.ItemCategoryType; +import urn.ebay.apis.eBLBaseComponents.PaymentActionCodeType; +import urn.ebay.apis.eBLBaseComponents.PaymentDetailsItemType; +import urn.ebay.apis.eBLBaseComponents.PaymentDetailsType; +import urn.ebay.apis.eBLBaseComponents.PaymentInfoType; +import urn.ebay.apis.eBLBaseComponents.SetExpressCheckoutRequestDetailsType; + +import com.sample.util.Configuration; + +public class PaymentCaptureServlet extends HttpServlet{ + + private static final long serialVersionUID = 34096986986994L; + + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + if(request.getRequestURI().contains("SetExpressCheckoutPaymentAuthorization")){ + getServletConfig().getServletContext() + .getRequestDispatcher("/usecase_jsp/SetExpressCheckoutPaymentAuthorization.jsp") + .forward(request, response); + }else if(request.getRequestURI().contains("SetExpressCheckoutPaymentOrder")){ + getServletConfig().getServletContext() + .getRequestDispatcher("/usecase_jsp/SetExpressCheckoutPaymentOrder.jsp") + .forward(request, response); + }else if(request.getRequestURI().contains("AuthorizedPaymentCapture")){ + getServletConfig().getServletContext() + .getRequestDispatcher("/usecase_jsp/PaymentCapture.jsp") + .forward(request, response); + }else if(request.getRequestURI().contains("OrderPaymentCapture")){ + getServletConfig().getServletContext() + .getRequestDispatcher("/usecase_jsp/PaymentCapture.jsp") + .forward(request, response); + }else if(request.getRequestURI().contains("DoAuthorizationForOrderPayment")){ + getServletConfig().getServletContext() + .getRequestDispatcher("/usecase_jsp/DoAuthorizationForOrderPayment.jsp") + .forward(request, response); + }else if(request.getRequestURI().contains("DoExpressCheckout")){ + getServletConfig().getServletContext() + .getRequestDispatcher("/usecase_jsp/DoExpressCheckout.jsp") + .forward(request, response); + } + } + + protected void doPost(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + HttpSession session = request.getSession(); + session.setAttribute("url", request.getRequestURI()); + response.setContentType("text/html"); + + // Configuration map containing signature credentials and other required configuration. + // For a full list of configuration parameters refer at + // [https://github.com/paypal/merchant-sdk-java/wiki/SDK-Configuration-Parameters] + Map configurationMap = Configuration.getSignatureConfig(); + + // Creating service wrapper object to make an API call by loading configuration map. + PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap); + + //# SetExpressCheckout API + // The SetExpressCheckout API operation initiates an Express Checkout + // transaction. + // This sample code uses Merchant Java SDK to make API call. You can + // download the SDKs [here](https://github.com/paypal/sdk-packages/tree/gh-pages/merchant-sdk/java) + + if(request.getRequestURI().contains("SetExpressCheckoutPaymentAuthorization") || request.getRequestURI().contains("SetExpressCheckoutPaymentOrder")){ + + SetExpressCheckoutRequestType setExpressCheckoutReq = new SetExpressCheckoutRequestType(); + SetExpressCheckoutRequestDetailsType details = new SetExpressCheckoutRequestDetailsType(); + + StringBuffer url = new StringBuffer(); + url.append("http://"); + url.append(request.getServerName()); + url.append(":"); + url.append(request.getServerPort()); + url.append(request.getContextPath()); + + String returnURL = url.toString() + "/DoExpressCheckout"; + String cancelURL = null; + if(request.getRequestURI().contains("SetExpressCheckoutPaymentAuthorization")){ + cancelURL = url.toString() + "/SetExpressCheckoutPaymentAuthorization"; + + }else if(request.getRequestURI().contains("SetExpressCheckoutPaymentOrder")){ + cancelURL = url.toString() + "/SetExpressCheckoutPaymentOrder"; + } + + + + /* + * (Required) URL to which the buyer's browser is returned after choosing + * to pay with PayPal. For digital goods, you must add JavaScript to this + * page to close the in-context experience. + Note: + PayPal recommends that the value be the final review page on which the buyer + confirms the order and payment or billing agreement. + Character length and limitations: 2048 single-byte characters + */ + details.setReturnURL(returnURL + "?currencyCodeType=" + + request.getParameter("currencyCode")); + + details.setCancelURL(cancelURL); + /* + * (Optional) Email address of the buyer as entered during checkout. + * PayPal uses this value to pre-fill the PayPal membership sign-up portion on the PayPal pages. + * Character length and limitations: 127 single-byte alphanumeric characters + */ + details.setBuyerEmail(request.getParameter("buyerMail")); + + double itemTotal = 0.00; + double orderTotal = 0.00; + // populate line item details + //Cost of item. This field is required when you pass a value for ItemCategory. + String amountItems = request.getParameter("itemAmount"); + /* + * Item quantity. This field is required when you pass a value for ItemCategory. + * For digital goods (ItemCategory=Digital), this field is required. + Character length and limitations: Any positive integer + This field is introduced in version 53.0. + */ + String qtyItems = request.getParameter("itemQuantity"); + /* + * Item name. This field is required when you pass a value for ItemCategory. + Character length and limitations: 127 single-byte characters + This field is introduced in version 53.0. + */ + String names = request.getParameter("itemName"); + + List lineItems = new ArrayList(); + + PaymentDetailsItemType item = new PaymentDetailsItemType(); + BasicAmountType amt = new BasicAmountType(); + //PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables. + amt.setCurrencyID(CurrencyCodeType.fromValue(request.getParameter("currencyCode"))); + amt.setValue(amountItems); + item.setQuantity(new Integer(qtyItems)); + item.setName(names); + item.setAmount(amt); + /* + * Indicates whether an item is digital or physical. For digital goods, this field is required and must be set to Digital. It is one of the following values: + 1.Digital + 2.Physical + This field is available since version 65.1. + */ + item.setItemCategory(ItemCategoryType.fromValue(request.getParameter("itemCategory"))); + /* + * (Optional) Item description. + Character length and limitations: 127 single-byte characters + This field is introduced in version 53.0. + */ + item.setDescription(request.getParameter("itemDescription")); + lineItems.add(item); + /* + * (Optional) Item sales tax. + Note: You must set the currencyID attribute to one of + the 3-character currency codes for any of the supported PayPal currencies. + Character length and limitations: Value is a positive number which cannot exceed $10,000 USD in any currency. + It includes no currency symbol. It must have 2 decimal places, the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,). + */ + if (request.getParameter("salesTax") != "") { + item.setTax(new BasicAmountType(CurrencyCodeType + .fromValue(request.getParameter("currencyCode")), + request.getParameter("salesTax"))); + } + + itemTotal += Double.parseDouble(qtyItems) * Double.parseDouble(amountItems); + orderTotal += itemTotal; + + List payDetails = new ArrayList(); + PaymentDetailsType paydtl = new PaymentDetailsType(); + /* + * How you want to obtain payment. When implementing parallel payments, + * this field is required and must be set to Order. + * When implementing digital goods, this field is required and must be set to Sale. + * If the transaction does not include a one-time purchase, this field is ignored. + * It is one of the following values: + + Sale – This is a final sale for which you are requesting payment (default). + Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture. + Order – This payment is an order authorization subject to settlement with PayPal Authorization and Capture. + */ + paydtl.setPaymentAction(PaymentActionCodeType.fromValue(request.getParameter("paymentAction"))); + /* + * (Optional) Total shipping costs for this order. + Note: + You must set the currencyID attribute to one of the 3-character currency codes + for any of the supported PayPal currencies. + Character length and limitations: + Value is a positive number which cannot exceed $10,000 USD in any currency. + It includes no currency symbol. + It must have 2 decimal places, the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,) + */ + if (request.getParameter("shippingTotal") != "") { + BasicAmountType shippingTotal = new BasicAmountType(); + shippingTotal.setValue(request + .getParameter("shippingTotal")); + shippingTotal.setCurrencyID(CurrencyCodeType + .fromValue(request.getParameter("currencyCode"))); + orderTotal += Double.parseDouble(request + .getParameter("shippingTotal")); + paydtl.setShippingTotal(shippingTotal); + } + + /* + * (Optional) Total shipping insurance costs for this order. + * The value must be a non-negative currency amount or null if you offer insurance options. + Note: + You must set the currencyID attribute to one of the 3-character currency + codes for any of the supported PayPal currencies. + Character length and limitations: + Value is a positive number which cannot exceed $10,000 USD in any currency. + It includes no currency symbol. It must have 2 decimal places, + the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,). + InsuranceTotal is available since version 53.0. + */ + if (request.getParameter("insuranceTotal") != "") { + paydtl.setInsuranceTotal(new BasicAmountType( + CurrencyCodeType.fromValue(request + .getParameter("currencyCode")), request + .getParameter("insuranceTotal"))); + paydtl.setInsuranceOptionOffered("true"); + orderTotal += Double.parseDouble(request + .getParameter("insuranceTotal")); + } + /* + * (Optional) Total handling costs for this order. + Note: + You must set the currencyID attribute to one of the 3-character currency codes + for any of the supported PayPal currencies. + Character length and limitations: Value is a positive number which + cannot exceed $10,000 USD in any currency. + It includes no currency symbol. It must have 2 decimal places, + the decimal separator must be a period (.), and the optional + thousands separator must be a comma (,). + */ + if (request.getParameter("handlingTotal") != "") { + paydtl.setHandlingTotal(new BasicAmountType( + CurrencyCodeType.fromValue(request + .getParameter("currencyCode")), request + .getParameter("handlingTotal"))); + orderTotal += Double.parseDouble(request + .getParameter("handlingTotal")); + } + + /* + * (Optional) Sum of tax for all items in this order. + Note: + You must set the currencyID attribute to one of the 3-character currency codes + for any of the supported PayPal currencies. + Character length and limitations: Value is a positive number which + cannot exceed $10,000 USD in any currency. It includes no currency symbol. + It must have 2 decimal places, the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,). + */ + if (request.getParameter("taxTotal") != "") { + paydtl.setTaxTotal(new BasicAmountType(CurrencyCodeType + .fromValue(request.getParameter("currencyCode")), + request.getParameter("taxTotal"))); + orderTotal += Double.parseDouble(request + .getParameter("taxTotal")); + } + + /* + * (Optional) Description of items the buyer is purchasing. + Note: + The value you specify is available only if the transaction includes a purchase. + This field is ignored if you set up a billing agreement for a recurring payment + that is not immediately charged. + Character length and limitations: 127 single-byte alphanumeric characters + */ + if (request.getParameter("orderDescription") != "") { + paydtl.setOrderDescription(request.getParameter("orderDescription")); + } + + + BasicAmountType itemsTotal = new BasicAmountType(); + itemsTotal.setValue(Double.toString(itemTotal)); + //PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables. + itemsTotal.setCurrencyID(CurrencyCodeType.fromValue(request.getParameter("currencyCode"))); + paydtl.setOrderTotal(new BasicAmountType(CurrencyCodeType.fromValue(request.getParameter("currencyCode")), + Double.toString(orderTotal))); + paydtl.setPaymentDetailsItem(lineItems); + + paydtl.setItemTotal(itemsTotal); + /* + * (Optional) Your URL for receiving Instant Payment Notification (IPN) + * about this transaction. If you do not specify this value in the request, + * the notification URL from your Merchant Profile is used, if one exists. + Important: + The notify URL applies only to DoExpressCheckoutPayment. + This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails. + Character length and limitations: 2,048 single-byte alphanumeric characters + */ + paydtl.setNotifyURL(request.getParameter("notifyURL")); + payDetails.add(paydtl); + details.setPaymentDetails(payDetails); + + setExpressCheckoutReq.setSetExpressCheckoutRequestDetails(details); + + SetExpressCheckoutReq expressCheckoutReq = new SetExpressCheckoutReq(); + expressCheckoutReq.setSetExpressCheckoutRequest(setExpressCheckoutReq); + SetExpressCheckoutResponseType setExpressCheckoutResponse = null; + try{ + setExpressCheckoutResponse = service.setExpressCheckout(expressCheckoutReq); + }catch(Exception e){ + e.printStackTrace(); + } + + if (setExpressCheckoutResponse != null) { + session.setAttribute("lastReq", service.getLastRequest()); + session.setAttribute("lastResp", service.getLastResponse()); + if (setExpressCheckoutResponse.getAck().toString().equalsIgnoreCase("SUCCESS")) { + response.sendRedirect("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="+setExpressCheckoutResponse.getToken()); + } else { + + session.setAttribute("Error", setExpressCheckoutResponse.getErrors()); + response.sendRedirect(this.getServletContext().getContextPath()+"/Error.jsp"); + } + } + + }else if(request.getRequestURI().contains("AuthorizedPaymentCapture") || request.getRequestURI().contains("OrderPaymentCapture")){ + + // ## DoCaptureReq + DoCaptureReq req = new DoCaptureReq(); + // `Amount` to capture which takes mandatory params: + // + // * `currencyCode` + // * `amount` + BasicAmountType amount = new BasicAmountType( + CurrencyCodeType.fromValue(request + .getParameter("currencyCode")), + request.getParameter("amt")); + + // `DoCaptureRequest` which takes mandatory params: + // + // * `Authorization ID` - Authorization identification number of the + // payment you want to capture. This is the transaction ID returned from + // DoExpressCheckoutPayment, DoDirectPayment, or Checkout. For + // point-of-sale transactions, this is the transaction ID returned by + // the Checkout call when the payment action is Authorization. + // * `amount` - Amount to capture + // * `CompleteCode` - Indicates whether or not this is your last capture. + // It is one of the following values: + // * Complete – This is the last capture you intend to make. + // * NotComplete – You intend to make additional captures. + // `Note: + // If Complete, any remaining amount of the original authorized + // transaction is automatically voided and all remaining open + // authorizations are voided.` + DoCaptureRequestType reqType = new DoCaptureRequestType( + request.getParameter("authID"), amount, + CompleteCodeType.fromValue(request + .getParameter("completeCodeType"))); + + req.setDoCaptureRequest(reqType); + DoCaptureResponseType resp = null; + try{ + resp = service.doCapture(req); + }catch(Exception e){ + e.printStackTrace(); + } + + if (resp != null) { + //session.setAttribute("nextDescription","
    The payment capture is completed.
"); + session.setAttribute("lastReq", service.getLastRequest()); + session.setAttribute("lastResp", service.getLastResponse()); + if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) { + Map map = new LinkedHashMap(); + map.put("Ack", resp.getAck()); + /* + * Authorization identification number you specified in the request. + Character length and limits: 19 single-byte characters maximum + */ + map.put("Authorization ID", resp + .getDoCaptureResponseDetails() + .getAuthorizationID()); + /* + * The final amount charged, including any shipping and taxes from your + * Merchant Profile. Shipping and taxes do not apply to point-of-sale + * transactions. + Character length and limitations: Value is a positive number which + cannot exceed $10,000 USD in any currency. It includes no currency symbol. + It must have 2 decimal places, the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,). Equivalent to 9 + characters maximum for USD. + */ + map.put("Gross Amount", resp + .getDoCaptureResponseDetails().getPaymentInfo() + .getGrossAmount().getValue() + + " " + + resp.getDoCaptureResponseDetails() + .getPaymentInfo().getGrossAmount() + .getCurrencyID()); + session.setAttribute("map", map); + response.sendRedirect(this.getServletContext().getContextPath()+"/Response.jsp"); + + } else { + + session.setAttribute("Error", resp.getErrors()); + response.sendRedirect(this.getServletContext().getContextPath()+"/Error.jsp"); + } + } + + }else if(request.getRequestURI().contains("DoExpressCheckout")){ // *************** DoExpressCheckout api call ************************ + + DoExpressCheckoutPaymentRequestType doCheckoutPaymentRequestType = new DoExpressCheckoutPaymentRequestType(); + DoExpressCheckoutPaymentRequestDetailsType details = new DoExpressCheckoutPaymentRequestDetailsType(); + /* + * A timestamped token by which you identify to PayPal that you are processing + * this payment with Express Checkout. The token expires after three hours. + * If you set the token in the SetExpressCheckout request, the value of the token + * in the response is identical to the value in the request. + Character length and limitations: 20 single-byte characters + */ + details.setToken(request.getParameter("token")); + /* + * Unique PayPal Customer Account identification number. + Character length and limitations: 13 single-byte alphanumeric characters + */ + details.setPayerID(request.getParameter("payerID")); + /* + * (Optional) How you want to obtain payment. If the transaction does not include + * a one-time purchase, this field is ignored. + * It is one of the following values: + Sale – This is a final sale for which you are requesting payment (default). + Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture. + Order – This payment is an order authorization subject to settlement with PayPal Authorization and Capture. + Note: + You cannot set this field to Sale in SetExpressCheckout request and then change + this value to Authorization or Order in the DoExpressCheckoutPayment request. + If you set the field to Authorization or Order in SetExpressCheckout, + you may set the field to Sale. + Character length and limitations: Up to 13 single-byte alphabetic characters + This field is deprecated. Use PaymentAction in PaymentDetailsType instead. + */ + details.setPaymentAction(PaymentActionCodeType.fromValue(request.getParameter("paymentAction"))); + double itemTotalAmt = 0.00; + double orderTotalAmt = 0.00; + String amt = request.getParameter("amt"); + String quantity = request.getParameter("itemQuantity"); + itemTotalAmt = Double.parseDouble(amt) * Double.parseDouble(quantity); + orderTotalAmt += itemTotalAmt; + + PaymentDetailsType paymentDetails = new PaymentDetailsType(); + BasicAmountType orderTotal = new BasicAmountType(); + orderTotal.setValue(Double.toString(orderTotalAmt)); + //PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables. + orderTotal.setCurrencyID(CurrencyCodeType.fromValue(request.getParameter("currencyCode"))); + /* + * (Required) The total cost of the transaction to the buyer. + * If shipping cost (not applicable to digital goods) and tax charges are known, + * include them in this value. If not, this value should be the current sub-total + * of the order. If the transaction includes one or more one-time purchases, this + * field must be equal to the sum of the purchases. Set this field to 0 if the + * transaction does not include a one-time purchase such as when you set up a + * billing agreement for a recurring payment that is not immediately charged. + * When the field is set to 0, purchase-specific fields are ignored. + * For digital goods, the following must be true: + total cost > 0 + total cost <= total cost passed in the call to SetExpressCheckout + Note: + You must set the currencyID attribute to one of the 3-character currency codes + for any of the supported PayPal currencies. + When multiple payments are passed in one transaction, all of the payments must + have the same currency code. + Character length and limitations: Value is a positive number which cannot + exceed $10,000 USD in any currency. It includes no currency symbol. + It must have 2 decimal places, the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,). + */ + paymentDetails.setOrderTotal(orderTotal); + + BasicAmountType itemTotal = new BasicAmountType(); + itemTotal.setValue(Double.toString(itemTotalAmt)); + //PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables. + itemTotal.setCurrencyID(CurrencyCodeType.fromValue(request.getParameter("currencyCode"))); + /* + * Sum of cost of all items in this order. For digital goods, this field is + * required. PayPal recommends that you pass the same value in the call to + * DoExpressCheckoutPayment that you passed in the call to SetExpressCheckout. + Note: + You must set the currencyID attribute to one of the 3-character currency + codes for any of the supported PayPal currencies. + Character length and limitations: Value is a positive number which cannot + exceed $10,000 USD in any currency. It includes no currency symbol. + It must have 2 decimal places, the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,). + */ + paymentDetails.setItemTotal(itemTotal); + + List paymentItems = new ArrayList(); + PaymentDetailsItemType paymentItem = new PaymentDetailsItemType(); + /* + * Item name. This field is required when you pass a value for ItemCategory. + Character length and limitations: 127 single-byte characters + This field is introduced in version 53.0. + */ + paymentItem.setName(request.getParameter("itemName")); + /* + * Item quantity. This field is required when you pass a value for ItemCategory. + * For digital goods (ItemCategory=Digital), this field is required. + Character length and limitations: Any positive integer + This field is introduced in version 53.0. + */ + paymentItem.setQuantity(Integer.parseInt(request.getParameter("itemQuantity"))); + BasicAmountType amount = new BasicAmountType(); + /* + * Cost of item. This field is required when you pass a value for ItemCategory. + Note: + You must set the currencyID attribute to one of the 3-character currency codes for + any of the supported PayPal currencies. + Character length and limitations: Value is a positive number which cannot + exceed $10,000 USD in any currency. It includes no currency symbol. + It must have 2 decimal places, the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,). + This field is introduced in version 53.0. + */ + amount.setValue(request.getParameter("amt")); + //PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables. + amount.setCurrencyID(CurrencyCodeType.fromValue(request.getParameter("currencyCode"))); + paymentItem.setAmount(amount); + paymentItems.add(paymentItem); + paymentDetails.setPaymentDetailsItem(paymentItems); + /* + * (Optional) Your URL for receiving Instant Payment Notification (IPN) + * about this transaction. If you do not specify this value in the request, + * the notification URL from your Merchant Profile is used, if one exists. + Important: + The notify URL applies only to DoExpressCheckoutPayment. + This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails. + Character length and limitations: 2,048 single-byte alphanumeric characters + */ + paymentDetails.setNotifyURL(request.getParameter("notifyURL")); + + List payDetailType = new ArrayList(); + payDetailType.add(paymentDetails); + /* + * When implementing parallel payments, you can create up to 10 sets of payment + * details type parameter fields, each representing one payment you are hosting + * on your marketplace. + */ + details.setPaymentDetails(payDetailType); + + doCheckoutPaymentRequestType + .setDoExpressCheckoutPaymentRequestDetails(details); + DoExpressCheckoutPaymentReq doExpressCheckoutPaymentReq = new DoExpressCheckoutPaymentReq(); + doExpressCheckoutPaymentReq.setDoExpressCheckoutPaymentRequest(doCheckoutPaymentRequestType); + DoExpressCheckoutPaymentResponseType doCheckoutPaymentResponseType = null; + try{ + doCheckoutPaymentResponseType = service.doExpressCheckoutPayment(doExpressCheckoutPaymentReq); + }catch(Exception e){ + e.printStackTrace(); + } + response.setContentType("text/html"); + + if (doCheckoutPaymentResponseType != null) { + session.setAttribute( + "nextDescription", + "
    If paymentAction is Authorization .you can capture the payment directly using DoCapture api" + + "
  • DoCapture
  • " + + "If paymentAction is Order .you need to call DoAuthorization api, before you can capture the payment using DoCapture api." + + "
  • DoAuthorization
"); + session.setAttribute("lastReq", service.getLastRequest()); + session.setAttribute("lastResp", service.getLastResponse()); + if (doCheckoutPaymentResponseType.getAck().toString() + .equalsIgnoreCase("SUCCESS")) { + Map map = new LinkedHashMap(); + map.put("Ack", doCheckoutPaymentResponseType.getAck()); + Iterator iterator = doCheckoutPaymentResponseType + .getDoExpressCheckoutPaymentResponseDetails() + .getPaymentInfo().iterator(); + int index = 1; + /* + * Unique transaction ID of the payment. + Note: + If the PaymentAction of the request was Authorization or Order, + this value is your AuthorizationID for use with the Authorization + & Capture APIs. + Character length and limitations: 19 single-byte characters + */ + while (iterator.hasNext()) { + PaymentInfoType result = (PaymentInfoType) iterator.next(); + map.put("Transaction ID" + index, + result.getTransactionID()); + index++; + } + session.setAttribute("transactionId", doCheckoutPaymentResponseType.getDoExpressCheckoutPaymentResponseDetails().getPaymentInfo().get(0).getTransactionID()); + session.setAttribute("map", map); + response.sendRedirect(this.getServletContext().getContextPath()+"/Response.jsp"); + } else { + + session.setAttribute("Error", + doCheckoutPaymentResponseType.getErrors()); + response.sendRedirect(this.getServletContext().getContextPath()+"/Error.jsp"); + } + } + + + }else if(request.getRequestURI().contains("DoAuthorizationForOrderPayment")){ + + // ## DoAuthorizationReq + DoAuthorizationReq req = new DoAuthorizationReq(); + + // `Amount` which takes mandatory params: + // + // * `currencyCode` + // * `amount + BasicAmountType amount = new BasicAmountType( + CurrencyCodeType.fromValue(request.getParameter("currencyCode")), + request.getParameter("amt")); + + // `DoAuthorizationRequest` which takes mandatory params: + // + // * `Transaction ID` - Value of the order's transaction identification + // number returned by PayPal. + // * `Amount` - Amount to authorize. + DoAuthorizationRequestType reqType = new DoAuthorizationRequestType( + request.getParameter("transID"), amount); + + req.setDoAuthorizationRequest(reqType); + DoAuthorizationResponseType resp = null; + try{ + resp = service.doAuthorization(req); + }catch(Exception e){ + e.printStackTrace(); + } + + session.setAttribute( + "nextDescription", + "
    The payment order is authorized , now you can capture the payment using DoCapture api" + + "
  • DoCapture
  • " ); + if (resp != null) { + session.setAttribute("lastReq", service.getLastRequest()); + session.setAttribute("lastResp", service.getLastResponse()); + if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) { + Map map = new LinkedHashMap(); + map.put("Ack", resp.getAck()); + /* + * Amount you specified in the request. + Character length and limitations: Value is a positive number which + cannot exceed $10,000 USD in any currency. It includes no currency symbol. + It must have 2 decimal places, the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,). + */ + map.put("Amount", resp.getAmount().getValue() + " " + + resp.getAmount().getCurrencyID()); + /* + * Status of the payment. It is one of the following values: + None – No status. + Canceled-Reversal – A reversal has been canceled. For example, when you win a dispute, PayPal returns the funds for the reversal to you. + Completed – The payment has been completed, and the funds have been added successfully to your account balance. + Denied – You denied the payment. This happens only if the payment was previously pending because of possible reasons described for the PendingReason element. + Expired – The authorization period for this payment has been reached. + Failed – The payment has failed. This happens only if the payment was made from the buyer's bank account. + In-Progress – The transaction has not terminated. For example, an authorization may be awaiting completion. + Partially-Refunded – The payment has been partially refunded. + Pending – The payment is pending. See the PendingReason field for more information. + Refunded – You refunded the payment. + Reversed– A payment was reversed due to a chargeback or other type of reversal. PayPal removes the funds from your account balance and returns them to the buyer. The ReasonCode element specifies the reason for the reversal. + Processed – A payment has been accepted. + Voided – An authorization for this transaction has been voided. + */ + map.put("Payment Status", resp.getAuthorizationInfo() + .getPaymentStatus()); + session.setAttribute("map", map); + response.sendRedirect(this.getServletContext().getContextPath()+"/Response.jsp"); + + } else { + + session.setAttribute("Error", resp.getErrors()); + response.sendRedirect(this.getServletContext().getContextPath()+"/Error.jsp"); + } + } + + } + } + +} diff --git a/merchantsample/src/main/java/com/sample/usecase/RecurringPaymentServlet.java b/merchantsample/src/main/java/com/sample/usecase/RecurringPaymentServlet.java new file mode 100644 index 0000000..0789715 --- /dev/null +++ b/merchantsample/src/main/java/com/sample/usecase/RecurringPaymentServlet.java @@ -0,0 +1,746 @@ +package com.sample.usecase; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import urn.ebay.api.PayPalAPI.CreateRecurringPaymentsProfileReq; +import urn.ebay.api.PayPalAPI.CreateRecurringPaymentsProfileRequestType; +import urn.ebay.api.PayPalAPI.CreateRecurringPaymentsProfileResponseType; +import urn.ebay.api.PayPalAPI.PayPalAPIInterfaceServiceService; +import urn.ebay.api.PayPalAPI.SetExpressCheckoutReq; +import urn.ebay.api.PayPalAPI.SetExpressCheckoutRequestType; +import urn.ebay.api.PayPalAPI.SetExpressCheckoutResponseType; +import urn.ebay.apis.CoreComponentTypes.BasicAmountType; +import urn.ebay.apis.eBLBaseComponents.BillingAgreementDetailsType; +import urn.ebay.apis.eBLBaseComponents.BillingCodeType; +import urn.ebay.apis.eBLBaseComponents.BillingPeriodDetailsType; +import urn.ebay.apis.eBLBaseComponents.BillingPeriodType; +import urn.ebay.apis.eBLBaseComponents.CreateRecurringPaymentsProfileRequestDetailsType; +import urn.ebay.apis.eBLBaseComponents.CreditCardDetailsType; +import urn.ebay.apis.eBLBaseComponents.CreditCardTypeType; +import urn.ebay.apis.eBLBaseComponents.CurrencyCodeType; +import urn.ebay.apis.eBLBaseComponents.ItemCategoryType; +import urn.ebay.apis.eBLBaseComponents.PayerInfoType; +import urn.ebay.apis.eBLBaseComponents.PaymentActionCodeType; +import urn.ebay.apis.eBLBaseComponents.PaymentDetailsItemType; +import urn.ebay.apis.eBLBaseComponents.PaymentDetailsType; +import urn.ebay.apis.eBLBaseComponents.RecurringPaymentsProfileDetailsType; +import urn.ebay.apis.eBLBaseComponents.ScheduleDetailsType; +import urn.ebay.apis.eBLBaseComponents.SetExpressCheckoutRequestDetailsType; + +import com.sample.util.Configuration; + +public class RecurringPaymentServlet extends HttpServlet { + private static final long serialVersionUID = 3409273409234L; + + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + + if (request.getRequestURI().contains("SetExpressCheckoutForRecurringPayments")) { + getServletConfig() + .getServletContext() + .getRequestDispatcher("/usecase_jsp/SetExpressCheckoutForRecurringPayments.jsp") + .forward(request, response); + } else if (request.getRequestURI().contains("RecurringPaymentsUsingPayPal")) { + getServletConfig() + .getServletContext() + .getRequestDispatcher( + "/usecase_jsp/RecurringPaymentsUsingPayPal.jsp") + .forward(request, response); + } else if (request.getRequestURI().contains("RecurringPaymentsUsingCreditCard")) { + getServletConfig() + .getServletContext() + .getRequestDispatcher( + "/usecase_jsp/RecurringPaymentsUsingCreditCard.jsp") + .forward(request, response); + } + } + + protected void doPost(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + CurrencyCodeType currency = CurrencyCodeType.fromValue("USD"); + HttpSession session = request.getSession(); + session.setAttribute("url", request.getRequestURI()); + response.setContentType("text/html"); + + // Configuration map containing signature credentials and other required configuration. + // For a full list of configuration parameters refer at + // [https://github.com/paypal/merchant-sdk-java/wiki/SDK-Configuration-Parameters] + Map configurationMap = Configuration.getSignatureConfig(); + + // Creating service wrapper object to make an API call by loading configuration map. + PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap); + + //# SetExpressCheckout API + // The SetExpressCheckout API operation initiates an Express Checkout + // transaction. + // This sample code uses Merchant Java SDK to make API call. You can + // download the SDKs [here](https://github.com/paypal/sdk-packages/tree/gh-pages/merchant-sdk/java) + + if (request.getRequestURI().contains("SetExpressCheckoutForRecurringPayments")) { + + SetExpressCheckoutRequestType setExpressCheckoutReq = new SetExpressCheckoutRequestType(); + SetExpressCheckoutRequestDetailsType details = new SetExpressCheckoutRequestDetailsType(); + + StringBuffer url = new StringBuffer(); + url.append("http://"); + url.append(request.getServerName()); + url.append(":"); + url.append(request.getServerPort()); + url.append(request.getContextPath()); + + String returnURL = url.toString() + "/RecurringPaymentsUsingPayPal"; + String cancelURL = url.toString() + "/SetExpressCheckoutForRecurringPayments"; + + /* + * (Required) URL to which the buyer's browser is returned after choosing + * to pay with PayPal. For digital goods, you must add JavaScript to this + * page to close the in-context experience. + Note: + PayPal recommends that the value be the final review page on which the buyer + confirms the order and payment or billing agreement. + Character length and limitations: 2048 single-byte characters + */ + details.setReturnURL(returnURL + "?currencyCodeType="+ request.getParameter("currencyCode")); + + details.setCancelURL(cancelURL); + /* + * (Optional) Email address of the buyer as entered during checkout. + * PayPal uses this value to pre-fill the PayPal membership sign-up portion on the PayPal pages. + * Character length and limitations: 127 single-byte alphanumeric characters + */ + details.setBuyerEmail(request.getParameter("buyerMail")); + + double itemTotal = 0.00; + double orderTotal = 0.00; + // populate line item details + //Cost of item. This field is required when you pass a value for ItemCategory. + String amountItems = request.getParameter("itemAmount"); + /* + * Item quantity. This field is required when you pass a value for ItemCategory. + * For digital goods (ItemCategory=Digital), this field is required. + Character length and limitations: Any positive integer + This field is introduced in version 53.0. + */ + String qtyItems = request.getParameter("itemQuantity"); + /* + * Item name. This field is required when you pass a value for ItemCategory. + Character length and limitations: 127 single-byte characters + This field is introduced in version 53.0. + */ + String names = request.getParameter("itemName"); + + List lineItems = new ArrayList(); + + PaymentDetailsItemType item = new PaymentDetailsItemType(); + BasicAmountType amt = new BasicAmountType(); + //PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables. + amt.setCurrencyID(CurrencyCodeType.fromValue(request.getParameter("currencyCode"))); + amt.setValue(amountItems); + item.setQuantity(new Integer(qtyItems)); + item.setName(names); + item.setAmount(amt); + /* + * Indicates whether an item is digital or physical. For digital goods, this field is required and must be set to Digital. It is one of the following values: + 1.Digital + 2.Physical + This field is available since version 65.1. + */ + item.setItemCategory(ItemCategoryType.fromValue(request.getParameter("itemCategory"))); + /* + * (Optional) Item description. + Character length and limitations: 127 single-byte characters + This field is introduced in version 53.0. + */ + item.setDescription(request.getParameter("itemDescription")); + lineItems.add(item); + /* + * (Optional) Item sales tax. + Note: You must set the currencyID attribute to one of + the 3-character currency codes for any of the supported PayPal currencies. + Character length and limitations: Value is a positive number which cannot exceed $10,000 USD in any currency. + It includes no currency symbol. It must have 2 decimal places, the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,). + */ + if (request.getParameter("salesTax") != "") { + item.setTax(new BasicAmountType(CurrencyCodeType + .fromValue(request.getParameter("currencyCode")), + request.getParameter("salesTax"))); + } + + itemTotal += Double.parseDouble(qtyItems) * Double.parseDouble(amountItems); + orderTotal += itemTotal; + + List payDetails = new ArrayList(); + PaymentDetailsType paydtl = new PaymentDetailsType(); + /* + * How you want to obtain payment. When implementing parallel payments, + * this field is required and must be set to Order. + * When implementing digital goods, this field is required and must be set to Sale. + * If the transaction does not include a one-time purchase, this field is ignored. + * It is one of the following values: + + Sale – This is a final sale for which you are requesting payment (default). + Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture. + Order – This payment is an order authorization subject to settlement with PayPal Authorization and Capture. + */ + paydtl.setPaymentAction(PaymentActionCodeType.fromValue(request.getParameter("paymentAction"))); + /* + * (Optional) Total shipping costs for this order. + Note: + You must set the currencyID attribute to one of the 3-character currency codes + for any of the supported PayPal currencies. + Character length and limitations: + Value is a positive number which cannot exceed $10,000 USD in any currency. + It includes no currency symbol. + It must have 2 decimal places, the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,) + */ + if (request.getParameter("shippingTotal") != "") { + BasicAmountType shippingTotal = new BasicAmountType(); + shippingTotal.setValue(request + .getParameter("shippingTotal")); + shippingTotal.setCurrencyID(CurrencyCodeType + .fromValue(request.getParameter("currencyCode"))); + orderTotal += Double.parseDouble(request + .getParameter("shippingTotal")); + paydtl.setShippingTotal(shippingTotal); + } + + /* + * (Optional) Total shipping insurance costs for this order. + * The value must be a non-negative currency amount or null if you offer insurance options. + Note: + You must set the currencyID attribute to one of the 3-character currency + codes for any of the supported PayPal currencies. + Character length and limitations: + Value is a positive number which cannot exceed $10,000 USD in any currency. + It includes no currency symbol. It must have 2 decimal places, + the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,). + InsuranceTotal is available since version 53.0. + */ + if (request.getParameter("insuranceTotal") != "") { + paydtl.setInsuranceTotal(new BasicAmountType( + CurrencyCodeType.fromValue(request + .getParameter("currencyCode")), request + .getParameter("insuranceTotal"))); + paydtl.setInsuranceOptionOffered("true"); + orderTotal += Double.parseDouble(request + .getParameter("insuranceTotal")); + } + /* + * (Optional) Total handling costs for this order. + Note: + You must set the currencyID attribute to one of the 3-character currency codes + for any of the supported PayPal currencies. + Character length and limitations: Value is a positive number which + cannot exceed $10,000 USD in any currency. + It includes no currency symbol. It must have 2 decimal places, + the decimal separator must be a period (.), and the optional + thousands separator must be a comma (,). + */ + if (request.getParameter("handlingTotal") != "") { + paydtl.setHandlingTotal(new BasicAmountType( + CurrencyCodeType.fromValue(request + .getParameter("currencyCode")), request + .getParameter("handlingTotal"))); + orderTotal += Double.parseDouble(request + .getParameter("handlingTotal")); + } + + /* + * (Optional) Sum of tax for all items in this order. + Note: + You must set the currencyID attribute to one of the 3-character currency codes + for any of the supported PayPal currencies. + Character length and limitations: Value is a positive number which + cannot exceed $10,000 USD in any currency. It includes no currency symbol. + It must have 2 decimal places, the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,). + */ + if (request.getParameter("taxTotal") != "") { + paydtl.setTaxTotal(new BasicAmountType(CurrencyCodeType + .fromValue(request.getParameter("currencyCode")), + request.getParameter("taxTotal"))); + orderTotal += Double.parseDouble(request + .getParameter("taxTotal")); + } + + /* + * (Optional) Description of items the buyer is purchasing. + Note: + The value you specify is available only if the transaction includes a purchase. + This field is ignored if you set up a billing agreement for a recurring payment + that is not immediately charged. + Character length and limitations: 127 single-byte alphanumeric characters + */ + if (request.getParameter("orderDescription") != "") { + paydtl.setOrderDescription(request.getParameter("orderDescription")); + } + + + BasicAmountType itemsTotal = new BasicAmountType(); + itemsTotal.setValue(Double.toString(itemTotal)); + //PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables. + itemsTotal.setCurrencyID(CurrencyCodeType.fromValue(request.getParameter("currencyCode"))); + paydtl.setOrderTotal(new BasicAmountType(CurrencyCodeType.fromValue(request.getParameter("currencyCode")), + Double.toString(orderTotal))); + paydtl.setPaymentDetailsItem(lineItems); + + paydtl.setItemTotal(itemsTotal); + /* + * (Optional) Your URL for receiving Instant Payment Notification (IPN) + * about this transaction. If you do not specify this value in the request, + * the notification URL from your Merchant Profile is used, if one exists. + Important: + The notify URL applies only to DoExpressCheckoutPayment. + This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails. + Character length and limitations: 2,048 single-byte alphanumeric characters + */ + paydtl.setNotifyURL(request.getParameter("notifyURL")); + + payDetails.add(paydtl); + details.setPaymentDetails(payDetails); + + if (request.getParameter("billingAgreementText") != "") { + /* + * (Required) Type of billing agreement. For recurring payments, + * this field must be set to RecurringPayments. + * In this case, you can specify up to ten billing agreements. + * Other defined values are not valid. + Type of billing agreement for reference transactions. + You must have permission from PayPal to use this field. + This field must be set to one of the following values: + 1. MerchantInitiatedBilling - PayPal creates a billing agreement + for each transaction associated with buyer.You must specify + version 54.0 or higher to use this option. + 2. MerchantInitiatedBillingSingleAgreement - PayPal creates a + single billing agreement for all transactions associated with buyer. + Use this value unless you need per-transaction billing agreements. + You must specify version 58.0 or higher to use this option. + + */ + BillingAgreementDetailsType billingAgreement = new BillingAgreementDetailsType( + BillingCodeType.fromValue(request.getParameter("billingType"))); + /* + * Description of goods or services associated with the billing agreement. + * This field is required for each recurring payment billing agreement. + * PayPal recommends that the description contain a brief summary of + * the billing agreement terms and conditions. For example, + * buyer is billed at "9.99 per month for 2 years". + Character length and limitations: 127 single-byte alphanumeric characters + */ + billingAgreement.setBillingAgreementDescription(request.getParameter("billingAgreementText")); + List billList = new ArrayList(); + billList.add(billingAgreement); + details.setBillingAgreementDetails(billList); + } + + setExpressCheckoutReq.setSetExpressCheckoutRequestDetails(details); + SetExpressCheckoutReq expressCheckoutReq = new SetExpressCheckoutReq(); + expressCheckoutReq.setSetExpressCheckoutRequest(setExpressCheckoutReq); + + SetExpressCheckoutResponseType setExpressCheckoutResponse = null; + try{ + setExpressCheckoutResponse = service.setExpressCheckout(expressCheckoutReq); + }catch(Exception e){ + e.printStackTrace(); + } + + if (setExpressCheckoutResponse != null) { + session.setAttribute("lastReq", service.getLastRequest()); + session.setAttribute("lastResp", service.getLastResponse()); + if (setExpressCheckoutResponse.getAck().toString().equalsIgnoreCase("SUCCESS")) { + session.setAttribute("ecToken",setExpressCheckoutResponse.getToken()); + response.sendRedirect("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="+setExpressCheckoutResponse.getToken()); + } else { + session.setAttribute("Error",setExpressCheckoutResponse.getErrors()); + response.sendRedirect(this.getServletContext().getContextPath()+"/Error.jsp"); + } + } + + } + // ********** Creating Recurring Profile using PayPal ********* + else if (request.getRequestURI().contains("RecurringPaymentsUsingPayPal")) { + + CreateRecurringPaymentsProfileReq req = new CreateRecurringPaymentsProfileReq(); + CreateRecurringPaymentsProfileRequestType reqType = new CreateRecurringPaymentsProfileRequestType(); + /* + * (Required) The date when billing for this profile begins. + Note: + The profile may take up to 24 hours for activation. + Character length and limitations: Must be a valid date, in UTC/GMT format + */ + RecurringPaymentsProfileDetailsType profileDetails = new RecurringPaymentsProfileDetailsType( + request.getParameter("billingStartDate") + + "T00:00:00:000Z"); + + // Populate schedule details + ScheduleDetailsType scheduleDetails = new ScheduleDetailsType(); + /* + * (Required) Description of the recurring payment. + Note: + You must ensure that this field matches the corresponding billing agreement + description included in the SetExpressCheckout request. + Character length and limitations: 127 single-byte alphanumeric characters + */ + scheduleDetails.setDescription(request.getParameter("profileDescription")); + + if (request.getParameter("billingAmount") != "") { + /* + * (Required) Number of billing periods that make up one billing cycle. + The combination of billing frequency and billing period must be less than + or equal to one year. For example, if the billing cycle is Month, + the maximum value for billing frequency is 12. Similarly, + if the billing cycle is Week, the maximum value for billing frequency is 52. + Note: + If the billing period is SemiMonth, the billing frequency must be 1. + */ + int frequency = Integer.parseInt(request.getParameter("billingFrequency")); + /* + * (Required) Billing amount for each billing cycle during this payment period. + * This amount does not include shipping and tax amounts. + Note: + All amounts in the CreateRecurringPaymentsProfile request must have the same + currency. + Character length and limitations: Value is a positive number which cannot + exceed $10,000 USD in any currency. It includes no currency symbol. + It must have 2 decimal places, the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,). + */ + BasicAmountType paymentAmount = new BasicAmountType(currency, request.getParameter("billingAmount")); + /* + * (Required) Unit for billing during this subscription period. + * It is one of the following values: + [Day, Week, SemiMonth, Month, Year] + For SemiMonth, billing is done on the 1st and 15th of each month. + Note: + The combination of BillingPeriod and BillingFrequency cannot exceed one year. + */ + BillingPeriodType period = BillingPeriodType.fromValue(request.getParameter("billingPeriod")); + /* + * (Optional) Number of billing cycles for payment period. + For the regular payment period, if no value is specified or the value is 0, + the regular payment period continues until the profile is canceled or deactivated. + For the regular payment period, if the value is greater than 0, + the regular payment period will expire after the trial period is + finished and continue at the billing frequency for TotalBillingCycles cycles. + + */ + int numCycles = Integer.parseInt(request.getParameter("totalBillingCycles")); + + BillingPeriodDetailsType paymentPeriod = new BillingPeriodDetailsType( + period, frequency, paymentAmount); + paymentPeriod.setTotalBillingCycles(numCycles); + /* + * (Optional) Shipping amount for each billing cycle during this payment period. + Note: + All amounts in the request must have the same currency. + */ + if (request.getParameter("shippingAmount") != "") { + paymentPeriod.setShippingAmount(new BasicAmountType( + currency, request.getParameter("shippingAmount"))); + } + /* + * (Optional) Tax amount for each billing cycle during this payment period. + Note: + All amounts in the request must have the same currency. + Character length and limitations: + Value is a positive number which cannot exceed $10,000 USD in any currency. + It includes no currency symbol. It must have 2 decimal places, + the decimal separator must be a period (.), and the optional + thousands separator must be a comma (,). + */ + + if (request.getParameter("taxAmount") != "") { + paymentPeriod.setTaxAmount(new BasicAmountType( + currency, request.getParameter("taxAmount"))); + } + scheduleDetails.setPaymentPeriod(paymentPeriod); + } + + CreateRecurringPaymentsProfileRequestDetailsType reqDetails = new CreateRecurringPaymentsProfileRequestDetailsType( + profileDetails, scheduleDetails); + /* + * A timestamped token, the value of which was returned in the response to the + * first call to SetExpressCheckout. You can also use the token returned in the + * SetCustomerBillingAgreement response.Each CreateRecurringPaymentsProfile request creates + * a single recurring payments profile. + Note: + Tokens expire after approximately 3 hours. + */ + reqDetails.setToken(request.getParameter("token")); + + reqType.setCreateRecurringPaymentsProfileRequestDetails(reqDetails); + req.setCreateRecurringPaymentsProfileRequest(reqType); + CreateRecurringPaymentsProfileResponseType resp = null; + try{ + resp = service.createRecurringPaymentsProfile(req); + }catch(Exception e){ + e.printStackTrace(); + } + + if (resp != null) { + session.setAttribute("lastReq", service.getLastRequest()); + session.setAttribute("lastResp", service.getLastResponse()); + if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) { + Map map = new LinkedHashMap(); + map.put("Ack", resp.getAck()); + /* + * (Required) Recurring payments profile ID returned in the + * CreateRecurringPaymentsProfile response. + Note: The profile must have a status of either Active or Suspended. + Character length and limitations: 14 single-byte alphanumeric characters. + 19 character profile IDs are supported for compatibility with previous versions + of the PayPal API. + */ + map.put("Profile ID", + resp.getCreateRecurringPaymentsProfileResponseDetails() + .getProfileID()); + map.put("Transaction ID", + resp.getCreateRecurringPaymentsProfileResponseDetails() + .getTransactionID()); + /* + * Status of the recurring payment profile. + ActiveProfile – The recurring payment profile has been successfully created and activated for scheduled payments according the billing instructions from the recurring payments profile. + PendingProfile – The system is in the process of creating the recurring payment profile. Please check your IPN messages for an update. + */ + map.put("Profile Status", + resp.getCreateRecurringPaymentsProfileResponseDetails() + .getProfileStatus()); + session.setAttribute("map", map); + response.sendRedirect(this.getServletContext().getContextPath()+"/Response.jsp"); + } else { + session.setAttribute("Error", resp.getErrors()); + response.sendRedirect(this.getServletContext().getContextPath()+"/Error.jsp"); + } + } + + + } + // ************ Creating recurring profile using credit card **************** + else if(request.getRequestURI().contains("RecurringPaymentsUsingCreditCard")){ + + + CreateRecurringPaymentsProfileReq req = new CreateRecurringPaymentsProfileReq(); + CreateRecurringPaymentsProfileRequestType reqType = new CreateRecurringPaymentsProfileRequestType(); + /* + * (Required) The date when billing for this profile begins. + Note: + The profile may take up to 24 hours for activation. + Character length and limitations: Must be a valid date, in UTC/GMT format + */ + RecurringPaymentsProfileDetailsType profileDetails = new RecurringPaymentsProfileDetailsType( + request.getParameter("billingStartDate") + + "T00:00:00:000Z"); + // Populate schedule details + ScheduleDetailsType scheduleDetails = new ScheduleDetailsType(); + /* + * (Required) Description of the recurring payment. + Note: + You must ensure that this field matches the corresponding billing agreement + description included in the SetExpressCheckout request. + Character length and limitations: 127 single-byte alphanumeric characters + */ + scheduleDetails.setDescription(request.getParameter("profileDescription")); + + + + if (request.getParameter("billingAmount") != "") { + /* + * (Required) Number of billing periods that make up one billing cycle. + The combination of billing frequency and billing period must be less than + or equal to one year. For example, if the billing cycle is Month, + the maximum value for billing frequency is 12. Similarly, + if the billing cycle is Week, the maximum value for billing frequency is 52. + Note: + If the billing period is SemiMonth, the billing frequency must be 1. + */ + int frequency = Integer.parseInt(request.getParameter("billingFrequency")); + /* + * (Required) Billing amount for each billing cycle during this payment period. + * This amount does not include shipping and tax amounts. + Note: + All amounts in the CreateRecurringPaymentsProfile request must have the same + currency. + Character length and limitations: Value is a positive number which cannot + exceed $10,000 USD in any currency. It includes no currency symbol. + It must have 2 decimal places, the decimal separator must be a period (.), + and the optional thousands separator must be a comma (,). + */ + BasicAmountType paymentAmount = new BasicAmountType(currency, request.getParameter("billingAmount")); + /* + * (Required) Unit for billing during this subscription period. + * It is one of the following values: + [Day, Week, SemiMonth, Month, Year] + For SemiMonth, billing is done on the 1st and 15th of each month. + Note: + The combination of BillingPeriod and BillingFrequency cannot exceed one year. + */ + BillingPeriodType period = BillingPeriodType.fromValue(request.getParameter("billingPeriod")); + /* + * (Optional) Number of billing cycles for payment period. + For the regular payment period, if no value is specified or the value is 0, + the regular payment period continues until the profile is canceled or deactivated. + For the regular payment period, if the value is greater than 0, + the regular payment period will expire after the trial period is + finished and continue at the billing frequency for TotalBillingCycles cycles. + + */ + int numCycles = Integer.parseInt(request.getParameter("totalBillingCycles")); + + BillingPeriodDetailsType paymentPeriod = new BillingPeriodDetailsType( + period, frequency, paymentAmount); + paymentPeriod.setTotalBillingCycles(numCycles); + /* + * (Optional) Shipping amount for each billing cycle during this payment period. + Note: + All amounts in the request must have the same currency. + */ + if (request.getParameter("shippingAmount") != "") { + paymentPeriod.setShippingAmount(new BasicAmountType( + currency, request.getParameter("shippingAmount"))); + } + /* + * (Optional) Tax amount for each billing cycle during this payment period. + Note: + All amounts in the request must have the same currency. + Character length and limitations: + Value is a positive number which cannot exceed $10,000 USD in any currency. + It includes no currency symbol. It must have 2 decimal places, + the decimal separator must be a period (.), and the optional + thousands separator must be a comma (,). + */ + if (request.getParameter("taxAmount") != "") { + paymentPeriod.setTaxAmount(new BasicAmountType( + currency, request.getParameter("taxAmount"))); + } + scheduleDetails.setPaymentPeriod(paymentPeriod); + } + + CreateRecurringPaymentsProfileRequestDetailsType reqDetails = new CreateRecurringPaymentsProfileRequestDetailsType( + profileDetails, scheduleDetails); + /* + * credit card number is required for CreateRecurringPaymentsProfile. + * Each CreateRecurringPaymentsProfile request creates + * a single recurring payments profile. + Note: + */ + CreditCardDetailsType cc = new CreditCardDetailsType(); + /* + * (Required) Credit card number. + Character length and limitations: Numeric characters only with no spaces + or punctuation. The string must conform with modulo and length required + by each credit card type. + */ + cc.setCreditCardNumber(request.getParameter("creditCardNumber")); + /* + * Card Verification Value, version 2. + * Your Merchant Account settings determine whether this field is required. + * To comply with credit card processing regulations, you must not store this + * value after a transaction has been completed. + Character length and limitations: + For Visa, MasterCard, and Discover, the value is exactly 3 digits. + For American Express, the value is exactly 4 digits. + */ + cc.setCVV2(request.getParameter("cvv")); + //Expiry Month + cc.setExpMonth(Integer.parseInt(request.getParameter("expMonth"))); + //Expiry Year + cc.setExpYear(Integer.parseInt(request.getParameter("expYear"))); + PayerInfoType payerInfo= new PayerInfoType(); + /* + * (Required) Email address of buyer. + Character length and limitations: 127 single-byte characters + */ + payerInfo.setPayer(request.getParameter("BuyerEmailId")); + cc.setCardOwner(payerInfo); + /* + * (Optional) Type of credit card. + * For UK, only Maestro, MasterCard, Discover, and Visa are allowable. + * For Canada, only MasterCard and Visa are allowable and + * Interac debit cards are not supported. It is one of the following values: + [ Visa, MasterCard, Discover, Amex, Maestro: See note.] + Note: + If the credit card type is Maestro, you must set CURRENCYCODE to GBP. + In addition, you must specify either STARTDATE or ISSUENUMBER. + */ + CreditCardTypeType type = CreditCardTypeType.fromValue(request.getParameter("creditCardType")); + switch(type){ + case AMEX: + cc.setCreditCardType(CreditCardTypeType.AMEX); + break; + case VISA: + cc.setCreditCardType(CreditCardTypeType.VISA); + break; + case DISCOVER: + cc.setCreditCardType(CreditCardTypeType.DISCOVER); + break; + case MASTERCARD: + cc.setCreditCardType(CreditCardTypeType.MASTERCARD); + break; + default: + break; + } + + reqDetails.setCreditCard(cc); + + reqType.setCreateRecurringPaymentsProfileRequestDetails(reqDetails); + req.setCreateRecurringPaymentsProfileRequest(reqType); + CreateRecurringPaymentsProfileResponseType resp = null; + try{ + resp = service.createRecurringPaymentsProfile(req); + }catch(Exception e){ + e.printStackTrace(); + } + + if (resp != null) { + session.setAttribute("lastReq", service.getLastRequest()); + session.setAttribute("lastResp", service.getLastResponse()); + if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) { + Map map = new LinkedHashMap(); + map.put("Ack", resp.getAck()); + /* + * (Required) Recurring payments profile ID returned in the + * CreateRecurringPaymentsProfile response. + Note: The profile must have a status of either Active or Suspended. + Character length and limitations: 14 single-byte alphanumeric characters. + 19 character profile IDs are supported for compatibility with previous versions + of the PayPal API. + */ + map.put("Profile ID", + resp.getCreateRecurringPaymentsProfileResponseDetails() + .getProfileID()); + map.put("Transaction ID", + resp.getCreateRecurringPaymentsProfileResponseDetails() + .getTransactionID()); + /* + * Status of the recurring payment profile. + ActiveProfile – The recurring payment profile has been successfully created and activated for scheduled payments according the billing instructions from the recurring payments profile. + PendingProfile – The system is in the process of creating the recurring payment profile. Please check your IPN messages for an update. + */ + map.put("Profile Status", + resp.getCreateRecurringPaymentsProfileResponseDetails() + .getProfileStatus()); + session.setAttribute("map", map); + response.sendRedirect(this.getServletContext().getContextPath()+"/Response.jsp"); + } else { + session.setAttribute("Error", resp.getErrors()); + response.sendRedirect(this.getServletContext().getContextPath()+"/Error.jsp"); + } + } + + + } + } +} diff --git a/merchantsample/src/main/java/com/sample/merchant/Configuration.java b/merchantsample/src/main/java/com/sample/util/Configuration.java similarity index 98% rename from merchantsample/src/main/java/com/sample/merchant/Configuration.java rename to merchantsample/src/main/java/com/sample/util/Configuration.java index 97370b0..85384b6 100644 --- a/merchantsample/src/main/java/com/sample/merchant/Configuration.java +++ b/merchantsample/src/main/java/com/sample/util/Configuration.java @@ -1,4 +1,4 @@ -package com.sample.merchant; +package com.sample.util; import java.util.HashMap; import java.util.Map; diff --git a/merchantsample/src/main/webapp/Checkout/DoExpressCheckout.jsp b/merchantsample/src/main/webapp/Checkout/DoExpressCheckout.jsp index 82e95b2..10472d2 100644 --- a/merchantsample/src/main/webapp/Checkout/DoExpressCheckout.jsp +++ b/merchantsample/src/main/webapp/Checkout/DoExpressCheckout.jsp @@ -7,6 +7,7 @@ PayPal SDK - DoExpressCheckout + PAYMENTS BY PayPal