コード例 #1
0
  protected void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    HttpSession session = req.getSession();
    session.setAttribute("url", req.getRequestURI());
    session.setAttribute(
        "relatedUrl",
        "<ul><li><a href='BM/BMCreateButton'>BMCreateButton</a></li><li><a href='BM/BMUpdateButton'>BMUpdateButton</a></li><li><a href='BM/BMButtonSearch'>BMButtonSearch</a></li><li><a href='BM/BMGetButtonDetails'>BMGetButtonDetails</a></li><li><a href='BM/BMManageButtonStatus'>BMManageButtonStatus</a></li><li><a href='BM/BMSetInventory'>BMSetInventory</a></li><li><a href='BM/BMGetInventory'>BMGetInventory</a></li></ul>");
    res.setContentType("text/html");
    try {
      // Configuration map containing signature credentials and other required configuration.
      // For a full list of configuration parameters refer in wiki page.
      // (https://github.com/paypal/sdk-core-java/blob/master/README.md)
      Map<String, String> configurationMap = Configuration.getAcctAndConfig();

      // Creating service wrapper object to make an API call by loading configuration map.
      PayPalAPIInterfaceServiceService service =
          new PayPalAPIInterfaceServiceService(configurationMap);

      if (req.getRequestURI().contains("BMCreateButton")) {

        BMCreateButtonReq request = new BMCreateButtonReq();
        BMCreateButtonRequestType reqType = new BMCreateButtonRequestType();

        /*
        *  (Required) The kind of button you want to create.
        *  It is one of the following values:

           BUYNOW - Buy Now button
           CART - Add to Cart button
           GIFTCERTIFICATE - Gift Certificate button
           SUBSCRIBE - Subscribe button
           DONATE - Donate button
           UNSUBSCRIBE - Unsubscribe button
           VIEWCART - View Cart button
           PAYMENTPLAN - Installment Plan button; since version 63.0
           AUTOBILLING - Automatic Billing button; since version 63.0
           PAYMENT - Pay Now button; since version 65.1

        Note: Do not specify BUYNOW if BUTTONCODE=TOKEN; specify PAYMENT instead.
        Do not specify PAYMENT if BUTTONCODE=HOSTED.
        */
        reqType.setButtonType(ButtonTypeType.fromValue(req.getParameter("buttonType")));

        /*
        *  (Optional) The kind of button code to create.
        *  It is one of the following values:

           1.HOSTED - A secure button stored on PayPal; default for all buttons
             except View Cart, Unsubscribe, and Pay Now
           2.ENCRYPTED - An encrypted button, not stored on PayPal; default for
              View Cart button
           3.CLEARTEXT - An unencrypted button, not stored on PayPal; default for
             Unsubscribe button
           4.TOKEN - A secure button, not stored on PayPal, used only to initiate the Hosted
             Solution checkout flow; default for Pay Now button. Since version 65.1
        */
        reqType.setButtonCode(ButtonCodeType.fromValue(req.getParameter("buttonCode")));

        // (Optional) HTML standard button variables
        List<String> lst = new ArrayList<String>();
        lst.add("item_name=" + req.getParameter("itemName"));
        lst.add("return=" + req.getParameter("returnURL"));
        lst.add("business=" + req.getParameter("businessMail"));
        lst.add("amount=" + req.getParameter("amt"));
        lst.add("notify_url=" + req.getParameter("notifyURL"));
        reqType.setButtonVar(lst);

        /*
        * Construct the request values according to the Button Type and
          Button Code.
        */
        if (req.getParameter("buttonType").equalsIgnoreCase("PAYMENTPLAN")) {

          OptionSelectionDetailsType detailsType = new OptionSelectionDetailsType("CreateButton");

          List<InstallmentDetailsType> insList = new ArrayList<InstallmentDetailsType>();
          InstallmentDetailsType insType = new InstallmentDetailsType();
          /*
           * (Optional) The total number of billing cycles, regardless of the duration
           * of a cycle; 1 is the default
           */
          insType.setTotalBillingCycles(Integer.parseInt(req.getParameter("billingCycles")));

          // (Optional) The base amount to bill for the cycle.
          insType.setAmount(req.getParameter("installmentAmt"));

          /*
           * (Optional) The installment cycle frequency in units, e.g. if the billing frequency is 2
           * and the billing period is Month, the billing cycle is every 2 months.
           * The default billing frequency is 1.
           */
          insType.setBillingFrequency(Integer.parseInt(req.getParameter("billingFreq")));

          /*
          *  (Optional) The installment cycle unit,
          *  which is one of the following values:

             NoBillingPeriodType - None (default)
             Day
             Week
             SemiMonth
             Month
             Year
          */
          insType.setBillingPeriod(BillingPeriodType.fromValue(req.getParameter("billingPeriod")));
          insList.add(insType);

          /*
          *  (Optional) The installment option type for an OPTIONnNAME,
          *  which is one of the following values:

             FULL - Payment in full
             VARIABLE - Variable installments
             EMI - Equal installments
          */
          detailsType.setOptionType(OptionTypeListType.fromValue(req.getParameter("optionType")));

          // (Optional) Information about an installment option
          detailsType.setPaymentPeriod(insList);

          // Option Details created with Menu name
          OptionDetailsType optType = new OptionDetailsType("CreateButton");
          List<OptionSelectionDetailsType> optSelectList =
              new ArrayList<OptionSelectionDetailsType>();
          optSelectList.add(detailsType);
          List<OptionDetailsType> optList = new ArrayList<OptionDetailsType>();

          // (Optional) Menu items
          optType.setOptionSelectionDetails(optSelectList);

          optList.add(optType);
          reqType.setOptionDetails(optList);
        } else if (req.getParameter("buttonType").equalsIgnoreCase("AUTOBILLING")) {

          // (Optional) HTML standard button variables
          lst.add("min_amount=" + req.getParameter("minAmt"));
        } else if (req.getParameter("buttonType").equalsIgnoreCase("GIFTCERTIFICATE")) {

          // (Optional) HTML standard button variables
          lst.add("shopping_url=" + req.getParameter("shoppingUrl"));
        } else if (req.getParameter("buttonType").equalsIgnoreCase("PAYMENT")) {

          // (Optional) HTML standard button variables
          lst.add("subtotal=" + req.getParameter("subTotal"));

        } else if (req.getParameter("buttonType").equalsIgnoreCase("SUBSCRIBE")) {

          // (Optional) HTML standard button variables
          lst.add("a3=" + req.getParameter("subAmt"));
          lst.add("p3=" + req.getParameter("subPeriod"));
          lst.add("t3=" + req.getParameter("subInterval"));
        }
        request.setBMCreateButtonRequest(reqType);
        BMCreateButtonResponseType resp = service.bMCreateButton(request);

        if (resp != null) {
          session.setAttribute("lastReq", service.getLastRequest());
          session.setAttribute("lastResp", service.getLastResponse());
          if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
            Map<Object, Object> map = new LinkedHashMap<Object, Object>();
            map.put("Ack", resp.getAck());

            // ID of a PayPal-hosted button or a Hosted Solution token
            map.put("Hosted Button ID", resp.getHostedButtonID());

            session.setAttribute("map", map);
            res.sendRedirect(this.getServletContext().getContextPath() + "/Response.jsp");
          } else {
            session.setAttribute("Error", resp.getErrors());
            res.sendRedirect(this.getServletContext().getContextPath() + "/Error.jsp");
          }
        }

      } else if (req.getRequestURI().contains("BMUpdateButton")) {

        BMUpdateButtonReq request = new BMUpdateButtonReq();
        BMUpdateButtonRequestType reqType = new BMUpdateButtonRequestType();
        /*
         *  (Required) The kind of button you want to update. It is one of the following values:

            BUYNOW - Buy Now button
            CART - Add to Cart button
            GIFTCERTIFICATE - Gift Certificate button
            SUBSCRIBE - Subscribe button
            DONATE - Donate button
            UNSUBSCRIBE - Unsubscribe button
            VIEWCART - View Cart button
            PAYMENTPLAN - Installment Plan button; since version 63.0
            AUTOBILLING - Automatic Billing button; since version 63.0

        Note:
         You cannot change the kind of button after the button has been created.

         */
        reqType.setButtonType(ButtonTypeType.fromValue(req.getParameter("buttonType")));
        /*
        *  (Optional) The kind of button code to create.
        *  It is one of the following values:

           HOSTED - A secure button stored on PayPal; default for all buttons except View Cart and Unsubscribe
           ENCRYPTED - An encrypted button, not stored on PayPal; default for View Cart button
           CLEARTEXT - An unencrypted button, not stored on PayPal; default for Unsubscribe button
        			Note:
        				You cannot change the kind of button code after after the button has been created.
        */
        reqType.setButtonCode(ButtonCodeType.fromValue(req.getParameter("buttonCode")));

        // (Optional) HTML standard button variables
        List<String> lst = new ArrayList<String>();
        lst.add("item_name=" + req.getParameter("itemName"));
        lst.add("amount=" + req.getParameter("amt"));
        lst.add("return=" + req.getParameter("returnURL"));
        lst.add("business=" + req.getParameter("businessMail"));
        lst.add("notify_url=" + req.getParameter("notifyURL"));

        reqType.setButtonVar(lst);
        // Construct the request values according to the Button Type and
        // Button Code
        if (req.getParameter("buttonType").equalsIgnoreCase("PAYMENTPLAN")) {

          OptionSelectionDetailsType detailsType = new OptionSelectionDetailsType("CreateButton");

          List<InstallmentDetailsType> insList = new ArrayList<InstallmentDetailsType>();
          InstallmentDetailsType insType = new InstallmentDetailsType();

          /*
           * (Optional) The total number of billing cycles, regardless of the duration
           * of a cycle; 1 is the default
           */
          insType.setTotalBillingCycles(3);

          // (Optional) The base amount to bill for the cycle.
          insType.setAmount("2.00");

          /*
           * (Optional) The installment cycle frequency in units, e.g.
           * if the billing frequency is 2 and the billing period is Month,
           * the billing cycle is every 2 months. The default billing frequency is 1.
           */
          insType.setBillingFrequency(2);

          /*
          *  (Optional) The installment cycle unit, which is one of the following values:

             NoBillingPeriodType - None (default)
             Day
             Week
             SemiMonth
             Month
             Year
          */
          insType.setBillingPeriod(BillingPeriodType.MONTH);
          insList.add(insType);
          /*
          *  (Optional) The installment option type for an OPTIONnNAME,
          *  which is one of the following values:

             FULL - Payment in full
             VARIABLE - Variable installments
             EMI - Equal installments

          Note:
          Only available for Installment Plan buttons.
          */
          detailsType.setOptionType(OptionTypeListType.EMI);

          // (Optional) Information about an installment option
          detailsType.setPaymentPeriod(insList);

          // Option Details created with Menu name
          OptionDetailsType optType = new OptionDetailsType("CreateButton");
          List<OptionSelectionDetailsType> optSelectList =
              new ArrayList<OptionSelectionDetailsType>();
          optSelectList.add(detailsType);
          List<OptionDetailsType> optList = new ArrayList<OptionDetailsType>();

          // (Optional) Menu items
          optType.setOptionSelectionDetails(optSelectList);

          optList.add(optType);
          reqType.setOptionDetails(optList);
        } else if (req.getParameter("buttonType").equalsIgnoreCase("AUTOBILLING")) {
          // (Optional) HTML standard button variables
          lst.add("min_amount=4.00");
        } else if (req.getParameter("buttonType").equalsIgnoreCase("GIFTCERTIFICATE")) {
          // (Optional) HTML standard button variables
          lst.add("shopping_url=http://www.ebay.com");
        } else if (req.getParameter("buttonType").equalsIgnoreCase("PAYMENT")) {
          // (Optional) HTML standard button variables
          lst.add("subtotal=2.00");
        } else if (req.getParameter("buttonType").equalsIgnoreCase("SUBSCRIBE")) {
          // (Optional) HTML standard button variables
          lst.add("a3=2.00");
          lst.add("p3=3");
          lst.add("t3=W");
        }

        // (Required) The ID of the hosted button you want to modify.
        reqType.setHostedButtonID(req.getParameter("hostedID"));
        request.setBMUpdateButtonRequest(reqType);

        // ## Making API call
        // Invoke the appropriate method corresponding to API in service
        // wrapper object
        BMUpdateButtonResponseType resp = service.bMUpdateButton(request);

        if (resp != null) {
          session.setAttribute("lastReq", service.getLastRequest());
          session.setAttribute("lastResp", service.getLastResponse());
          if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
            Map<Object, Object> map = new LinkedHashMap<Object, Object>();
            map.put("Ack", resp.getAck());

            // ID of a PayPal hosted button
            map.put("Hosted Button ID", resp.getHostedButtonID());
            session.setAttribute("map", map);
            res.sendRedirect(this.getServletContext().getContextPath() + "/Response.jsp");
          } else {
            session.setAttribute("Error", resp.getErrors());
            res.sendRedirect(this.getServletContext().getContextPath() + "/Error.jsp");
          }
        }
      } else if (req.getRequestURI().contains("BMButtonSearch")) {
        BMButtonSearchReq request = new BMButtonSearchReq();
        BMButtonSearchRequestType reqType = new BMButtonSearchRequestType();

        /*
         * (Required) Starting date for the search. The value must be in UTC/GMT format;
         * for example, 2009-08-24T05:38:48Z. No wildcards are allowed.
         */
        reqType.setStartDate(req.getParameter("startDate") + "T00:00:00.000Z");
        /*
         * (Optional) Ending date for the search. The value must be in UTC/GMT format;
         * for example, 2010-05-01T05:38:48Z. No wildcards are allowed.
         */
        reqType.setEndDate(req.getParameter("endDate") + "T23:59:59.000Z");

        request.setBMButtonSearchRequest(reqType);

        // ## Making API call
        // Invoke the appropriate method corresponding to API in service
        // wrapper object
        BMButtonSearchResponseType resp = service.bMButtonSearch(request);
        if (resp != null) {
          session.setAttribute("lastReq", service.getLastRequest());
          session.setAttribute("lastResp", service.getLastResponse());
          if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
            Map<Object, Object> map = new LinkedHashMap<Object, Object>();
            map.put("Ack", resp.getAck());
            Iterator<ButtonSearchResultType> iterator = resp.getButtonSearchResult().iterator();
            while (iterator.hasNext()) {
              ButtonSearchResultType result = (ButtonSearchResultType) iterator.next();

              // The hosted button ID
              map.put("ButtonType", result.getButtonType());

              // The hosted button ID
              map.put("Hosted Button ID", result.getHostedButtonID());

              // The item name
              map.put("Item Name", result.getItemName());
            }

            session.setAttribute("map", map);
            res.sendRedirect(this.getServletContext().getContextPath() + "/Response.jsp");
          } else {
            session.setAttribute("Error", resp.getErrors());
            res.sendRedirect(this.getServletContext().getContextPath() + "/Error.jsp");
          }
        }

      } else if (req.getRequestURI().contains("BMGetButtonDetails")) {

        BMGetButtonDetailsReq request = new BMGetButtonDetailsReq();
        BMGetButtonDetailsRequestType reqType = new BMGetButtonDetailsRequestType();

        // (Required) The ID of the hosted button whose details you want to obtain.
        reqType.setHostedButtonID(req.getParameter("hostedID"));

        request.setBMGetButtonDetailsRequest(reqType);

        // ## Making API call
        // Invoke the appropriate method corresponding to API in service
        // wrapper object
        BMGetButtonDetailsResponseType resp = service.bMGetButtonDetails(request);
        if (resp != null) {
          session.setAttribute("lastReq", service.getLastRequest());
          session.setAttribute("lastResp", service.getLastResponse());
          if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
            Map<Object, Object> map = new LinkedHashMap<Object, Object>();
            map.put("Ack", resp.getAck());
            /*
            * The kind of button. It is one of the following values:

               BUYNOW - Buy Now button
               CART - Add to Cart button
               GIFTCERTIFICATE - Gift Certificate button
               SUBSCRIBE - Subscribe button
               DONATE - Donate button
               UNSUBSCRIBE - Unsubscribe button
               VIEWCART - View Cart button
               PAYMENTPLAN - Installment Plan button; since version 63.0
               AUTOBILLING - Automatic Billing button; since version 63.0
            */
            map.put("ButtonType", resp.getButtonType());

            /*
            * The kind of button code. It is one of the following values:

               HOSTED - A secure button stored on PayPal
               ENCRYPTED - An encrypted button, not stored on PayPal
               CLEARTEXT - An unencrypted button, not stored on PayPal
            */
            map.put("ButtonCode", resp.getButtonCode());

            // HTML code for web pages
            map.put("Website", resp.getWebsite());
            session.setAttribute("map", map);
            res.sendRedirect(this.getServletContext().getContextPath() + "/Response.jsp");
          } else {
            session.setAttribute("Error", resp.getErrors());
            res.sendRedirect(this.getServletContext().getContextPath() + "/Error.jsp");
          }
        }

      } else if (req.getRequestURI().contains("BMManageButtonStatus")) {
        BMManageButtonStatusReq request = new BMManageButtonStatusReq();
        BMManageButtonStatusRequestType reqType = new BMManageButtonStatusRequestType();

        // (Required) The ID of the hosted button whose status you want to change.
        reqType.setHostedButtonID(req.getParameter("hostedID"));

        /*
        *  (Required) The new status of the button. It is one of the following values:
        			 DELETE - the button is deleted from PayPal
        */
        reqType.setButtonStatus(ButtonStatusType.fromValue(req.getParameter("buttonStatus")));
        request.setBMManageButtonStatusRequest(reqType);

        // ## Making API call
        // Invoke the appropriate method corresponding to API in service
        // wrapper object
        BMManageButtonStatusResponseType resp = service.bMManageButtonStatus(request);

        if (resp != null) {
          session.setAttribute("lastReq", service.getLastRequest());
          session.setAttribute("lastResp", service.getLastResponse());
          if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
            Map<Object, Object> map = new LinkedHashMap<Object, Object>();
            map.put("Ack", resp.getAck());
            session.setAttribute("map", map);
            res.sendRedirect(this.getServletContext().getContextPath() + "/Response.jsp");
          } else {
            session.setAttribute("Error", resp.getErrors());
            res.sendRedirect(this.getServletContext().getContextPath() + "/Error.jsp");
          }
        }

      } else if (req.getRequestURI().contains("BMGetInventory")) {
        BMGetInventoryReq request = new BMGetInventoryReq();
        BMGetInventoryRequestType reqType = new BMGetInventoryRequestType();
        // (Required) The ID of the hosted button whose inventory information you want to obtain.
        reqType.setHostedButtonID(req.getParameter("hostedID"));
        request.setBMGetInventoryRequest(reqType);

        // ## Making API call
        // Invoke the appropriate method corresponding to API in service
        // wrapper object
        BMGetInventoryResponseType resp = service.bMGetInventory(request);

        if (resp != null) {
          if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
            session.setAttribute("lastReq", service.getLastRequest());
            session.setAttribute("lastResp", service.getLastResponse());
            if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
              Map<Object, Object> map = new LinkedHashMap<Object, Object>();
              map.put("Ack", resp.getAck());
              /*
              * Whether to track inventory levels associated with the button.
              * It is one of the following values:

                 0 - do not track inventory
                 1 - track inventory
              */
              map.put("TrackInv", resp.getTrackInv());

              /*
               * Whether to track the gross profit associated with inventory changes.
               * It is one of the following values:

                  0 - do not track the gross profit
                  1 - track the gross profit

              Note:
              The gross profit is calculated as the price of the item less its cost,
              multiplied by the change in the inventory level since the last call to
              BMSetInventory.
               */
              map.put("TrackPnl", resp.getTrackPnl());
              // The ID of the hosted button whose inventory you want to set.
              map.put("Hosted Button ID", resp.getHostedButtonID());

              // The cost of the item associated with this button
              map.put("Item Cost", resp.getItemTrackingDetails().getItemCost());

              // The current inventory level of the item associated with this button
              map.put("Item Quantity", resp.getItemTrackingDetails().getItemQty());
              session.setAttribute("map", map);
              res.sendRedirect(this.getServletContext().getContextPath() + "/Response.jsp");
            }

          } else {
            session.setAttribute("Error", resp.getErrors());
            res.sendRedirect(this.getServletContext().getContextPath() + "/Error.jsp");
          }
        }
      } else if (req.getRequestURI().contains("BMSetInventory")) {
        BMSetInventoryReq request = new BMSetInventoryReq();
        BMSetInventoryRequestType reqType = new BMSetInventoryRequestType();

        // API Version
        reqType.setVersion("82");

        // (Required) The ID of the hosted button whose inventory you want to set.
        reqType.setHostedButtonID(req.getParameter("hostedID"));

        /*
        *  (Required) Whether to track inventory levels associated with the button.
        *  It is one of the following values:

           0 - do not track inventory
           1 - track inventory
        */
        reqType.setTrackInv(req.getParameter("trackInv"));

        /*
        *  (Required) Whether to track the gross profit associated with inventory changes.
        *  It is one of the following values:

           0 - do not track the gross profit
           1 - track the gross profit
        Note: The gross profit is calculated as the price of the item less its cost,
        multiplied by the change in the inventory level since the last call to
        BMSetInventory
        */
        reqType.setTrackPnl(req.getParameter("trackPnl"));
        ItemTrackingDetailsType itemTrackDetails = new ItemTrackingDetailsType();

        /*
         * The quantity you want to specify for the item associated with this button.
         * Specify either the absolute quantity in this field or the change in quantity in
         * the quantity delta field
         */
        itemTrackDetails.setItemQty(req.getParameter("itemQty"));

        // (Optional) The cost of the item associated with this button
        itemTrackDetails.setItemCost(req.getParameter("itemCost"));
        reqType.setItemTrackingDetails(itemTrackDetails);
        request.setBMSetInventoryRequest(reqType);

        // ## Making API call
        // Invoke the appropriate method corresponding to API in service
        // wrapper object
        BMSetInventoryResponseType resp = service.bMSetInventory(request);
        res.setContentType("text/html");
        if (resp != null) {
          session.setAttribute("lastReq", service.getLastRequest());
          session.setAttribute("lastResp", service.getLastResponse());
          if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
            Map<Object, Object> map = new LinkedHashMap<Object, Object>();
            map.put("Ack", resp.getAck());
            session.setAttribute("map", map);
            res.sendRedirect(this.getServletContext().getContextPath() + "/Response.jsp");
          } else {

            session.setAttribute("Error", resp.getErrors());
            res.sendRedirect(this.getServletContext().getContextPath() + "/Error.jsp");
          }
        }
      }

    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SSLConfigurationException e) {
      e.printStackTrace();
    } catch (InvalidCredentialException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (HttpErrorException e) {
      e.printStackTrace();
    } catch (InvalidResponseDataException e) {
      e.printStackTrace();
    } catch (ClientActionRequiredException e) {
      e.printStackTrace();
    } catch (MissingCredentialException e) {
      e.printStackTrace();
    } catch (OAuthException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
コード例 #2
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    HttpSession session = request.getSession();
    session.setAttribute("url", request.getRequestURI());
    session.setAttribute(
        "relatedUrl",
        "<ul><li><a href='Pay'>Pay</a></li><li><a href='Refund'>Refund</a></li><li><a href='Preapproval'>Preapproval</a></li></ul>");
    RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");

    List<CurrencyType> currency = new ArrayList<CurrencyType>();
    CurrencyType type1 = new CurrencyType();
    /** (Required) The amount to be converted. */
    if (request.getParameter("amount") != "")
      type1.setAmount(Double.parseDouble(request.getParameter("amount")));

    /** (Required) The currency code. */
    if (request.getParameter("code") != "") type1.setCode(request.getParameter("code"));
    currency.add(type1);
    CurrencyList baseAmountList = new CurrencyList(currency);
    List<String> currencyCode = new ArrayList<String>();

    /** (Required) A list of currencies to convert to. */
    if (request.getParameter("convertTo") != "")
      currencyCode.add(request.getParameter("convertTo"));

    CurrencyCodeList convertToCurrencyList = new CurrencyCodeList(currencyCode);

    ConvertCurrencyRequest req =
        new ConvertCurrencyRequest(requestEnvelope, baseAmountList, convertToCurrencyList);
    /**
     * (Optional)The conversion type allows you to determine the converted amounts for a PayPal user
     * in different currency conversion scenarios, e.g., sending a payment in a different currency
     * than what this user holds, accepting payment in a different currency than what the user
     * holds, or converting a balance to a different currency than the user holds.. The default
     * value is SENDER_SIDE
     */
    if (request.getParameter("conversionType") != "")
      req.setConversionType(request.getParameter("conversionType"));
    /**
     * (Optional)The two-character ISO code for the country where the function is supposed to
     * happen. The default value is US.
     */
    if (request.getParameter("countryCode") != "")
      req.setCountryCode(request.getParameter("countryCode"));

    // Configuration map containing signature credentials and other required configuration.
    // For a full list of configuration parameters refer in wiki page
    // (https://github.com/paypal/sdk-core-java/wiki/SDK-Configuration-Parameters)
    Map<String, String> configurationMap = Configuration.getAcctAndConfig();

    // Creating service wrapper object to make an API call by loading configuration map.
    AdaptivePaymentsService service = new AdaptivePaymentsService(configurationMap);

    response.setContentType("text/html");
    try {

      // if (request.getParameter("ConvertBtn").equals("convert")) {
      ConvertCurrencyResponse resp = service.convertCurrency(req);
      if (resp != null) {
        session.setAttribute("RESPONSE_OBJECT", resp);
        session.setAttribute("lastReq", service.getLastRequest());
        session.setAttribute("lastResp", service.getLastResponse());
        if (resp.getResponseEnvelope().getAck().toString().equalsIgnoreCase("SUCCESS")) {
          Map<Object, Object> map = new LinkedHashMap<Object, Object>();
          map.put("Ack", resp.getResponseEnvelope().getAck());

          /**
           * Correlation identifier. It is a 13-character, alphanumeric string (for example,
           * db87c705a910e) that is used only by PayPal Merchant Technical Support. Note: You must
           * log and store this data for every response you receive. PayPal Technical Support uses
           * the information to assist with reported issues.
           */
          map.put("Correlation ID", resp.getResponseEnvelope().getCorrelationId());

          /**
           * Date on which the response was sent, for example: 2012-04-02T22:33:35.774-07:00 Note:
           * You must log and store this data for every response you receive. PayPal Technical
           * Support uses the information to assist with reported issues.
           */
          map.put("Time Stamp", resp.getResponseEnvelope().getTimestamp());
          Iterator<CurrencyConversionList> iterator =
              resp.getEstimatedAmountTable().getCurrencyConversionList().iterator();
          int index = 1;
          while (iterator.hasNext()) {
            CurrencyConversionList currencyList = iterator.next();
            map.put("Amount to be converted" + index, currencyList.getBaseAmount().getAmount());
            Iterator<CurrencyType> currencyIterator =
                currencyList.getCurrencyList().getCurrency().iterator();
            int innerIndex = 1;
            while (currencyIterator.hasNext()) {
              CurrencyType currencyType = currencyIterator.next();
              map.put("Currency" + innerIndex, currencyType.getCode());
              map.put("Converted Amount" + innerIndex, currencyType.getAmount());
              innerIndex++;
            }
            index++;
          }
          session.setAttribute("map", map);
          response.sendRedirect("Response.jsp");
        } else {
          session.setAttribute("Error", resp.getError());
          response.sendRedirect("Error.jsp");
        }
      }

      // }
    } catch (SSLConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidCredentialException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (HttpErrorException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidResponseDataException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClientActionRequiredException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MissingCredentialException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (OAuthException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    HttpSession session = request.getSession();
    session.setAttribute("url", request.getRequestURI());
    session.setAttribute(
        "relatedUrl",
        "<ul><li><a href='RequestPermissions'>RequestPermissions</a></li><li><a href='GetAccessToken'>GetAccessToken</a></li><li><a href='GetPermissions'>GetPermissions</a></li><li><a href='CancelPermissions'>CancelPermissions</a></li><li><a href='GetBasicPersonalData'>GetBasicPersonalData</a></li><li><a href='GetAdvancedPersonalData'>GetAdvancedPersonalData</a></li></ul>");

    GetAdvancedPersonalDataRequest req = new GetAdvancedPersonalDataRequest();
    /*
     * (Required) RFC 3066 language in which error messages are returned; by
     * default it is en_US, which is the only language currently supported.
     */
    RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
    req.setRequestEnvelope(requestEnvelope);

    /*
     * The attributes whose value you are requesting. You specify one or
     * more of the following URIs:
     *
     * http://axschema.org/birthDate - Date of birth
     * http://axschema.org/contact/postalCode/home - Postcode
     * http://schema.openid.net/contact/street1 - Street1
     * http://schema.openid.net/contact/street2 - Street2
     * http://axschema.org/contact/city/home - City
     * http://axschema.org/contact/state/home - State
     * http://axschema.org/contact/phone/default - Phone
     */
    List<PersonalAttribute> lst = new ArrayList<PersonalAttribute>();
    String check[] = request.getParameterValues("attr");
    for (int i = 0; i < check.length; i++) {
      lst.add(PersonalAttribute.fromValue(check[i]));
    }
    PersonalAttributeList attribute = new PersonalAttributeList();
    attribute.setAttribute(lst);
    req.setAttributeList(attribute);

    SignatureCredential cred = null;
    if (request.getParameter("accessToken") != null
        && request.getParameter("accessToken").length() > 0
        && request.getParameter("tokenSecret") != null
        && request.getParameter("tokenSecret").length() > 0) {
      // The access token that identifies a set of permissions.
      // The secret associated with the access token.
      ThirdPartyAuthorization thirdPartyAuth =
          new TokenAuthorization(
              request.getParameter("accessToken"), request.getParameter("tokenSecret"));

      cred =
          new SignatureCredential(
              "jb-us-seller_api1.paypal.com",
              "WX4WTU3S8MY44S7F",
              "AFcWxV21C7fd0v3bYYYRCpSSRl31A7yDhhsPUU2XhtMoZXsWHFxu-RWy");

      cred.setApplicationId("APP-80W284485P519543T");
      cred.setThirdPartyAuthorization(thirdPartyAuth);
    }
    // ## Creating service wrapper object
    // Creating service wrapper object to make API call
    // Configuration map containing mode and other required configuration.
    // For a full list of configuration parameters refer in wiki page.
    // (https://github.com/paypal/sdk-core-java/wiki/SDK-Configuration-Parameters)
    PermissionsService service = new PermissionsService(Configuration.getAcctAndConfig());
    try {

      // ## Making API call
      // Invoke the appropriate method corresponding to API in service
      // wrapper object
      GetAdvancedPersonalDataResponse resp = null;
      if (cred != null) {
        resp = service.getAdvancedPersonalData(req, cred);
      } else {
        resp = service.getAdvancedPersonalData(req);
      }
      response.setContentType("text/html");
      if (resp != null) {
        session.setAttribute("RESPONSE_OBJECT", resp);
        session.setAttribute("lastReq", service.getLastRequest());
        session.setAttribute("lastResp", service.getLastResponse());
        if (resp.getResponseEnvelope().getAck().toString().equalsIgnoreCase("SUCCESS")) {
          Map<Object, Object> map = new LinkedHashMap<Object, Object>();
          /*
           * Acknowledgement code. It is one of the following values:
           *
           * Success - The operation completed successfully. Failure -
           * The operation failed. Warning - Warning.
           * SuccessWithWarning - The operation completed
           * successfully; however, there is a warning message.
           * FailureWithWarning - The operation failed with a warning
           * message.
           */
          map.put("Ack", resp.getResponseEnvelope().getAck());
          Iterator<PersonalData> iterator = resp.getResponse().getPersonalData().iterator();
          int index = 1;
          while (iterator.hasNext()) {
            PersonalData personalData = iterator.next();
            /*
             * The attributes whose values you are requesting. You
             * specify one or more of the following URIs:
             *
             * http://axschema.org/namePerson/first - First name
             * http://axschema.org/namePerson/last - last name
             * http://axschema.org/contact/email - Email
             * http://schema.openid.net/contact/fullname - Full name
             * http://openid.net/schema/company/name - Business name
             * http://axschema.org/contact/country/home - Country
             * https://www.paypal.com/webapps/auth/schema/payerID -
             * Payer ID
             */
            map.put("PersonalDataKey" + index, personalData.getPersonalDataKey().getValue());

            // The value associated with the key
            map.put("PersonalDataValue" + index, personalData.getPersonalDataValue());
            index++;
          }

          session.setAttribute("map", map);
          response.sendRedirect("Response.jsp");
        } else {
          session.setAttribute("Error", resp.getError());
          response.sendRedirect("Error.jsp");
        }
      }

    } catch (OAuthException e) {
      // TODO: handle exception
      e.printStackTrace();
    } catch (SSLConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidCredentialException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (HttpErrorException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidResponseDataException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClientActionRequiredException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MissingCredentialException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #4
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    InvoiceType invoiceType = new InvoiceType();
    invoiceType.setMerchantEmail(request.getParameter("merchantEmail"));
    invoiceType.setPayerEmail(request.getParameter("payerEmail"));
    List<InvoiceItemType> items = new ArrayList<InvoiceItemType>();
    items.add(
        new InvoiceItemType(
            request.getParameter("item_name1"),
            Double.valueOf(request.getParameter("item_quantity1")),
            Double.valueOf(request.getParameter("item_unitPrice1"))));
    items.add(
        new InvoiceItemType(
            request.getParameter("item_name2"),
            Double.valueOf(request.getParameter("item_quantity2")),
            Double.valueOf(request.getParameter("item_unitPrice2"))));
    invoiceType.setItems(items);
    invoiceType.setCurrencyCode(request.getParameter("currencyCode"));
    invoiceType.setPaymentTerms(PaymentTermsType.valueOf(request.getParameter("paymentTerms")));

    RequestEnvelope env = new RequestEnvelope("en_US");
    try {

      if (request.getParameter("CreateBtn") != null) {
        if (request.getParameter("CreateBtn").equals("CreateInvoice")) {
          CreateInvoiceRequest createRequest = new CreateInvoiceRequest(env, invoiceType);
          InvoiceService invoiceSrvc =
              new InvoiceService(
                  this.getServletContext().getRealPath("/") + "/WEB-INF/sdk_config.properties");

          CreateInvoiceResponse createResp = invoiceSrvc.createInvoice(createRequest);
          response.getWriter().println("Ack:" + createResp.getResponseEnvelope().getAck());
          response.getWriter().println("InvoiceID:" + createResp.getInvoiceID());
          response.getWriter().println("InvoiceNumber:" + createResp.getInvoiceNumber());

        } else if (request.getParameter("CreateBtn").equals("CreateAndSendInvoice")) {
          CreateAndSendInvoiceRequest createRequest =
              new CreateAndSendInvoiceRequest(env, invoiceType);
          InvoiceService invoiceSrvc =
              new InvoiceService(
                  this.getServletContext().getRealPath("/") + "/WEB-INF/sdk_config.properties");

          CreateAndSendInvoiceResponse createResp = invoiceSrvc.createAndSendInvoice(createRequest);
          response.getWriter().println("Ack:" + createResp.getResponseEnvelope().getAck());
          response.getWriter().println("InvoiceID:" + createResp.getInvoiceID());
          response.getWriter().println("InvoiceNumber:" + createResp.getInvoiceNumber());
        } else {
          response.getWriter().println("Unknown request - click one of the buttons");
        }
      }

    } catch (SSLConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidCredentialException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (HttpErrorException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidResponseDataException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClientActionRequiredException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MissingCredentialException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }