Paypal Integration

Posted: January 4, 2013 in Java Posts
Tags: , , , , , , ,

Image representing PayPal as depicted in Crunc...

Basic Steps:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_NVPAPIOverview#id09C2EN00EHT
NVP API Method and Field Reference: http://www.paypalobjects.com/en_US/ebook/PP_NVPAPI_DeveloperGuide/Appx_fieldreference.html#2830894

Here you can generate your desire paypal source code:
https://www.paypal-labs.com/integrationwizard/ecpaypal/code.php

Process of payment using PayPal checkout :
1. First, we generate a unique token id from paypal for each transaction , then start the
payment by passing the token to the paypal site:
2. Next, Send the merchant or seller account details with API signature to the paypal site.
So buyer can transfer money to seller account.

PaymentAction.java

public String expressCheckout(){
HttpSession session=request.getSession();
System.out.println(“return url: “+PaymentConstants.returnURL);
CallShortcutExpressCheckout(PaymentConstants.paymentAmount,
PaymentConstants.currencyCodeType,PaymentConstants.paymentType,
.returnURL,PaymentConstants.cancelURL,session);
return “success”;
}

public HashMap CallShortcutExpressCheckout( String paymentAmount, String currencyCodeType, String paymentType, String returnURL, String cancelURL,HttpSession session)
{
session.setAttribute(“paymentType”, paymentType);
session.setAttribute(“currencyCodeType”, currencyCodeType);

/*
Construct the parameter string that describes the PayPal payment
the varialbes were set in the web form, and the resulting string
is stored in $nvpstr
*/

String nvpstr = “&Amt=” + paymentAmount +
“&PAYMENTACTION=” +paymentType+
“&ReturnUrl=” + URLEncoder.encode( returnURL ) +
“&CANCELURL=” + URLEncoder.encode( cancelURL ) +
“&CURRENCYCODE=” + currencyCodeType;

/*
Make the call to PayPal to get the Express Checkout token
If the API call succeded, then redirect the buyer to PayPal
to begin to authorize payment. If an error occured, show the
resulting errors
*/

HashMap nvp = httpcall(“SetExpressCheckout”, nvpstr);
String strAck = nvp.get(“ACK”).toString();
if(strAck !=null && strAck.equalsIgnoreCase(“Success”))
{
session.setAttribute(“TOKEN”, nvp.get(“TOKEN”).toString());
}
return nvp;
}

public HashMap CallMarkExpressCheckout( String paymentAmount, String currencyCodeType, String paymentType, String returnURL, String cancelURL,
String shipToName, String shipToStreet, String shipToCity, String shipToState,
String shipToCountryCode, String shipToZip, String shipToStreet2, String phoneNum,
HttpSession session)
{
session.setAttribute(“paymentType”, paymentType);
session.setAttribute(“currencyCodeType”, currencyCodeType);

/*
Construct the parameter string that describes the PayPal payment
the varialbes were set in the web form, and the resulting string
is stored in $nvpstr
*/

String nvpStr = “ADDROVERRIDE=1&Amt=” + paymentAmount + “&PAYMENTACTION=” + paymentType;
nvpStr = nvpStr + “&CURRENCYCODE=” + currencyCodeType +
“&ReturnUrl=” + URLEncoder.encode( returnURL ) +
“&CANCELURL=” + URLEncoder.encode( cancelURL );
nvpStr = nvpStr + “&SHIPTONAME=” + shipToName +
“&SHIPTOSTREET=” + shipToStreet +
“&SHIPTOSTREET2=” + shipToStreet2;
nvpStr = nvpStr + “&SHIPTOCITY=” + shipToCity +
“&SHIPTOSTATE=” + shipToState +
“&SHIPTOCOUNTRYCODE=” +shipToCountryCode;
nvpStr = nvpStr + “&SHIPTOZIP=” + shipToZip +
“&PHONENUM” + phoneNum;
/*
Make the call to PayPal to set the Express Checkout token
If the API call succeded, then redirect the buyer to PayPal
to begin to authorize payment. If an error occured, show the
resulting errors
*/
HashMap nvp = httpcall(“SetExpressCheckout”, nvpStr);
String strAck = nvp.get(“ACK”).toString();
if(strAck !=null && (strAck.equalsIgnoreCase(“Success”)
||strAck.equalsIgnoreCase(“SuccessWithWarning”)))
{
session.setAttribute(“TOKEN”, nvp.get(“TOKEN”).toString());
}
return nvp;
}

