package examples; //JDK imports import java.io.IOException; import java.io.PrintWriter; import java.sql.Date; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpUtils; import java.util.Enumeration; //WorldPay imports import com.worldpay.protocols.http.*; import com.worldpay.servlet.*; import com.worldpay.util.*; import com.worldpay.core.*; import com.worldpay.select.*; import com.worldpay.select.merchant.MerchantCurrencyConverter; import com.worldpay.select.merchant.MerchantInfo; public class BuyThis extends WorldPayServlet implements SelectDefs { /** * a request that resolves to this example should have the following * parameters. Compulsory values for generation of a purchase token * indicated by *. Calling this servlet with no parameters displays * a form that can then be filled in for creation of a purchase token. * Passing in all necessary parameters including noForm will bypass * the form and simply present a purchase token for submission to * WorldPay. * * instId* The id for this installation. * cartId merchant's identifier for the purchase (cart id). * cost* (Not compulsory if FuturePay is presemt) * A cost for the product (decimal number) * curr* The currency in which the cost is represented - ISO code * desc Description of the purchase * amountLimit Payment limit for limited future pay agreements. * initialAmount The amount of the first payment if different * from the normal amount. * normalAmt* (Compulsory for non-adjustable regular future pay agreements only) * The normal future payment amount. * startDate* (Compulsory for regular future pay agreements only) * The start date of payments, and for regular * future pay agreements the date in the month on which all * subsequent payments will be made. * endDate The end date of agreement used only for limited future pay. * intervalUnit* (Compulsory for regular future pay agreements only and when * there is more then one payment) * The unit of the interval. * intervalMultiplier* (Compulsory for regular future pay agreements only and when * there is more then one payment) * This multiplied by the interval unit gives the * interval between payments. * numberOfPayments Number of future payments, acts as a limit if * future payment is limited type. * limitedFuturePay Set to "on" if token to contain one. * regularFuturePay Set to "on" if token to contain one. * option Allows options to be set. * testMode Number indicating a test mode for this purchase * authMode character indicating an auth Mode (full=A, pre=E) null defaults to A * accId optional list of preferred accounts, from accId1 * purchaseURL URL to which to submit the purchase - if not provided * the value in select.properties will be used * name, address, postcode, country, email, tel, fax * optional contact details. country must be the two * character ISO country code. * noForm If this has a non-null value then you simply get a purchase * link, otherwise you get an input form for next time round * */ public void doRequest(WorldPayServletRequest req, WorldPayServletResponse resp) throws ServletException, IOException{ // set up response & get output stream resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); // get all parameters from the request into convenience variables String cartId = req.getParameter(SEL_cartId); String instId = req.getParameter(SEL_instId); String cost = req.getParameter("cost"); if (cost==null) // maybe this is someone using the old params cost = req.getParameter("price"); String curr = req.getParameter(SEL_currency); if (curr==null) // maybe this is someone using the old params curr = req.getParameter("curr"); if (curr != null) curr = curr.toUpperCase(); String desc = req.getParameter(SEL_desc); String startDate = req.getParameter(SEL_startDate); String intervalUnit = req.getParameter(SEL_intervalUnit); String intervalMultiplier = req.getParameter(SEL_intervalMultiplier); String numberOfPayments = req.getParameter(SEL_numberOfPayments); String option = req.getParameter(SEL_option); String initialAmount = req.getParameter(SEL_initialAmount); String normalAmount = req.getParameter(SEL_normalAmt); String amountLimit = req.getParameter(SEL_amountLimit); String endDate = req.getParameter(SEL_endDate); String startDelayUnit = req.getParameter(SEL_startDelayUnit); String startDelayMult = req.getParameter(SEL_startDelayMult); String lengthUnit = req.getParameter(SEL_lengthUnit); String lengthMult = req.getParameter(SEL_lengthMult); String testMode = req.getParameter(SEL_testMode); String authMode = req.getParameter(SEL_authMode); // not defined in SelectDefs as only used in this example String limitedFuturePay = req.getParameter("limitedFuturePay"); String regularFuturePay = req.getParameter("regularFuturePay"); String purchaseURL = req.getParameter("purchaseURL"); if (orNull(purchaseURL).length()==0) { try { purchaseURL=Select.getPurchaseURL(); } catch (SelectException e) { out.println("Can't get default PurchaseURL: "+ "you must specify it"); } } String name = req.getParameter(SEL_name); String address = req.getParameter(SEL_address); String postcode = req.getParameter(SEL_postcode); String country = req.getParameter(SEL_country); if (country != null) country = country.toUpperCase(); String email = req.getParameter(SEL_email); String tel = req.getParameter(SEL_tel); String fax = req.getParameter(SEL_fax); String noForm = req.getParameter("noForm"); // start the output page out.println("Purchase: " + desc + ""); // generate a purchase token if we have the information to do so, // otherwise we simply go straight to generating the form for // next time round if (!isEmpty(instId) && !isEmpty(curr) && !isEmpty(cartId)) { try { HTTPURL link; try { link = new HTTPURL(purchaseURL); } catch (ArgumentException e) { out.println("Can't parse purchaseURL - "+ "generating relative link instead"); link = new HTTPURL(); } URLParameters linkparms = link.getParameters(); // construct list of accounts, if any LongList accList = new LongList(); int count = 1; String accId = req.getParameter(SEL_accId + count); while (accId != null) { long accId_l = Long.parseLong(accId); accList.append(accId_l); //Debug.println("Adding account: " + accId); count += 1; accId = req.getParameter(SEL_accId + count); } // convert strings into numbers where needed double cost_d = 0.0; if (!isEmpty(cost)) { cost_d = Double.valueOf(cost).doubleValue(); } int instId_i = Integer.parseInt(instId); int testMode_i = (isEmpty(testMode)?0: Integer.parseInt(testMode)); String authMode_i = (isEmpty(authMode)?"A":authMode.substring(0,1)); //get values as currencies and get currency converter and info Currency currency = SelectCurrency.getInstanceByISOCode(curr); CurrencyAmount cAmount = null; cAmount = new CurrencyAmount(cost_d,currency); // now we can create the purchase token and add it and the // other parameters to the link PurchaseToken purchase = new PurchaseToken(instId_i, cAmount, cartId); boolean regularFuturePayPresent = false; boolean limitedFuturePayPresent = false; if (regularFuturePay != null || limitedFuturePay != null) { Debug.println("Future Pay Present"); short intervalUnit_s = 0; if (!StringUtil.isEmpty(intervalUnit)) { intervalUnit_s = Short.valueOf(intervalUnit).shortValue(); } int intervalMultiplier_i = 0; if (!StringUtil.isEmpty(intervalMultiplier)) { intervalMultiplier_i = Integer.parseInt(intervalMultiplier); } TimePeriod interval = null; if (intervalMultiplier_i > 0 && intervalUnit_s > 0) { interval = new TimePeriod(intervalUnit_s,intervalMultiplier_i); } int numberOfPayments_i = 0; if (!StringUtil.isEmpty(numberOfPayments)) { numberOfPayments_i = Integer.parseInt(numberOfPayments); } short option_s = 0; if (!StringUtil.isEmpty(option)) { option_s = Short.valueOf(option).shortValue(); } short startDelayUnit_s = 0; if (!StringUtil.isEmpty(startDelayUnit)) { startDelayUnit_s = Short.valueOf(startDelayUnit).shortValue(); } int startDelayMult_i = 0; if (!StringUtil.isEmpty(startDelayMult)) { startDelayMult_i = Integer.parseInt(startDelayMult); } TimePeriod startDelay = null; if (startDelayMult_i > 0 && startDelayUnit_s > 0) { startDelay = new TimePeriod(startDelayUnit_s,startDelayMult_i); } Date startDate_D = null; if (!StringUtil.isEmpty(startDate)) { startDate_D = Date.valueOf(startDate); } if (regularFuturePay != null && regularFuturePay.equals("on")) { Debug.println("Regular Future Pay Present"); CurrencyAmount initialAmount_CA = null; if (!StringUtil.isEmpty(initialAmount)) { double initialAmount_d = Double.valueOf(initialAmount).doubleValue(); initialAmount_CA = new CurrencyAmount(initialAmount_d,currency); } CurrencyAmount normalAmount_CA = null; if (!StringUtil.isEmpty(normalAmount)) { double normalAmount_d = Double.valueOf(normalAmount).doubleValue(); normalAmount_CA = new CurrencyAmount(normalAmount_d,currency); } RegularFuturePay futurePay = null; Debug.println("Attempting to construct regular type..."); futurePay = new RegularFuturePay(startDate_D,startDelay,numberOfPayments_i,interval, initialAmount_CA,normalAmount_CA,option_s); purchase.setFuturePay(futurePay); regularFuturePayPresent = true; } else if (limitedFuturePay != null && limitedFuturePay.equals("on")) { Debug.println("Limited Future Pay Present"); Date endDate_D = null; if (!StringUtil.isEmpty(startDate)) { startDate_D = Date.valueOf(startDate); } if (!StringUtil.isEmpty(endDate)) { endDate_D = Date.valueOf(endDate); } double amountLimit_d = 0; CurrencyAmount amountLimit_CA = null; if (!StringUtil.isEmpty(amountLimit)) { amountLimit_d = Double.valueOf(amountLimit).doubleValue(); amountLimit_CA = new CurrencyAmount(amountLimit_d,currency); } short lengthUnit_s = 0; if (!StringUtil.isEmpty(lengthUnit)) { lengthUnit_s = Short.valueOf(lengthUnit).shortValue(); } int lengthMult_i = 0; if (!StringUtil.isEmpty(lengthMult)) { lengthMult_i = Integer.parseInt(lengthMult); } TimePeriod agreementLength = null; if (lengthMult_i > 0 && lengthUnit_s > 0) { agreementLength = new TimePeriod(lengthUnit_s,lengthMult_i); } LimitedFuturePay futurePay = null; Debug.println("Attempting to construct limited type..."); futurePay = new LimitedFuturePay(startDate_D,startDelay,numberOfPayments_i,interval, amountLimit_CA,endDate_D,agreementLength,option_s); purchase.setFuturePay(futurePay); limitedFuturePayPresent = true; } } // seems to be a problem if I add an empty account list // to the purchase token - but fine if I don't add it! if (count > 1) purchase.setMerchantAccountIDList(accList); if (!isEmpty(testMode)) purchase.setTestMode(testMode_i); if (!isEmpty(authMode)) purchase.setAuthorisationMode(authMode_i); linkparms.setValue(SEL_purchase, purchase.produce()); if (!isEmpty(desc)) linkparms.setValue(SEL_desc, desc); // contact details boolean contactsPresent = false; if (!isEmpty(name)) { linkparms.setValue(SEL_name, name); contactsPresent = true; } if (!isEmpty(address)) { linkparms.setValue(SEL_address, address); contactsPresent = true; } if (!isEmpty(postcode)) { linkparms.setValue(SEL_postcode, postcode); contactsPresent = true; } if (!isEmpty(country)) { linkparms.setValue(SEL_country, country); contactsPresent = true; } if (!isEmpty(email)) { linkparms.setValue(SEL_email, email); contactsPresent = true; } if (!isEmpty(tel)) { linkparms.setValue(SEL_tel, tel); contactsPresent = true; } if (!isEmpty(fax)) { linkparms.setValue(SEL_fax, fax); contactsPresent = true; } // output a description of purchase & the link for paying out.println("
Description:" + desc); if (cAmount != null && cAmount.getAmount() != 0) { out.println("
Transaction Cost:" + cAmount.toString()); } if (contactsPresent) { out.println("
Contact:" + name + ", " + address + ", " + postcode + ", " + country + ", " + email + ", " + tel + ", " +fax); } out.println("
Test mode:" + testMode); out.println("
Auth mode:" + authMode); out.println("
"); if (regularFuturePayPresent) { out.println(" Contains Regular FuturePay Agreement"); } if (limitedFuturePayPresent) { out.println(" Contains Limited FuturePay Agreement"); } out.println("

"); out.println("Pay for this at WorldPay"); out.println(""); out.println("


"); } catch(NumberFormatException e) { out.println(""+ "Invalid number format for instId, cost or "+ "testMode

"); out.println("


"); } catch(ArgumentException e) { out.println("Invalid argument for creation "+ "of currencyAmount or purchaseToken:
");
				e.printStackTrace(out);
				out.println("

"); } catch (SelectException e) { out.println("SelectException thrown during "+ "creation of purchaseToken - incorrect instId "+ "or uninitialised installation?:"+ "
");
                e.printStackTrace(out);
                out.println("

"); } catch (MissingResourceException e) { out.println("Invalid currency code"+ "
");
                out.println("

"); } } else { // if absolutely no params then assume is first time round // so don't print error message if (req.getParameterNames().hasMoreElements()) { out.println("Insufficient data "+ "supplied for purchase:
"); if (isEmpty(instId)) out.println("- Missing instId
"); if (isEmpty(cartId)) out.println("- Missing cartId
"); if (isEmpty(cost)) out.println("- Missing cost
"); if (isEmpty(curr)) out.println("- Missing currency
"); out.println("

"); } } // now check to see whether an input form for next time round is wanted // (this is the default) if (isEmpty(noForm)) { out.println("Compulsory fields are marked with *

"); out.println("Transaction Details

"); out.println("

"); out.println(""); out.println(""); out.println(""+ ""); out.println(""); out.println("
Installation ID*"+ ""); out.println("
Cart ID*"+ ""); out.println("
Cost* (not compulsory if FuturePay present)"+ ""); out.println("
Currency (ISO code)*"+ ""); out.println("
Description"+ ""); out.println("
Test mode"+ ""); out.println("
Auth mode (defaults to full auth 'A')"+ ""); out.println("
Purchase URL"+ ""); out.println("

FuturePay Agreement Common Details

"); out.println("

"); out.println("

Start date"+ " yyyy-mm-dd (* if Regular and no start delay defined)"); out.println("
Start delay unit"+ " (* if Regular and no start date defined) Units: 1-day, 2-week, 3-month, 4-year"); out.println("
Start delay multiplier"+ " (* if Regular and no start date defined)"); out.println("
Interval Unit"+ " (* if Regular and No. != 1) Units: 1-day, 2-week, 3-month, 4-year"); out.println("
Interval multiplier"+ " (* if Regular and No. != 1)"); out.println("
Number of payments"+ " (acts as limit on Limited type)"); out.println("
Option*"); out.println("
Regular options: 0-default, 1-amount adjusted occasionally, 2-amount adjusted every payment
Limited options: 0-default, 1-no of payments limited to interval, 2-amount limit is per agreement, 3-amount limit is per interval
Regular FuturePay Specific Details

"); out.println("

"); out.println("

Token to contain Regular FuturePay Agreement"); out.println("
Initial amount"+ " (will default to normal amount)"); out.println("
Normal amount"+ " (* if not adjustable)"); out.println("

"); out.println("

Limited FuturePay Specific Details

"); out.println("

"); out.println("

Token to contain Limited FuturePay Agreement"); out.println("
Amount limit"+ ""); out.println("
End date"+ " yyy-mm-dd"); out.println("
Agreement length unit"+ " Units: 1-day, 2-week, 3-month, 4-year"); out.println("
Agreement length multiplier"+ ""); out.println("

You can fill in some of these "+ "contact details, if you like - "+ "they should then be reflected in the first "+ "new contact details form you see on the wcc."); out.println("
Name"+ ""); out.println("
Address"+ ""); out.println("
Postcode"+ ""); out.println("
Country (ISO Code)"+ ""); out.println("
Email"+ ""); out.println("
Telephone"+ ""); out.println("
Fax"+ ""); out.println("
"); out.println(""); out.println("
"); } // finish the output out.println(""); out.close(); } /** * utility method for returning an empty string if a string is null **/ private static String orNull(String x) { return (x==null)?"":x; } /** * utility method returning true if string is either null or empty **/ private static boolean isEmpty(String x) { return (x==null || x.trim().length()==0); } }