PayPal Java-SDK付款问题



我正在尝试将教皇与我的春季Web服务集成。我正在引用高级服务器集成并使用此SDK创建付款样本。

这是我的客户端代码

<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>

这是我的Web服务

@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;
    }

当我单击贝宝结帐按钮时。客户代码试图访问我的创建付款API http://localhost/api/createpayment。我得到的回应是403禁止。我试图使用Post Man Client访问此API,这很好。我无法弄清楚我身边出了什么问题。

问题可能来自您的弹簧正在运行的 port

另外,如果该请求是从另一个域完成的,请确保您有@Crossorigin注释。

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

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

最新更新