jeudi 16 avril 2015

Spring, Paypal : Using sample code to make a test payment

I am working on a Spring-MVC application in which I would like to integrate paypal payment mechanism. As you can expect I have to use the java-api-sdk by Paypal and the sameples seem good, but I am having trouble integrating those samples in my code.


As an initial task I would like to integrate the sample java file into my project and make a test payment. I have already created an app in Paypal and have the client-id and secret for a sandbox to go on with. I need to understand how to use their code to make a test payment using PaymentWithPayPalServlet.


The github link for the project is here


I am interested in using the below code to make a test payment and once successful, I will modify it to suit my requirements once I understand how to call it from Controller.


PaymentWithPayPalServlet.java :



public class PaymentWithPayPalServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

private static final Logger LOGGER = Logger
.getLogger(PaymentWithPayPalServlet.class);
Map<String, String> map = new HashMap<String, String>();

public void init(ServletConfig servletConfig) throws ServletException {

InputStream is = PaymentWithPayPalServlet.class
.getResourceAsStream("resources/sdk_config.properties");
try {
PayPalResource.initConfig(is);
} catch (PayPalRESTException e) {
LOGGER.fatal(e.getMessage());
}

}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}

// ##Create
// Sample showing to create a Payment using PayPal
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
createPayment(req, resp);
req.getRequestDispatcher("response.jsp").forward(req, resp);
}

public Payment createPayment(HttpServletRequest req, HttpServletResponse resp) {
Payment createdPayment = null;
// ###AccessToken
// Retrieve the access token from
// OAuthTokenCredential by passing in
// ClientID and ClientSecret
APIContext apiContext = null;
String accessToken = null;
try {
accessToken = GenerateAccessToken.getAccessToken();

// ### 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 = new APIContext(accessToken);
// Use this variant if you want to pass in a request id
// that is meaningful in your application, ideally
// a order id.
/*
* String requestId = Long.toString(System.nanoTime(); APIContext
* apiContext = new APIContext(accessToken, requestId ));
*/
} catch (PayPalRESTException e) {
req.setAttribute("error", e.getMessage());
}
if (req.getParameter("PayerID") != null) {
Payment payment = new Payment();
if (req.getParameter("guid") != null) {
payment.setId(map.get(req.getParameter("guid")));
}

PaymentExecution paymentExecution = new PaymentExecution();
paymentExecution.setPayerId(req.getParameter("PayerID"));
try {
createdPayment = payment.execute(apiContext, paymentExecution);
ResultPrinter.addResult(req, resp, "Executed The Payment", Payment.getLastRequest(), Payment.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Executed The Payment", Payment.getLastRequest(), null, e.getMessage());
}
} else {

// ###Details
// Let's you specify details of a payment amount.
Details details = new Details();
details.setShipping("1");
details.setSubtotal("5");
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("7");
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("Ground Coffee 40 oz").setQuantity("1").setCurrency("USD").setPrice("5");
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(req.getScheme() + "://"
+ req.getServerName() + ":" + req.getServerPort()
+ req.getContextPath() + "/paymentwithpaypal?guid=" + guid);
redirectUrls.setReturnUrl(req.getScheme() + "://"
+ req.getServerName() + ":" + req.getServerPort()
+ req.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")) {
req.setAttribute("redirectURL", link.getHref());
}
}
ResultPrinter.addResult(req, resp, "Payment with PayPal", Payment.getLastRequest(), Payment.getLastResponse(), null);
map.put(guid, createdPayment.getId());
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Payment with PayPal", Payment.getLastRequest(), null, e.getMessage());
}
}
return createdPayment;
}
}


I am also posting contents of response.jsp, presuming I get the response there.


response.jsp