public HashMap httpcall( String methodName, String nvpStr)
{
String version = “2.3”;
String respText = “”;
HashMap nvp=null;
// Enter Seller paypal account details.
String gv_APISignature = “AagAlIIxsi4TWAcTDu.FFUfJmzyAAUH7fQ3qUuhoQQ-yynHN9wgtWUuL “;
String gv_APIUserName = “jajnas_1293170638_biz_api1.gmail.com”;
String gv_BNCode = “PP-ECWizard”;
String gv_APIPassword = “1293170653”;
String gv_Version = “2.3”;
String encodedData = “METHOD=” + methodName + “&VERSION=” + PaymentConstants.gv_Version + “&PWD=” + PaymentConstants.gv_APIPassword + “&USER=” + PaymentConstants.gv_APIUserName + “&SIGNATURE=” + PaymentConstants.gv_APISignature + nvpStr + “&BUTTONSOURCE=” + PaymentConstants.gv_BNCode;

try
{
Object gv_APIEndpoint = “https://api-3t.sandbox.paypal.com/nvp”;
URL postURL = new URL( (String) gv_APIEndpoint );
HttpURLConnection conn = (HttpURLConnection)postURL.openConnection();
// Set connection parameters. We need to perform input and output,
// so set both as true.
conn.setDoInput (true);
conn.setDoOutput (true);
// Set the content type we are POSTing. We impersonate it as
// encoded form data
conn.setRequestProperty(“Content-Type“, “application/x-www-form-urlencoded“);
conn.setRequestProperty( “User-Agent“, PaymentConstants.agent );
//conn.setRequestProperty( “Coentent-Typ”, type );
conn.setRequestProperty( “Content-Length“, String.valueOf( encodedData.length()) );
conn.setRequestMethod(“POST”);
// get the output stream to POST to.
DataOutputStream output = new DataOutputStream( conn.getOutputStream());
output.writeBytes( encodedData );
output.flush();
output.close ();
// Read input from the input stream.
DataInputStream in = new DataInputStream (conn.getInputStream());
int rc = conn.getResponseCode();
if ( rc != -1)
{
BufferedReader is = new BufferedReader(new InputStreamReader( conn.getInputStream()));
String _line = null;
while(((_line = is.readLine()) !=null))
{
respText = respText + _line;
}
nvp = deformatNVP(respText );
}
return nvp;
}
catch( IOException e )
{
// handle the error here
return null;
}
}
public HashMap deformatNVP( String pPayload ) throws IOException
{
HashMap nvp = new HashMap();
StringTokenizer stTok = new StringTokenizer( pPayload, “&”);
while (stTok.hasMoreTokens())
{
StringTokenizer stInternalTokenizer = new StringTokenizer( stTok.nextToken(), “=”);
if (stInternalTokenizer.countTokens() == 2)
{
String key = URLDecoder.decode( stInternalTokenizer.nextToken());
System.out.println(“Key”+key);
String value = URLDecoder.decode( stInternalTokenizer.nextToken());
nvp.put( key.toUpperCase(), value );
if(key.equals(“TOKEN”)){
String url=”https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=”+value;
response.sendRedirect(url);
}
}
}
return nvp;
}

PaymentPostBackAction.java //call this function on-click return url from paypal

