From d1bd7cdcbf150285a921f4f71aa533bd08f38687 Mon Sep 17 00:00:00 2001 From: tkanta Date: Mon, 8 Jul 2013 15:02:54 -0700 Subject: [PATCH 01/11] recurring usecase sample added --- .../com/sample/usecase/Configuration.java | 49 + .../usecase/RecurringPaymentServlet.java | 1156 +++++++++++++++++ .../CreateRecurringPaymentsProfile.jsp | 3 +- .../src/main/webapp/WEB-INF/web.xml | 20 + merchantsample/src/main/webapp/index.html | 416 +++--- .../RecurringPaymentsUsingCreditCard.jsp | 275 ++++ .../RecurringPaymentsUsingPayPal.jsp | 230 ++++ ...SetExpressCheckoutForRecurringPayments.jsp | 166 +++ 8 files changed, 2119 insertions(+), 196 deletions(-) create mode 100644 merchantsample/src/main/java/com/sample/usecase/Configuration.java create mode 100644 merchantsample/src/main/java/com/sample/usecase/RecurringPaymentServlet.java create mode 100644 merchantsample/src/main/webapp/usecase_jsp/RecurringPaymentsUsingCreditCard.jsp create mode 100644 merchantsample/src/main/webapp/usecase_jsp/RecurringPaymentsUsingPayPal.jsp create mode 100644 merchantsample/src/main/webapp/usecase_jsp/SetExpressCheckoutForRecurringPayments.jsp diff --git a/merchantsample/src/main/java/com/sample/usecase/Configuration.java b/merchantsample/src/main/java/com/sample/usecase/Configuration.java new file mode 100644 index 0000000..156a642 --- /dev/null +++ b/merchantsample/src/main/java/com/sample/usecase/Configuration.java @@ -0,0 +1,49 @@ +package com.sample.usecase; + +import java.util.HashMap; +import java.util.Map; + +/** + * For a full list of configuration parameters refer at [https://github.com/paypal/merchant-sdk-java/wiki/SDK-Configuration-Parameters] + */ +public class Configuration { + + // Creates a configuration map containing signature credentials and other required configuration parameters. + public static final Map getSignatureConfig(){ + + Map configMap = new HashMap(); + + // Endpoints are varied depending on whether sandbox OR live is chosen for mode + configMap.put("mode", "sandbox"); + + // Account Credential + configMap.put("acct1.UserName", "platfo_1255077030_biz_api1.gmail.com"); + configMap.put("acct1.Password", "1255077037"); + configMap.put("acct1.Signature", "Abg0gYcQyxQvnf2HDJkKtA-p6pqhA1k-KTYE0Gcy1diujFio4io5Vqjf "); + configMap.put("acct1.AppId", "APP-80W284485P519543T"); + // Subject is optional, only required in case of third party permission + //configMap.put("acct1.Subject", ""); + + return configMap; + } + + //Creates a configuration map containing certificate credentials and other required configuration parameters. + public static final Map getCertificateConfig(){ + + Map configMap = new HashMap(); + + // Endpoints are varied depending on whether sandbox OR live is chosen for mode + configMap.put("mode", "sandbox"); + + //Account Credential + configMap.put("acct2.UserName", "certuser_biz_api1.paypal.com"); + configMap.put("acct2.Password", "D6JNKKULHN3G5B8A"); + configMap.put("acct2.CertKey", "password"); + configMap.put("acct2.CertPath", "resource/sdk-cert.p12"); + configMap.put("acct2.AppId", "APP-80W284485P519543T"); + // Subject is optional, only required in case of third party permission + //configMap.put("acct2.Subject", ""); + + return configMap; + } +} 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..c1c7bb3 --- /dev/null +++ b/merchantsample/src/main/java/com/sample/usecase/RecurringPaymentServlet.java @@ -0,0 +1,1156 @@ +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.ActivationDetailsType; +import urn.ebay.apis.eBLBaseComponents.AddressType; +import urn.ebay.apis.eBLBaseComponents.AutoBillType; +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.FailedPaymentActionType; +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; + +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")); + + /* + * 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. + */ + request.getSession().setAttribute("paymentType",request.getParameter("paymentType")); + + 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("paymentType"))); + /* + * (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"); + /* + * (Optional) Full name of the person receiving the product or service paid for + * by the recurring payment. If not present, the name in the buyer's PayPal + * account is used. + Character length and limitations: 32 single-byte characters + */ + if (request.getParameter("subscriberName") != "") { + profileDetails.setSubscriberName(request + .getParameter("subscriberName")); + } else if (request.getParameter("shippingName") != "") { + AddressType shippingAddr = new AddressType(); + /* + * Person's name associated with this shipping address. + * It is required if using a shipping address. + Character length and limitations: 32 single-byte characters + */ + shippingAddr.setName(request.getParameter("shippingName")); + /* + * First street address. It is required if using a shipping address. + Character length and limitations: 100 single-byte characters + */ + shippingAddr.setStreet1(request.getParameter("shippingStreet1")); + /* + * (Optional) Second street address. + Character length and limitations: 100 single-byte characters + */ + shippingAddr.setStreet2(request.getParameter("shippingStreet2")); + /* + * Optional) Phone number. + Character length and limitations: 20 single-byte characters + */ + shippingAddr.setPhone(request.getParameter("shippingPhone")); + /* + * Name of city. It is required if using a shipping address. + Character length and limitations: 40 single-byte characters + */ + shippingAddr.setCityName(request.getParameter("shippingCity")); + /* + * State or province. It is required if using a shipping address. + Character length and limitations: 40 single-byte characters + */ + shippingAddr.setStateOrProvince(request.getParameter("shippingState")); + /* + * Country code. It is required if using a shipping address. + Character length and limitations: 2 single-byte characters + */ + shippingAddr.setCountryName(request.getParameter("shippingCountry")); + /* + * U.S. ZIP code or other country-specific postal code. + * It is required if using a U.S. shipping address; may be required + * for other countries. + Character length and limitations: 20 single-byte characters + */ + shippingAddr.setPostalCode(request.getParameter("shippingPostalCode")); + profileDetails.setSubscriberShippingAddress(shippingAddr); + } + + // 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")); + /* + * (Optional) Number of scheduled payments that can fail before the profile + * is automatically suspended. An IPN message is sent to the merchant when the + * specified number of failed payments is reached. + Character length and limitations: Number string representing an integer + */ + if (request.getParameter("maxFailedPayments") != "") { + scheduleDetails.setMaxFailedPayments(Integer.parseInt(request + .getParameter("maxFailedPayments"))); + } + /* + * (Optional) Indicates whether you would like PayPal to automatically bill + * the outstanding balance amount in the next billing cycle. + * The outstanding balance is the total amount of any previously failed + * scheduled payments that have yet to be successfully paid. + * It is one of the following values: + NoAutoBill – PayPal does not automatically bill the outstanding balance. + AddToNextBilling – PayPal automatically bills the outstanding balance. + */ + if (request.getParameter("autoBillOutstandingAmount") != "") { + scheduleDetails.setAutoBillOutstandingAmount(AutoBillType.fromValue(request + .getParameter("autoBillOutstandingAmount"))); + } + /* + * (Optional) Initial non-recurring payment amount due immediately upon profile creation. + * Use an initial amount for enrolment or set-up fees. + Note: + All amounts included 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("initialAmount") != "") { + ActivationDetailsType activationDetails = new ActivationDetailsType( + new BasicAmountType(currency,request.getParameter("initialAmount"))); + /* + * (Optional) Action you can specify when a payment fails. + * It is one of the following values: + 1. ContinueOnFailure – By default, PayPal suspends the pending profile in the event that + the initial payment amount fails. You can override this default behavior by setting + this field to ContinueOnFailure. Then, if the initial payment amount fails, + PayPal adds the failed payment amount to the outstanding balance for this + recurring payment profile. When you specify ContinueOnFailure, a success code is + returned to you in the CreateRecurringPaymentsProfile response and the recurring + payments profile is activated for scheduled billing immediately. + You should check your IPN messages or PayPal account for updates of the + payment status. + 2. CancelOnFailure – If this field is not set or you set it to CancelOnFailure, + PayPal creates the recurring payment profile, but places it into a pending status + until the initial payment completes. If the initial payment clears, + PayPal notifies you by IPN that the pending profile has been activated. + If the payment fails, PayPal notifies you by IPN that the pending profile + has been canceled. + + */ + if (request.getParameter("failedInitialAmountAction") != "") { + activationDetails.setFailedInitialAmountAction(FailedPaymentActionType.fromValue(request + .getParameter("failedInitialAmountAction"))); + } + scheduleDetails.setActivationDetails(activationDetails); + } + if (request.getParameter("trialBillingAmount") != "") { + /* + * Number of billing periods that make up one billing cycle; + * required if you specify an optional trial period. + 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("trialBillingFrequency")); + /* + * Billing amount for each billing cycle during this payment period; + * required if you specify an optional trial 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("trialBillingAmount")); + /* + * Unit for billing during this subscription period; + * required if you specify an optional trial 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("trialBillingPeriod")); + /* + * Number of billing periods that make up one billing cycle; + * required if you specify an optional trial period. + 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 numCycles = Integer.parseInt(request.getParameter("trialBillingCycles")); + + BillingPeriodDetailsType trialPeriod = new BillingPeriodDetailsType( + period, frequency, paymentAmount); + trialPeriod.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("trialShippingAmount") != "") { + trialPeriod.setShippingAmount(new BasicAmountType( + currency, request + .getParameter("trialShippingAmount"))); + } + /* + * (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("trialTaxAmount") != "") { + trialPeriod.setTaxAmount(new BasicAmountType(currency, + request.getParameter("trialTaxAmount"))); + } + + scheduleDetails.setTrialPeriod(trialPeriod); + } + + 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"); + /* + * (Optional) Full name of the person receiving the product or service paid for + * by the recurring payment. If not present, the name in the buyer's PayPal + * account is used. + Character length and limitations: 32 single-byte characters + */ + if (request.getParameter("subscriberName") != "") { + profileDetails.setSubscriberName(request + .getParameter("subscriberName")); + } else if (request.getParameter("shippingName") != "") { + AddressType shippingAddr = new AddressType(); + /* + * Person's name associated with this shipping address. + * It is required if using a shipping address. + Character length and limitations: 32 single-byte characters + */ + shippingAddr.setName(request.getParameter("shippingName")); + /* + * First street address. It is required if using a shipping address. + Character length and limitations: 100 single-byte characters + */ + shippingAddr.setStreet1(request.getParameter("shippingStreet1")); + /* + * (Optional) Second street address. + Character length and limitations: 100 single-byte characters + */ + shippingAddr.setStreet2(request.getParameter("shippingStreet2")); + /* + * Optional) Phone number. + Character length and limitations: 20 single-byte characters + */ + shippingAddr.setPhone(request.getParameter("shippingPhone")); + /* + * Name of city. It is required if using a shipping address. + Character length and limitations: 40 single-byte characters + */ + shippingAddr.setCityName(request.getParameter("shippingCity")); + /* + * State or province. It is required if using a shipping address. + Character length and limitations: 40 single-byte characters + */ + shippingAddr.setStateOrProvince(request.getParameter("shippingState")); + /* + * Country code. It is required if using a shipping address. + Character length and limitations: 2 single-byte characters + */ + shippingAddr.setCountryName(request.getParameter("shippingCountry")); + /* + * U.S. ZIP code or other country-specific postal code. + * It is required if using a U.S. shipping address; may be required + * for other countries. + Character length and limitations: 20 single-byte characters + */ + shippingAddr.setPostalCode(request.getParameter("shippingPostalCode")); + profileDetails.setSubscriberShippingAddress(shippingAddr); + } + + // 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")); + /* + * (Optional) Number of scheduled payments that can fail before the profile + * is automatically suspended. An IPN message is sent to the merchant when the + * specified number of failed payments is reached. + Character length and limitations: Number string representing an integer + */ + if (request.getParameter("maxFailedPayments") != "") { + scheduleDetails.setMaxFailedPayments(Integer.parseInt(request + .getParameter("maxFailedPayments"))); + } + /* + * (Optional) Indicates whether you would like PayPal to automatically bill + * the outstanding balance amount in the next billing cycle. + * The outstanding balance is the total amount of any previously failed + * scheduled payments that have yet to be successfully paid. + * It is one of the following values: + NoAutoBill – PayPal does not automatically bill the outstanding balance. + AddToNextBilling – PayPal automatically bills the outstanding balance. + */ + if (request.getParameter("autoBillOutstandingAmount") != "") { + scheduleDetails.setAutoBillOutstandingAmount(AutoBillType.fromValue(request + .getParameter("autoBillOutstandingAmount"))); + } + /* + * (Optional) Initial non-recurring payment amount due immediately upon profile creation. + * Use an initial amount for enrolment or set-up fees. + Note: + All amounts included 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("initialAmount") != "") { + ActivationDetailsType activationDetails = new ActivationDetailsType( + new BasicAmountType(currency,request.getParameter("initialAmount"))); + /* + * (Optional) Action you can specify when a payment fails. + * It is one of the following values: + 1. ContinueOnFailure – By default, PayPal suspends the pending profile in the event that + the initial payment amount fails. You can override this default behavior by setting + this field to ContinueOnFailure. Then, if the initial payment amount fails, + PayPal adds the failed payment amount to the outstanding balance for this + recurring payment profile. When you specify ContinueOnFailure, a success code is + returned to you in the CreateRecurringPaymentsProfile response and the recurring + payments profile is activated for scheduled billing immediately. + You should check your IPN messages or PayPal account for updates of the + payment status. + 2. CancelOnFailure – If this field is not set or you set it to CancelOnFailure, + PayPal creates the recurring payment profile, but places it into a pending status + until the initial payment completes. If the initial payment clears, + PayPal notifies you by IPN that the pending profile has been activated. + If the payment fails, PayPal notifies you by IPN that the pending profile + has been canceled. + + */ + if (request.getParameter("failedInitialAmountAction") != "") { + activationDetails.setFailedInitialAmountAction(FailedPaymentActionType.fromValue(request + .getParameter("failedInitialAmountAction"))); + } + scheduleDetails.setActivationDetails(activationDetails); + } + if (request.getParameter("trialBillingAmount") != "") { + /* + * Number of billing periods that make up one billing cycle; + * required if you specify an optional trial period. + 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("trialBillingFrequency")); + /* + * Billing amount for each billing cycle during this payment period; + * required if you specify an optional trial 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("trialBillingAmount")); + /* + * Unit for billing during this subscription period; + * required if you specify an optional trial 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("trialBillingPeriod")); + /* + * Number of billing periods that make up one billing cycle; + * required if you specify an optional trial period. + 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 numCycles = Integer.parseInt(request.getParameter("trialBillingCycles")); + + BillingPeriodDetailsType trialPeriod = new BillingPeriodDetailsType( + period, frequency, paymentAmount); + trialPeriod.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("trialShippingAmount") != "") { + trialPeriod.setShippingAmount(new BasicAmountType( + currency, request + .getParameter("trialShippingAmount"))); + } + /* + * (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("trialTaxAmount") != "") { + trialPeriod.setTaxAmount(new BasicAmountType(currency, + request.getParameter("trialTaxAmount"))); + } + + scheduleDetails.setTrialPeriod(trialPeriod); + } + + 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; + } + + 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/webapp/RecurringPayments/CreateRecurringPaymentsProfile.jsp b/merchantsample/src/main/webapp/RecurringPayments/CreateRecurringPaymentsProfile.jsp index ef10cea..b961781 100644 --- a/merchantsample/src/main/webapp/RecurringPayments/CreateRecurringPaymentsProfile.jsp +++ b/merchantsample/src/main/webapp/RecurringPayments/CreateRecurringPaymentsProfile.jsp @@ -78,7 +78,8 @@
- +
+
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ + + + +
Recurring payments profile details
+
Subscriber Name
+
+ +
+
Billing start date
+
+ + + /> +
+
Subscriber shipping address (if + different from buyer's PayPal account address)
+ + + + + + + + + + + + + + + + + + + + + +
NameStreet 1Street 2CityStatePostal CodeCountryPhone
+
+
+ Schedule Details: +
+
+
Description*
+
+ +
+
+
Activation Details
+ + + + + + + + + +
Initial AmountFailed Payment Action
+ +
+ Trial Period +
+ + + + + + + + + + + + + + + + + +
Billing frequencyBilling periodTotal billing cyclesPer billing cycle amountShipping amountTax
+ + + + + + + + +
+ +
+ Payment Period * +
+ + + + + + + + + + + + + + + + + +
Billing frequencyBilling periodTotal billing cyclesPer billing cycle amountShipping amountTax
+ + + + + + +
+
+
Maximum failed payments before + profile suspension
+
+ +
+
+
Auto billing of outstanding amount
+
+ +
+
+
+
+
+ Home

+ + + + + \ No newline at end of file diff --git a/merchantsample/src/main/webapp/usecase_jsp/RecurringPaymentsUsingPayPal.jsp b/merchantsample/src/main/webapp/usecase_jsp/RecurringPaymentsUsingPayPal.jsp new file mode 100644 index 0000000..414770a --- /dev/null +++ b/merchantsample/src/main/webapp/usecase_jsp/RecurringPaymentsUsingPayPal.jsp @@ -0,0 +1,230 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ page import="java.text.DateFormat"%> +<%@ page import="java.text.SimpleDateFormat"%> +<%@ page import="java.util.Calendar"%> + + + + +PayPal SDK - CreateRecurringPaymentsProfile +<% + DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + Calendar startDate = Calendar.getInstance(); +%> + + +
+ +
+
+
You must set ExpressCheckout Token
+
+
Express Checkout Token *(Token + generated via ExpressCheckout)
+
+ " /> + <% + session.removeAttribute("ecToken"); + %> +
+
+ +
Recurring payments profile details
+
Subscriber Name
+
+ +
+
Billing start date
+
+ + + /> +
+
Subscriber shipping address (if + different from buyer's PayPal account address)
+ + + + + + + + + + + + + + + + + + + + + +
NameStreet 1Street 2CityStatePostal CodeCountryPhone
+
+
+ Schedule Details: + +
+
+
Description* (must match billing + agreement if using Express Checkout token)
+
+ +
+
+
Activation Details
+ + + + + + + + + +
Initial AmountFailed Payment Action
+ +
+ Trial Period +
+ + + + + + + + + + + + + + + + + +
Billing frequencyBilling periodTotal billing cyclesPer billing cycle amountShipping amountTax
+ + + + + + + + +
+ +
+ Payment Period * +
+ + + + + + + + + + + + + + + + + +
Billing frequencyBilling periodTotal billing cyclesPer billing cycle amountShipping amountTax
+ + + + + + +
+
+
Maximum failed payments before + profile suspension
+
+ +
+
+
Auto billing of outstanding amount
+
+ +
+ +
+
+
+ Home

+
+
+
+ + \ No newline at end of file diff --git a/merchantsample/src/main/webapp/usecase_jsp/SetExpressCheckoutForRecurringPayments.jsp b/merchantsample/src/main/webapp/usecase_jsp/SetExpressCheckoutForRecurringPayments.jsp new file mode 100644 index 0000000..7d04c51 --- /dev/null +++ b/merchantsample/src/main/webapp/usecase_jsp/SetExpressCheckoutForRecurringPayments.jsp @@ -0,0 +1,166 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +PayPal SDK - SetExpressCheckout + + +
+ +
+
+
+
+
BuyerMail
+
+ +
+
+
+
+ Payment Details: +

+
+
Total Shipping costs
+
+ +
+
+
+
Total insurance cost
+
+ +
+
+
+
Total handling cost
+
+ +
+
+
+
Total Tax
+
+ +
+
+
+
Order description
+
+ +
+
+
+
CurrencyCode
+
+ +
+
+
+
PaymentType
+
+ +
+
+
Item Details
+ + + + + + + + + + + + + + + + + + + + + + + +
NameCostQuantitySales taxItem CategoryDescription (optional)
+ +
+ +
+ +
+ +
+ +
+ +
+
+
IPN Notification Url (Receive IPN + call back from PayPal)
+
+ +
+
+
+
+ Billing Agreement (Required for Recurring payments/Reference + transactions only): +

+
Billing Agreement Description *
+
+ +
+
Billing type *
+
+ +
+ +
+
+
+
+ Home +
+
+ +
+ See also + +
+
+ + \ No newline at end of file From ff991ea419c094804ad272fe4a1124d7c12e94af Mon Sep 17 00:00:00 2001 From: tkanta Date: Mon, 8 Jul 2013 19:22:34 -0700 Subject: [PATCH 02/11] payment capture usecase added --- .../com/sample/usecase/Configuration.java | 6 +- .../com/sample/usecase/PaymentCapture.java | 632 ++++++++++++++++++ merchantsample/src/main/webapp/Response.jsp | 1 + .../src/main/webapp/WEB-INF/web.xml | 31 + merchantsample/src/main/webapp/index.html | 8 + .../usecase_jsp/AuthorizedPaymentCapture.jsp | 57 ++ .../webapp/usecase_jsp/DoExpressCheckout.jsp | 99 +++ ...SetExpressCheckoutPaymentAuthorization.jsp | 140 ++++ 8 files changed, 971 insertions(+), 3 deletions(-) create mode 100644 merchantsample/src/main/java/com/sample/usecase/PaymentCapture.java create mode 100644 merchantsample/src/main/webapp/usecase_jsp/AuthorizedPaymentCapture.jsp create mode 100644 merchantsample/src/main/webapp/usecase_jsp/DoExpressCheckout.jsp create mode 100644 merchantsample/src/main/webapp/usecase_jsp/SetExpressCheckoutPaymentAuthorization.jsp diff --git a/merchantsample/src/main/java/com/sample/usecase/Configuration.java b/merchantsample/src/main/java/com/sample/usecase/Configuration.java index 156a642..b387466 100644 --- a/merchantsample/src/main/java/com/sample/usecase/Configuration.java +++ b/merchantsample/src/main/java/com/sample/usecase/Configuration.java @@ -17,9 +17,9 @@ public static final Map getSignatureConfig(){ configMap.put("mode", "sandbox"); // Account Credential - configMap.put("acct1.UserName", "platfo_1255077030_biz_api1.gmail.com"); - configMap.put("acct1.Password", "1255077037"); - configMap.put("acct1.Signature", "Abg0gYcQyxQvnf2HDJkKtA-p6pqhA1k-KTYE0Gcy1diujFio4io5Vqjf "); + configMap.put("acct1.UserName", "jb-us-seller_api1.paypal.com"); + configMap.put("acct1.Password", "WX4WTU3S8MY44S7F"); + configMap.put("acct1.Signature", "AFcWxV21C7fd0v3bYYYRCpSSRl31A7yDhhsPUU2XhtMoZXsWHFxu-RWy"); configMap.put("acct1.AppId", "APP-80W284485P519543T"); // Subject is optional, only required in case of third party permission //configMap.put("acct1.Subject", ""); diff --git a/merchantsample/src/main/java/com/sample/usecase/PaymentCapture.java b/merchantsample/src/main/java/com/sample/usecase/PaymentCapture.java new file mode 100644 index 0000000..8ad81cd --- /dev/null +++ b/merchantsample/src/main/java/com/sample/usecase/PaymentCapture.java @@ -0,0 +1,632 @@ +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.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.merchant.Configuration; + +public class PaymentCapture 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/AuthorizedPaymentCapture.jsp") + .forward(request, response); + }else if(request.getRequestURI().contains("OrderPaymentCapture")){ + getServletConfig().getServletContext() + .getRequestDispatcher("/usecase_jsp/OrderPaymentCapture.jsp") + .forward(request, response); + }else if(request.getRequestURI().contains("DoAuthoricationForOrderPayment")){ + getServletConfig().getServletContext() + .getRequestDispatcher("/usecase_jsp/DoAuthoricationForOrderPayment.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")){ + + 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 = url.toString() + "/SetExpressCheckoutPaymentAuthorization"; + + /* + * (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")); + + /* + * 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. + */ + request.getSession().setAttribute("paymentType",request.getParameter("paymentType")); + + 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("paymentType"))); + /* + * (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("SetExpressCheckoutPaymentOrder")){ + }else if(request.getRequestURI().contains("AuthorizedPaymentCapture")){ + + // ## 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(); + } + session.setAttribute("relatedUrl","
    The payment capture is completed.
"); + 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()); + /* + * 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("OrderPaymentCapture")){ + }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"); + session.setAttribute( + "relatedUrl", + "
    The payment is authorized using SetExpressCheckout. Now you can capture the payment using DoCapture api. Click the link to initiate DoCapture.
  • Capture Authorized Payment
"); + if (doCheckoutPaymentResponseType != null) { + 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("authorizationId", 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/webapp/Response.jsp b/merchantsample/src/main/webapp/Response.jsp index 53b65f0..331b9d4 100644 --- a/merchantsample/src/main/webapp/Response.jsp +++ b/merchantsample/src/main/webapp/Response.jsp @@ -52,6 +52,7 @@ diff --git a/merchantsample/src/main/webapp/WEB-INF/web.xml b/merchantsample/src/main/webapp/WEB-INF/web.xml index ec7616f..c0fa235 100644 --- a/merchantsample/src/main/webapp/WEB-INF/web.xml +++ b/merchantsample/src/main/webapp/WEB-INF/web.xml @@ -144,4 +144,35 @@ RecurringPaymentServlet /RecurringPaymentsUsingCreditCard + + + + PaymentCapture + PaymentCapture + com.sample.usecase.PaymentCapture + + + PaymentCapture + /AuthorizedPaymentCapture + + + PaymentCapture + /DoExpressCheckout + + + PaymentCapture + /SetExpressCheckoutPaymentAuthorization + + + PaymentCapture + /DoAuthoricationForOrderPayment + + + PaymentCapture + /OrderPaymentCapture + + + PaymentCapture + /SetExpressCheckoutPaymentOrder + \ No newline at end of file diff --git a/merchantsample/src/main/webapp/index.html b/merchantsample/src/main/webapp/index.html index c1cb68a..de6c672 100644 --- a/merchantsample/src/main/webapp/index.html +++ b/merchantsample/src/main/webapp/index.html @@ -17,6 +17,14 @@ RecurringPayments Using CreditCard + + SetExpressCheckout Payment Authorization and Capture + + + + SetExpressCheckout Payment Order and Capture + +
diff --git a/merchantsample/src/main/webapp/usecase_jsp/AuthorizedPaymentCapture.jsp b/merchantsample/src/main/webapp/usecase_jsp/AuthorizedPaymentCapture.jsp new file mode 100644 index 0000000..2cd1e50 --- /dev/null +++ b/merchantsample/src/main/webapp/usecase_jsp/AuthorizedPaymentCapture.jsp @@ -0,0 +1,57 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +PayPal SDK - DoCapture + + + +
+ +
+
+
+
AuthorizationID*
+
+ " size="50" maxlength="260" /> + <%session.removeAttribute("authorizationId"); %> +
+
+
+
Amount*
+
+ +
+
+
+
Currency Code*
+
+ +
+
+
+
CompleteCodeType*
+
+ +
+
+
+
+
+ Home +
+
+ +
+ + \ No newline at end of file diff --git a/merchantsample/src/main/webapp/usecase_jsp/DoExpressCheckout.jsp b/merchantsample/src/main/webapp/usecase_jsp/DoExpressCheckout.jsp new file mode 100644 index 0000000..b48aa3c --- /dev/null +++ b/merchantsample/src/main/webapp/usecase_jsp/DoExpressCheckout.jsp @@ -0,0 +1,99 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +PayPal SDK - DoExpressCheckout + + + <% + String token = request.getParameter("token"); + String payerId = request.getParameter("PayerID"); + %> +
+ +
+
+
+
+ Token*(Get Token via SetExpressCheckout) +
+
+ +
+
+
+
Payer ID*
+
+ +
+
+
+
PaymentType* (Select the PaymentType that you had set in SetExpressCheckout)
+
+ +
+
+
Payment Details*
+ + + + + + + + + + + + + + + +
NameCostCurrency CodeQuantity
+ +
+ +
+ +
+ +
+
+
IPN Notification Url (Receive IPN call back from PayPal)
+
+ +
+
+
+
+
+ Home +
+
+
+
+ See also + +
+ + + \ No newline at end of file diff --git a/merchantsample/src/main/webapp/usecase_jsp/SetExpressCheckoutPaymentAuthorization.jsp b/merchantsample/src/main/webapp/usecase_jsp/SetExpressCheckoutPaymentAuthorization.jsp new file mode 100644 index 0000000..00c21f0 --- /dev/null +++ b/merchantsample/src/main/webapp/usecase_jsp/SetExpressCheckoutPaymentAuthorization.jsp @@ -0,0 +1,140 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +PayPal SDK - SetExpressCheckout + + +
+ +
+
+
+
+
BuyerMail
+
+ +
+
+
+
+ Payment Details: +

+
+
Total Shipping costs
+
+ +
+
+
+
Total insurance cost
+
+ +
+
+
+
Total handling cost
+
+ +
+
+
+
Total Tax
+
+ +
+
+
+
Order description
+
+ +
+
+
+
CurrencyCode
+
+ +
+
+
+
PaymentType
+
+ +
+
+
Item Details
+ + + + + + + + + + + + + + + + + + + + + + + +
NameCostQuantitySales taxItem CategoryDescription (optional)
+ +
+ +
+ +
+ +
+ +
+ +
+
+
IPN Notification Url (Receive IPN + call back from PayPal)
+
+ +
+
+
+
+
+
+ Home +
+
+
+ + \ No newline at end of file From 1c85dc86473dd328c27482c8d470eac2b7cd5f9c Mon Sep 17 00:00:00 2001 From: Ganesh Hegde <1ganesh1@facebook.com> Date: Tue, 9 Jul 2013 13:57:57 +0530 Subject: [PATCH 03/11] adding PayPal image to samples --- merchantsample/src/main/webapp/Checkout/DoExpressCheckout.jsp | 1 + .../src/main/webapp/Checkout/DoUATPExpressCheckoutPayment.jsp | 1 + .../src/main/webapp/Checkout/ExecuteCheckoutOperations.jsp | 1 + .../src/main/webapp/Checkout/ExternalRememberMeOptOut.jsp | 1 + merchantsample/src/main/webapp/Checkout/GetExpressCheckout.jsp | 1 + merchantsample/src/main/webapp/Checkout/SetExpressCheckout.jsp | 1 + merchantsample/src/main/webapp/DirectPayment/DoDirectPayment.jsp | 1 + merchantsample/src/main/webapp/Error.jsp | 1 + merchantsample/src/main/webapp/GenerateAccessToken.jsp | 1 + merchantsample/src/main/webapp/MassPay/MassPay.jsp | 1 + merchantsample/src/main/webapp/MassPay/PermissionsMassPay.jsp | 1 + merchantsample/src/main/webapp/Onboard/EnterBoarding.jsp | 1 + merchantsample/src/main/webapp/Onboard/GetBoardingDetails.jsp | 1 + .../src/main/webapp/RecurringPayments/BillAgreementUpdate.jsp | 1 + .../src/main/webapp/RecurringPayments/BillOutstandingAmount.jsp | 1 + merchantsample/src/main/webapp/RecurringPayments/BillUser.jsp | 1 + .../webapp/RecurringPayments/CreateRecurringPaymentsProfile.jsp | 1 + .../main/webapp/RecurringPayments/DeprecatedBillingAgreement.jsp | 1 + .../src/main/webapp/RecurringPayments/DoReferenceTransaction.jsp | 1 + .../RecurringPayments/GetBillingAgreementCustomerDetails.jsp | 1 + .../RecurringPayments/GetRecurringPaymentsProfileDetails.jsp | 1 + .../RecurringPayments/ManageRecurringPaymentsProfileStatus.jsp | 1 + .../webapp/RecurringPayments/UpdateRecurringPaymentsProfile.jsp | 1 + merchantsample/src/main/webapp/Reports/AddressVerify.jsp | 1 + merchantsample/src/main/webapp/Reports/GetBalance.jsp | 1 + merchantsample/src/main/webapp/Reports/GetPalDetails.jsp | 1 + merchantsample/src/main/webapp/Reports/GetTransactionDetails.jsp | 1 + merchantsample/src/main/webapp/Reports/TransactionSearch.jsp | 1 + merchantsample/src/main/webapp/RequestPermissions.jsp | 1 + merchantsample/src/main/webapp/Response.jsp | 1 + merchantsample/src/main/webapp/Settlements/DoAuthorization.jsp | 1 + merchantsample/src/main/webapp/Settlements/DoCapture.jsp | 1 + .../src/main/webapp/Settlements/DoNonReferencedCredit.jsp | 1 + merchantsample/src/main/webapp/Settlements/DoReauthorization.jsp | 1 + .../src/main/webapp/Settlements/DoUATPAuthorization.jsp | 1 + merchantsample/src/main/webapp/Settlements/DoVoid.jsp | 1 + .../main/webapp/Settlements/ManagePendingTransactionStatus.jsp | 1 + merchantsample/src/main/webapp/Settlements/Refund.jsp | 1 + .../src/main/webapp/Settlements/ReverseTransaction.jsp | 1 + .../main/webapp/usecase_jsp/DoAuthoricationForOrderPayment.jsp | 1 + merchantsample/src/main/webapp/usecase_jsp/DoExpressCheckout.jsp | 1 + merchantsample/src/main/webapp/usecase_jsp/PaymentCapture.jsp | 1 + .../main/webapp/usecase_jsp/RecurringPaymentsUsingCreditCard.jsp | 1 + .../src/main/webapp/usecase_jsp/RecurringPaymentsUsingPayPal.jsp | 1 + .../usecase_jsp/SetExpressCheckoutForRecurringPayments.jsp | 1 + .../usecase_jsp/SetExpressCheckoutPaymentAuthorization.jsp | 1 + .../main/webapp/usecase_jsp/SetExpressCheckoutPaymentOrder.jsp | 1 + 47 files changed, 47 insertions(+) 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