简体   繁体   中英

Paypal Java-SDK Payment issue

I am trying to integrate Papal with my Spring Web Service. I am refering Advanced Server Integration and using this SDK Create Payment Sample .

Here is my Client Side Code

<script src="https://www.paypalobjects.com/api/checkout.js">
</script>
<h1>Paypal Integration - Advanced Server Side Integration</h1>
<div id="paypal-button-container"></div>
<script>
// Render the PayPal button

paypal.Button.render({

    // Set your environment

    env: 'sandbox', // sandbox | production

    // Wait for the PayPal button to be clicked

    payment: function() {

        // Make a call to the merchant server to set up the payment

        return paypal.request.post('http://localhost:8080/api/createpayment').then(function(res) {
            console.log(res);
            return res.payToken;
        });
    },

    // Wait for the payment to be authorized by the customer

    onAuthorize: function(data, actions) {

        // Make a call to the merchant server to execute the payment

        return paypal.request.post('http://localhost:8080/api/createpayment', {
            payToken: data.paymentID,
            payerId: data.payerID
        }).then(function(res) {
            console.log(res);
            document.querySelector('#paypal-button-container').innerText = 'Payment Complete!';
        });
    }

}, '#paypal-button-container');
</script>

Here is my Web Service

@RequestMapping(value = "/createpayment", method = RequestMethod.POST)
    public @ResponseBody 
    Payment createPayment(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> map = new HashMap<String, String>();

        Payment createdPayment = null;
        try {

            final String clientID = "<clientId>";
            final String clientSecret = "clientSecret";
            // ### Api Context
            // Pass in a `ApiContext` object to authenticate
            // the call and to send a unique request id
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly.
            APIContext apiContext = new APIContext(clientID, clientSecret, "sandbox");
            if (request.getParameter("PayerID") != null) {
                logger.info("Payment Execution");
                Payment payment = new Payment();
                if (request.getParameter("guid") != null) {
                    payment.setId(map.get(request.getParameter("guid")));
                }

                PaymentExecution paymentExecution = new PaymentExecution();
                paymentExecution.setPayerId(request.getParameter("PayerID"));


                createdPayment = payment.execute(apiContext, paymentExecution);
                logger.info("Executed Payment - Request :: \n " + Payment.getLastRequest());
                logger.info("Exceuted Payment - Response :; \n " + Payment.getLastResponse());
                //ResultPrinter.addResult(req, resp, "Executed The Payment", Payment.getLastRequest(), Payment.getLastResponse(), null);

                //ResultPrinter.addResult(req, resp, "Executed The Payment", Payment.getLastRequest(), null, e.getMessage());

            } else {
                logger.info("Create Payment");
                // ###Details
                // Let's you specify details of a payment amount.
                Details details = new Details();
                //details.setShipping("1");
                details.setSubtotal("0.1");
                //details.setTax("1");

                // ###Amount
                // Let's you specify a payment amount.
                Amount amount = new Amount();
                amount.setCurrency("USD");
                // Total must be equal to sum of shipping, tax and subtotal.
                amount.setTotal("0.1");
                amount.setDetails(details);

                // ###Transaction
                // A transaction defines the contract of a
                // payment - what is the payment for and who
                // is fulfilling it. Transaction is created with
                // a `Payee` and `Amount` types
                Transaction transaction = new Transaction();
                transaction.setAmount(amount);
                transaction.setDescription("This is the payment transaction description.");

                // ### Items
                Item item = new Item();
                item.setName("Item for Purchase").setQuantity("1").setCurrency("USD").setPrice("0.1");
                ItemList itemList = new ItemList();
                List<Item> items = new ArrayList<Item>();
                items.add(item);
                itemList.setItems(items);

                transaction.setItemList(itemList);


                // The Payment creation API requires a list of
                // Transaction; add the created `Transaction`
                // to a List
                List<Transaction> transactions = new ArrayList<Transaction>();
                transactions.add(transaction);

                // ###Payer
                // A resource representing a Payer that funds a payment
                // Payment Method
                // as 'paypal'
                Payer payer = new Payer();
                payer.setPaymentMethod("paypal");

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as 'sale'
                Payment payment = new Payment();
                payment.setIntent("sale");
                payment.setPayer(payer);
                payment.setTransactions(transactions);

                // ###Redirect URLs
                RedirectUrls redirectUrls = new RedirectUrls();
                String guid = UUID.randomUUID().toString().replaceAll("-", "");
                redirectUrls.setCancelUrl(request.getScheme() + "://"
                        + request.getServerName() + ":" + request.getServerPort()
                        + request.getContextPath() + "/paymentwithpaypal?guid=" + guid);
                redirectUrls.setReturnUrl(request.getScheme() + "://"
                        + request.getServerName() + ":" + request.getServerPort()
                        + request.getContextPath() + "/paymentwithpaypal?guid=" + guid);
                payment.setRedirectUrls(redirectUrls);

                // Create a payment by posting to the APIService
                // using a valid AccessToken
                // The return object contains the status;
                try {
                    createdPayment = payment.create(apiContext);
                    logger.info("Created payment with id = "
                            + createdPayment.getId() + " and status = "
                            + createdPayment.getState());
                    // ###Payment Approval Url
                    Iterator<Links> links = createdPayment.getLinks().iterator();
                    while (links.hasNext()) {
                        Links link = links.next();
                        if (link.getRel().equalsIgnoreCase("approval_url")) {
                            request.setAttribute("redirectURL", link.getHref());
                        }
                    }
                    //ResultPrinter.addResult(req, resp, "Payment with PayPal", Payment.getLastRequest(), Payment.getLastResponse(), null);
                    map.put(guid, createdPayment.getId());
                } catch (PayPalRESTException e) {
                    e.printStackTrace();
                    //ResultPrinter.addResult(req, resp, "Payment with PayPal", Payment.getLastRequest(), null, e.getMessage());
                }
            }
        } catch (Exception e) {
            logger.error("Create Payment Exception ");
            e.printStackTrace();
        }
        return createdPayment;
    }

When I click on Paypal Checkout button. Client code trying to access my create payment api http://localhost/api/createpayment . I am getting response as 403 forbidden. I tried to access this API using POST man client, that is working fine. I can't figure out whats going wrong from my side.

The problem might be from the port that your spring is running on.

Also if it the request is done from another domain make sure you have @CrossOrigin annotation.

@CrossOrigin
@RequestMapping(value = "/createpayment", method = RequestMethod.POST)
    public @ResponseBody 
    Payment createPayment(HttpServletRequest request, HttpServletResponse response) {
.....
...

Reference : https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM