Paypal Java-SDK 支付问题
Paypal Java-SDK Payment issue
我正在尝试将 Papal 与我的 Spring Web 服务集成。我指的是 Advanced Server Integration and using this SDK Create Payment Sample.
这是我的客户端代码
<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>
这是我的网络服务
@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;
}
当我点击 Paypal Checkout 按钮时。尝试访问我的创建付款的客户端代码 api http://localhost/api/createpayment
。我收到 403 禁止回复。我尝试使用 POST man 客户端访问此 API,工作正常。我不知道我这边出了什么问题。
问题可能出在 端口 上,您的 spring 运行 开启。
此外,如果请求是从另一个域完成的,请确保您有 @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
我正在尝试将 Papal 与我的 Spring Web 服务集成。我指的是 Advanced Server Integration and using this SDK Create Payment Sample.
这是我的客户端代码
<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>
这是我的网络服务
@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;
}
当我点击 Paypal Checkout 按钮时。尝试访问我的创建付款的客户端代码 api http://localhost/api/createpayment
。我收到 403 禁止回复。我尝试使用 POST man 客户端访问此 API,工作正常。我不知道我这边出了什么问题。
问题可能出在 端口 上,您的 spring 运行 开启。
此外,如果请求是从另一个域完成的,请确保您有 @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