<script
src="http://ift.tt/1qRgvOJ"></script>
<script
src="http://ift.tt/1ri5oOa"></script>
<script
src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/scrollspy.min.js"></script>
<script>
$(document)
.ready(
function () {
$("#accordion .panel-collapse:last").collapse('toggle');

$(document.body)
.append(
'<footer class="footer"> <div class="container"> <div class="footer-div"> <ul class="footer-links"> <li> <a href="http://ift.tt/16bIwYE" target="_blank"><i class="fa fa-github"></i> Github</a></li><li> <a href="http://ift.tt/12Ptpko" target="_blank"><i class="fa fa-book"></i> REST API Reference</a> </li><li> <a href="http://ift.tt/1D7uHn0" target="_blank"><i class="fa fa-exclamation-triangle"></i> Report Issues </a> </li></ul> </div></div></footer>');

$(".prettyprint").each(function () {
if ($(this).html().trim() != '') {
try {
$(this).html(syntaxHighlight(JSON.stringify(JSON.parse($(this).html().trim()), null, 2)));
} catch (e) {
return false;
}
} else {
$(this).html('No Data');
}
});

});

/* http://ift.tt/1vsN6cv */
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '&lt;').replace(/>/g,
'&gt;');
return json
.replace(
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
if (match == '"id":') {
console.log("Matched ID" + match);
cls = 'key id';
}
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match
+ '</span>';
});
}
</script>
</head>
<body>
<%
List<String> responses = (List<String>) request
.getAttribute("responses");
List<String> requests = (List<String>) request
.getAttribute("requests");
List<String> messages = (List<String>) request
.getAttribute("messages");
List<String> errors = (List<String>) request.getAttribute("errors");
%>
<div class="row header">
<div class="col-md-5 pull-left">
<br/> <a href="index.html"><h1 class="home">&#10094;&#10094;
Back to Samples</h1></a><br/>
</div>
<br/>

<div class="col-md-4 pull-right">
<img
src="http://ift.tt/1D7uHn2"
class="logo" width="300"/>
</div>
</div>

<div class="panel-group" id="accordion" role="tablist"
aria-multiselectable="true">
<%
for (int i = 0; i < responses.size(); i++) {
String resp = responses.get(i);
String req = requests.get(i);
String message = messages.get(i);
String error = errors.get(i);
String errorClass = (error != null) ? "error" : null;
%>
<div class="panel panel-default">
<div class="panel-heading <%= errorClass %>" role="tab" id="heading-<%= i + 1 %>">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion"
href="#step-<%= i + 1 %>" aria-expanded="false"
aria-controls="step-<%= i + 1 %>"><%= i + 1 %>. <%= message %> <% if (error != null) { %>
(Failed)<% } %></a>
</h4>
</div>
<div id="step-<%= i + 1 %>" class="panel-collapse collapse"
role="tabpanel" aria-labelledby="heading-<%= i + 1 %>">
<div class="panel-body">
<%
if (request.getAttribute("redirectURL") != null) {
%>
<div>
<a href=<%=(String) request.getAttribute("redirectURL")%>>Redirect
to PayPal to approve the payment</a>
</div>
<%
}
%>
<div class="row hidden-xs hidden-sm hidden-md">
<div class="col-md-6">
<h4>Request Object</h4>
<pre class="prettyprint "><%= req %></pre>
</div>
<div class="col-md-6">
<h4 class="<%= errorClass %>">Response Object</h4>
<% if (error != null) { %>
<p class="error"><i class="fa fa-exclamation-triangle"></i> <%= error %>
</p>
<% } %>
<pre class="prettyprint "><%= resp %></pre>
</div>
</div>
<div class="hidden-lg">
<ul class="nav nav-tabs" role="tablist">
<li role="presentation"><a href="#step-<%= i + 1 %>-request"
role="tab" data-toggle="tab">Request</a></li>
<li role="presentation" class="active"><a
href="#step-<%= i + 1 %>-response" role="tab" data-toggle="tab">Response</a></li>
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane"
id="step-<%= i + 1 %>-request">
<h4>Request Object</h4>
<pre class="prettyprint "><%= req %></pre>
</div>
<div role="tabpanel" class="tab-pane active"
id="step-<%= i + 1 %>-response">
<h4>Response Object</h4>
<pre class="prettyprint "><%= resp %></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<% } %>
</div>
</body>
</html>


I would love to understand what they are trying to do and why not some simple methods which can be called directly. Thanks a lot.


Aucun commentaire:

Enregistrer un commentaire