public String handleResponse() throws Exception {
InvestorDetails investorDetails = (InvestorDetails) request.getSession().getAttribute(PaymentConstants.INVESTOR_DETAILS);
UsersDetails userDetails = (UsersDetails) request.getSession().getAttribute(PaymentConstants.USER_DETAILS);
User user=(User)investorDetails;
String status = request.getParameter(“status”);
String token = request.getParameter(“token”).toString();
HashMap nvp = GetShippingDetails(token, request.getSession());
String strAck = nvp.get(“ACK”).toString();
if(strAck != null && (strAck.equalsIgnoreCase(“Success”) || strAck.equalsIgnoreCase(“SuccessWithWarning”)))
{
String email = nvp.get(“EMAIL”).toString(); // ‘ Email address of payer.
String payerId = nvp.get(“PAYERID”).toString(); // ‘ Unique PayPal customer account identification number.
String payerStatus = nvp.get(“PAYERSTATUS”).toString(); // ‘ Status of payer. Character length and limitations: 10 single-byte alphabetic characters.
String firstName = nvp.get(“FIRSTNAME”).toString(); // ‘ Payer’s first name.
String lastName = nvp.get(“LASTNAME”).toString(); // ‘ Payer’s last name.
String cntryCode = nvp.get(“COUNTRYCODE”).toString(); // ‘ Payer’s country of residence in the form of ISO standard 3166 two-character country codes.
//confirmation of payment.
HashMap nvpreturn = ConfirmPayment(PaymentConstants.paymentAmount,request.getSession(),request);
String transactionId = nvpreturn.get(“TRANSACTIONID”).toString();
/*
‘ The information that is returned by the GetExpressCheckoutDetails call should be integrated by the partner into his Order Review
‘ page
*/
// Save Payment Details……..
if(nvpreturn != null){
//Long refId= null;
userService.registerUser(userDetails, investorDetails);
userService.saveRegistrationPreference(user);
UserPayment userPayment = new UserPayment();
userPayment.setRefno(String.valueOf(payerId));
userPayment.setStatus(status);
userPayment.setUppTransactionId(transactionId);// place of transactionId
userPayment.setUser(user);
userService.saveUserPaymentDetails(userPayment);
}
}
else
{
// Display a user friendly Error on the page using any of the following error information returned by PayPal
String ErrorCode = nvp.get(“L_ERRORCODE0”).toString();
String ErrorShortMsg = nvp.get(“L_SHORTMESSAGE0”).toString();
String ErrorLongMsg = nvp.get(“L_LONGMESSAGE0”).toString();
String ErrorSeverityCode = nvp.get(“L_SEVERITYCODE0”).toString();
request.setAttribute(“ErrorCode”, ErrorCode);
request.setAttribute(“ErrorShortMsg”, ErrorShortMsg);
request.setAttribute(“ErrorLongMsg”, ErrorLongMsg);
request.setAttribute(“ErrorSeverityCode”, ErrorSeverityCode);
userService.savePaymentFailureLog(user,token,”failure”);
return “failure”;
}
request.getSession().removeAttribute(PaymentConstants.INVESTOR_DETAILS);
request.getSession().removeAttribute(PaymentConstants.USER_DETAILS);
return “success”;
}
public HashMap ConfirmPayment( String finalPaymentAmount, HttpSession session, HttpServletRequest request)
{

/*’—————————————————————————-
‘—- Use the values stored in the session from the previous SetEC call
‘—————————————————————————-
*/
String token = session.getAttribute(“TOKEN”).toString();
String currencyCodeType = session.getAttribute(“currencyCodeType”).toString();
String paymentType = session.getAttribute(“paymentType”).toString();
String payerID = session.getAttribute(“PAYERID”).toString();
String serverName = request.getServerName();

String nvpstr = “&TOKEN=” + token + “&PAYERID=” + payerID + “&PAYMENTACTION=” + paymentType + “&AMT=” + finalPaymentAmount;
nvpstr = nvpstr + “&CURRENCYCODE=” + currencyCodeType + “&IPADDRESS=” + serverName;

/*Make the call to PayPal to finalize payment
If an error occured, show the resulting errors*/

HashMap nvp = httpcall(“DoExpressCheckoutPayment”, nvpstr);
return nvp;
}
public HashMap GetShippingDetails( String token, HttpSession session)
{
/*
Build a second API request to PayPal, using the token as the
ID to get the details on the payment authorization
*/

String nvpstr= “&TOKEN=” + token;

/*
Make the API call and store the results in an array. If the
call was a success, show the authorization details, and provide
an action to complete the payment. If failed, show the error
*/

HashMap nvp = httpcall(“GetExpressCheckoutDetails”, nvpstr);
String strAck = nvp.get(“ACK”).toString();
if(strAck !=null && (strAck.equalsIgnoreCase(“Success”) || strAck.equalsIgnoreCase(“SuccessWithWarning”)))
{
session.setAttribute(“PAYERID”, nvp.get(“PAYERID”).toString());
}
return nvp;
}

public HashMap httpcall( String methodName, String nvpStr)
{
String version = “2.3”;
String respText = “”;
HashMap nvp=null;
// enter Seller paypal account details.
String gv_APISignature = “AagAlIIxsi4TWAcTDu.FFUfJmzyAAUH7fQ3qUuhoQQ-yynHN9wgtWUuL “;
String gv_APIUserName = “jajnas_1293170638_biz_api1.gmail.com”;
String gv_BNCode = “PP-ECWizard”;
String gv_APIPassword = “1293170653”;
String gv_Version = “2.3”;
String encodedData = “METHOD=” + methodName + “&VERSION=” + PaymentConstants.gv_Version + “&PWD=” + PaymentConstants.gv_APIPassword + “&USER=” + PaymentConstants.gv_APIUserName + “&SIGNATURE=” + PaymentConstants.gv_APISignature + nvpStr + “&BUTTONSOURCE=” + PaymentConstants.gv_BNCode;

try
{
Object gv_APIEndpoint = “https://api-3t.sandbox.paypal.com/nvp”;
URL postURL = new URL( (String) gv_APIEndpoint );
HttpURLConnection conn = (HttpURLConnection)postURL.openConnection();

// Set connection parameters. We need to perform input and output,
// so set both as true.
conn.setDoInput (true);
conn.setDoOutput (true);

// Set the content type we are POSTing. We impersonate it as
// encoded form data
conn.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);
conn.setRequestProperty( “User-Agent”,PaymentConstants.agent );

//conn.setRequestProperty( “Content-Type”, type );
conn.setRequestProperty( “Content-Length”, String.valueOf( encodedData.length()) );
conn.setRequestMethod(“POST”);
// get the output stream to POST to.
DataOutputStream output = new DataOutputStream( conn.getOutputStream());
output.writeBytes( encodedData );
output.flush();
output.close ();
// Read input from the input stream.
DataInputStream in = new DataInputStream (conn.getInputStream());
int rc = conn.getResponseCode();
if ( rc != -1)
{
BufferedReader is = new BufferedReader(new InputStreamReader( conn.getInputStream()));
String _line = null;
while(((_line = is.readLine()) !=null))
{
respText = respText + _line;
}
nvp = deformatNVP( respText );
}
return nvp;
}
catch( IOException e )
{
// handle the error here
return null;
}
}
@SuppressWarnings(“unchecked”)
public HashMap deformatNVP( String pPayload ) throws IOException
{
HashMap nvp = new HashMap();
StringTokenizer stTok = new StringTokenizer( pPayload, “&”);
while (stTok.hasMoreTokens())
{
StringTokenizer stInternalTokenizer = new StringTokenizer( stTok.nextToken(), “=”);
if (stInternalTokenizer.countTokens() == 2)
{
String key = URLDecoder.decode( stInternalTokenizer.nextToken());
System.out.println(“Key”+key);
String value = URLDecoder.decode( stInternalTokenizer.nextToken());
nvp.put( key.toUpperCase(), value );
}
}
return nvp;
}
//End

Paypal Test account: //This is for testing the paypal payment while creating the test account for buyer as well as seller.

1. create paypal account: https://developer.paypal.com/ sign Up Now
2. click on “Test Account”: choose-> New test account: Preconfigured <-|
// create two account one for seller and one for buyer.
(Note: while creating the account note down the password and username.)

Advertisements
Comments

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s