Akamai Bypass (Java) - java

I am writing a bot to auto purchase items on a website (zalando).
Everything goes well from login to adding items to shopping cart but at the very end it doesn't work anyomore. It sends this error:
{ "edge_error": "halt", "ref_id": "18.57c51102.1663765843.299fc0e", "wait": 60, "feedback": { "email": true, "url": "", "recaptcha": { "enabled": false, "type": 0, "sitekey": "" } }}
I think it has something to do with their protection or just me missing a header or cookie or a delay... I honestly have no clue anymore
This is the code I use in the end (to checkout and generate a paypal link (post response)):
public void makePostJsonRequest(WebDriver driver, String eTag, String checkoutID)
{
retrieveCookiesMap(driver);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost postRequest = new HttpPost("https://www.zalando.be/api/checkout/buy-now");
postRequest.setHeader("authority", "www.zalando.be");
postRequest.setHeader("accept", "application/json");
postRequest.setHeader("accept-language", "en-US,en;q=0.9");
postRequest.setHeader("content-type", "application/json");
postRequest.setHeader("cookie", "language-preference=nl;" +
" Zalando-Client-Id=" + cookiesMap.get("Zalando-Client-Id") + ";" +
" ncx=f;" +
" _gcl_au=" + cookiesMap.get("_gcl_au") + ";" +
" sqt_cap=" + cookiesMap.get("sqt_cap") + ";" +
" _ga=" + cookiesMap.get("_ga") + ";" +
" _gid=" + cookiesMap.get("_gid") + ";" +
" bm_sz=" + cookiesMap.get("bm_sz") + ";" +
" ak_bms=" + cookiesMap.get("ak_bms") + ";" +
" _gat_zalga=1;" +
" mpulseinject=false;" +
" frsx=" + cookiesMap.get("frsx") + ";" +
" zsa=" + cookiesMap.get("zsa") + ";" +
" zsr=" + cookiesMap.get("zsr") + ";" +
" zsi=" + cookiesMap.get("zsi") + ";" +
" bm_sv=" + cookiesMap.get("bm_sv") + ";" +
" _abck=" + cookiesMap.get("_abck") + ";");
postRequest.setHeader("origin", "https://www.zalando.be");
postRequest.setHeader("referer", "https://www.zalando.be/checkout/confirm");
postRequest.setHeader("sec-ch-ua", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"");
postRequest.setHeader("sec-ch-ua-mobile", "?0");
postRequest.setHeader("sec-ch-ua-platform", "\"Linux\"");
postRequest.setHeader("sec-fetch-dest", "empty");
postRequest.setHeader("sec-fetch-mode", "cors");
postRequest.setHeader("sec-fetch-site", "same-origin");
postRequest.setHeader("user-agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36");
postRequest.setHeader("x-xsrf-token", cookiesMap.get("frsx"));
postRequest.setHeader("x-zalando-checkout-app", "web");
postRequest.setHeader("x-zalando-footer-mode", "desktop");
postRequest.setHeader("x-zalando-header-mode", "desktop");
eTag = StringUtils.chop(eTag);
eTag += "\\";
String jsonString = "{\"checkoutId\":\"" + checkoutID + "\"," +
"\"eTag\":" + "\"\\" + eTag + "\"" + "\"" + "}";
System.out.println(jsonString);
StringEntity entity = new StringEntity(jsonString);
postRequest.setEntity(entity);
long startTime = System.currentTimeMillis();
HttpResponse response = httpClient.execute(postRequest);
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Time taken : "+elapsedTime+"ms");
InputStream is = response.getEntity().getContent();
Reader reader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
while (true) {
try {
String line = bufferedReader.readLine();
if (line != null) {
builder.append(line);
} else {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(builder.toString());
System.out.println("****************");
} catch (Exception ex) {
ex.printStackTrace();
}
}

This means that Akamai (the provider that zalando uses for bot protection), has detected and stopped your request because it detected you as a bot. To avoid this "stop" you MUST send a valid _abck cookie, generated by passing sensor data to the zalando akamai endpoint( you can find using chrome devtools and analyzing the requests )

Related

Netsuite getting error while generating signature with filter

I am trying to create a RestAPI request to fetch details of a records with a filter 'START_WITH'. But every request I send is getting rejected with the error '401 Unauthorized. Invalid Signature'. But if I don't add the filter and only send the normal request, It gives correct response back.
My code for generating signature is:
public String generateOauthHeader(
String method, UserFields userFields, String baseUrl, String offset, String limit) {
long timestamp = new Date().getTime() / 1000;
String nonce = getAlphaNumericString();
ArrayList<String> parameters = new ArrayList<>();
parameters.add(
ApplicationConstants.CONSUMER_KEY
+ ApplicationConstants.EQUAL
+ userFields.getConsumerKey());
parameters.add(ApplicationConstants.NONCE + ApplicationConstants.EQUAL + nonce);
parameters.add(
ApplicationConstants.SIGNATURE_METHOD_KEY
+ ApplicationConstants.EQUAL
+ ApplicationConstants.SIGNATURE_METHOD_VAL);
parameters.add(ApplicationConstants.TIMESTAMP + ApplicationConstants.EQUAL + timestamp);
parameters.add(
ApplicationConstants.OAUTH_TOKEN + ApplicationConstants.EQUAL + userFields.getTokenId());
parameters.add(
ApplicationConstants.VERSION_KEY
+ ApplicationConstants.EQUAL
+ ApplicationConstants.VERSION_VAL);
if (offset != null) {
parameters.add(ApplicationConstants.OFFSET + ApplicationConstants.EQUAL + offset);
}
if (limit != null) {
parameters.add(ApplicationConstants.LIMIT_CLAUSE + ApplicationConstants.EQUAL + limit);
}
parameters.add("q" + ApplicationConstants.EQUAL + "companyname START_WITH COMP1234");
Collections.sort(parameters);
StringBuffer parametersList = new StringBuffer();
for (int i = 0; i < parameters.size(); i++) {
parametersList.append(((i > 0) ? ApplicationConstants.AMPERSAND : "") + parameters.get(i));
}
String signature = null;
try {
String signatureString =
method
+ ApplicationConstants.AMPERSAND
+ URLEncoder.encode(baseUrl, StandardCharsets.UTF_8)
+ ApplicationConstants.AMPERSAND
+ URLEncoder.encode(parametersList.toString(), StandardCharsets.UTF_8);
SecretKeySpec signingKey =
new SecretKeySpec(
(userFields.getConsumerSecret()
+ ApplicationConstants.AMPERSAND
+ userFields.getTokenSecret())
.getBytes(),
ApplicationConstants.HMACSHA256);
Mac m = Mac.getInstance(ApplicationConstants.HMACSHA256);
m.init(signingKey);
m.update(signatureString.getBytes());
byte[] res = m.doFinal();
signature = Base64Coder.encodeLines(res);
} catch (Exception e) {
e.printStackTrace();
}
return ApplicationConstants.OAUTH
+ ApplicationConstants.REALM
+ ApplicationConstants.EQUAL_START_QUOTES
+ userFields.getAccountId()
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.CONSUMER_KEY
+ ApplicationConstants.EQUAL_START_QUOTES
+ userFields.getConsumerKey()
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.OAUTH_TOKEN
+ ApplicationConstants.EQUAL_START_QUOTES
+ userFields.getTokenId()
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.SIGNATURE_METHOD_KEY
+ ApplicationConstants.EQUAL_START_QUOTES
+ ApplicationConstants.SIGNATURE_METHOD_VAL
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.TIMESTAMP
+ ApplicationConstants.EQUAL_START_QUOTES
+ timestamp
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.NONCE
+ ApplicationConstants.EQUAL_START_QUOTES
+ nonce
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.VERSION_KEY
+ ApplicationConstants.EQUAL_START_QUOTES
+ ApplicationConstants.VERSION_VAL
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.SIGNATURE
+ ApplicationConstants.EQUAL_START_QUOTES
+ URLEncoder.encode(signature, StandardCharsets.UTF_8)
+ ApplicationConstants.QUOTES;
}
Url generated without filter: https ://1212112-sb1.suitetalk.api.netsuite.com/services/rest/record/v1/customer/
Url generated with filter: https ://1212112-sb1.suitetalk.api.netsuite.com/services/rest/record/v1/customer?q="companyName START_WITH COMP1234"

How to run multiple get requests from one thread in java?

I want to set up a client with x connections, where each connection will send a new GET request to a different URL each random time.
So my approach is to create x threads, where each will send a GET request in a loop (till the program will terminate).
I was using Apache MultiThreadedHttpConnectionManager, where I set the number of possible connections as x.
ClientHandler(int numberOfClients) {
this.numberOfClients = numberOfClients;
connManager = new PoolingHttpClientConnectionManager();
HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(connManager);
connManager.setMaxTotal(numberOfClients);
CloseableHttpClient httpClient = clientBuilder.build();
generateMultiThreadedClient(httpClient);
}
private void generateMultiThreadedClient(CloseableHttpClient httpClient) {
for (int i = 0; i < numberOfClients; i++) {
String clientUrl = URL + i;
HttpGet httpGet = new HttpGet(clientUrl);
ClientMultiThreaded clientMultiThreaded = new ClientMultiThreaded(httpClient,httpGet, i);
LOGGER.info(CLIENT_LOG + "A new thread for clientId " + i + " was created.");
clientMultiThreaded.start();
LOGGER.info(CLIENT_LOG + "Thread for clientId " + i + " started..");
}
}
And this is my run() method of the thread.
ClientMultiThreaded(CloseableHttpClient httpClient, HttpGet httpGet, int clientId) {
this.httpClient = httpClient;
this.clientId = clientId;
this.httpGet = httpGet;
randomGenerator = new Random();
}
#Override
public void run() {
try{
// Execute request for the first time
executeRequest(httpGet);
while (true) {
int timeToSleep = randomGenerator.nextInt(BOUND_LIMIT) + 1;
LOGGER.info(CLIENT_LOG + "Thread id " + clientId + " went to sleep for " + timeToSleep / 1000 + " seconds");
sleep(timeToSleep);
LOGGER.info(" ------- This is a test log printing for clientId: " +clientId);
executeRequest(httpGet);
}
}catch(Exception e) {
LOGGER.info(e.getMessage());
}
}
private void executeRequest(HttpGet httpGet) throws IOException {
CloseableHttpResponse response = httpClient.execute(httpGet);
LOGGER.info(CLIENT_LOG + "clientId " + clientId + " sent get request to URL " + httpGet.getURI());
statusCode = this.response.getStatusLine().getStatusCode();
LOGGER.info(CLIENT_LOG + "Status received for clientId " + clientId + " is: " + statusCode);
}
The problem is that I actually get 2 GET requests sent and then it stops.
You need to close response, use try with resources
Use following code:
private void executeRequest(HttpGet httpGet) throws IOException {
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
LOGGER.info(CLIENT_LOG + "clientId " + clientId + " sent get request to URL " + httpGet.getURI());
statusCode = this.response.getStatusLine().getStatusCode();
LOGGER.info(CLIENT_LOG + "Status received for clientId " + clientId + " is: " + statusCode);
}
}

Twitter pagination for home_timeline API not working

I am using twitter home_timeline API for showing tweets.For first time I run this it works fine, but when I call it again (pull to load more), it doesn't responds. I am passing auth headers and in params I passed count, it doesn't worked too.
I don't know where am I stuck..
Here is code for pulling tweets:
if (auth != null && auth.token_type.equals("bearer")) {
HttpGet httpget = new HttpGet(TwitterStreamURL);
String oAuthConsumerKey = CONSUMER_KEY;
String oAuthConsumerSecret = CONSUMER_SECRET;
String oAuthAccessToken = HomeActivity.twitter_access_token;
String oAuthAccessTokenSecret = HomeActivity.twitter_access_token_secret;
String oAuthNonce = String.valueOf(System.currentTimeMillis());
String oAuthSignatureMethod = "HMAC-SHA1";
String oAuthTimestamp = time();
String oAuthVersion = "1.0";
String signatureBaseString1 = methods;
String signatureBaseString2 = TwitterStreamURL;
String signatureBaseString3Templ = "oauth_consumer_key=%s&oauth_nonce=%s&oauth_signature_method=%s&oauth_timestamp=%s&oauth_token=%s&oauth_version=%s";
String signatureBaseString3 = String.format(signatureBaseString3Templ,
oAuthConsumerKey,
oAuthNonce,
oAuthSignatureMethod,
oAuthTimestamp,
oAuthAccessToken,
oAuthVersion);
String signatureBaseStringTemplate = "%s&%s&%s";
try {
signatureBaseString = String.format(signatureBaseStringTemplate,
URLEncoder.encode(signatureBaseString1, "UTF-8"),
URLEncoder.encode(signatureBaseString2, "UTF-8"),
URLEncoder.encode(signatureBaseString3, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
compositeKey = URLEncoder.encode(oAuthConsumerSecret, "UTF-8") + "&" + URLEncoder.encode(oAuthAccessTokenSecret, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
String oAuthSignature = computeSignature(signatureBaseString, compositeKey);
oAuthSignatureEncoded = URLEncoder.encode(oAuthSignature, "UTF-8");
String authorizationHeaderValueTempl = "OAuth oauth_consumer_key=\"%s\", oauth_nonce=\"%s\", oauth_signature=\"%s\", oauth_signature_method=\"%s\", oauth_timestamp=\"%s\", oauth_token=\"%s\", oauth_version=\"%s\"";
String authorizationHeaderValue = String.format(authorizationHeaderValueTempl,
oAuthConsumerKey,
oAuthNonce,
oAuthSignatureEncoded,
oAuthSignatureMethod,
oAuthTimestamp,
oAuthAccessToken,
oAuthVersion);
} catch (Exception e) {
e.printStackTrace();
}
String vf = "oauth_consumer_key=" + oAuthConsumerKey + ",oauth_signature_method=" + oAuthSignatureMethod + ",oauth_timestamp=" + oAuthTimestamp + ",oauth_nonce=" + oAuthNonce + ",oauth_version=" + oAuthVersion + ",oauth_token=" + oAuthAccessToken + ",oauth_signature=" + oAuthSignatureEncoded + "";
httpget.setHeader("Authorization", "OAuth " + "oauth_consumer_key=" + oAuthConsumerKey + ",oauth_signature_method=" + oAuthSignatureMethod + ",oauth_timestamp=" + oAuthTimestamp + ",oauth_nonce=" + oAuthNonce + ",oauth_version=" + oAuthVersion + ",oauth_token=" + oAuthAccessToken + ",oauth_signature=" + oAuthSignatureEncoded + "");
httpget.setHeader("Content-Type", "application/json");
// update the results with the body of the response
checkTwitRes = true;
results = getResponseBody(httpget);
}
div {
color:#000;
font-weight:800
}
p {
color:red;
background:url("mypicture.png")
}

JSP file upload. Conversion from FTP to SFTP

I have a JSP page which contains a link to upload a file. Initially the file transfer was happening using FTP. The server seems to transfer the file from client using the FTP only. I require to change the code to support SFTP now. Like the server initiated an FTP session on the client machine, is it possible for SFTP as well? here is the client code:
FTPClient client = new FTPClient();
FTPClient clientUser = new FTPClient(); //From ftp location (user saves file here)
try { //Location where user chooses file from
eas_user_import_ip_address_val = resovleJNDIResource.resolveJNDIString(eas_user_import_ip_address_tx);
eas_user_import_id_val = resovleJNDIResource.resolveJNDIString(eas_user_import_id_tx);
eas_user_import_pwd_val = resovleJNDIResource.resolveJNDIString(eas_user_import_pwd_tx);
eas_user_file_prefix_val= resovleJNDIResource.resolveJNDIString(eas_user_file_prefix_tx);
eas_user_file_prefix_val= eas_user_file_prefix_val.trim();
clientUser.connect(eas_user_import_ip_address_val);
int replyUser = clientUser.getReplyCode();
if(!FTPReply.isPositiveCompletion(replyUser)) {
ENTADJRuntime.getInstance().logError("FTPService", "Error connecting to:" + eas_user_import_ip_address_val + " reply code:" + replyUser);
clientUser.disconnect();
return false;
}
boolean loginUser = clientUser.login(eas_user_import_id_val, eas_user_import_pwd_val);
if (!loginUser) {
ENTADJRuntime.getInstance().logError("FTPService", "Error logging in to:" + eas_user_import_id_val);
return false;
}
//Location where file gets copied to.
eas_import_ip_address_val = resovleJNDIResource.resolveJNDIString(eas_import_ip_address_tx);
eas_import_id_val = resovleJNDIResource.resolveJNDIString(eas_import_id_tx);
eas_import_pwd_val = resovleJNDIResource.resolveJNDIString(eas_import_pwd_tx);
eas_part_file_prefix_val = resovleJNDIResource.resolveJNDIString(eas_part_file_prefix_tx);
eas_p2p_file_prefix_val = resovleJNDIResource.resolveJNDIString(eas_p2p_file_prefix_tx);
client.connect(eas_import_ip_address_val);
int reply = client.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)) {
ENTADJRuntime.getInstance().logError("FTPService", "Error connecting to:" + eas_import_ip_address_val + " reply code:" + reply);
client.disconnect();
return false;
}
boolean login = client.login(eas_import_id_val, eas_import_pwd_val);
if (!login) {
ENTADJRuntime.getInstance().logError("FTPService", "Error loging in to:" + eas_import_id_val);
return false;
}
//Loged in to From and To locations. Now transfer file
clientUser.setFileType(FTP.ASCII_FILE_TYPE);
clientUser.enterLocalActiveMode(); //from example
String originalFileName = fileName;
fileName = eas_user_file_prefix_val+fileName;
InputStream ip = clientUser.retrieveFileStream(fileName);
String issueIdStr = StringHelper.prepad(issueId + "", 10, '0');
String headerRecord = "HEADER " + adjPlatformCd + issueIdStr + batchId + " Original file : " + fileName;
String trailerRecord = "TRAILER " + adjPlatformCd + issueIdStr + batchId + " Server file : " + eas_file_prefix_val + dt_tm_siz + ".csv";
client.setFileType(FTP.ASCII_FILE_TYPE);
//First store file as ".tmp". First header then data followed by trailer
boolean retValue = client.storeFile(eas_file_prefix_val + dt_tm_siz + ".tmp", new ByteArrayInputStream(headerRecord.getBytes()));
if (!retValue) {
ENTADJRuntime.getInstance().logError("FTPService", "Error creating:" + eas_file_prefix_val + dt_tm_siz + ".tmp");
return false;
}
retValue = client.appendFile(eas_file_prefix_val + dt_tm_siz + ".tmp", ip);
if (!retValue) {
ENTADJRuntime.getInstance().logError("FTPService", "Error append 1:" + eas_file_prefix_val + dt_tm_siz + ".tmp");
return false;
}
ip.close();
retValue = client.appendFile(eas_file_prefix_val + dt_tm_siz + ".tmp", new ByteArrayInputStream(trailerRecord.getBytes()));
if (!retValue) {
ENTADJRuntime.getInstance().logError("FTPService", "Error append 2:" + eas_file_prefix_val + dt_tm_siz + ".tmp");
return false;
}
boolean commandOK=clientUser.completePendingCommand(); // this command lets next few ftp commands proces successfully
// place user file in PROCESSED folder. Append issue id, batch #, date and time if file length is < 230
String renamedUserFileName = eas_user_file_prefix_val+ "PROCESSED\\" + originalFileName.substring(0, originalFileName.lastIndexOf(".csv")) + "_" + issueId + "_" + batchId.trim() + dt_tm_siz + ".csv";
String someSiteCommand = "RNFR " + fileName; //rename from
reply = clientUser.sendCommand(someSiteCommand);
someSiteCommand = "RNTO " + renamedUserFileName; //rename to
reply = clientUser.sendCommand(someSiteCommand);
if(!FTPReply.isPositiveCompletion(reply)) {
ENTADJRuntime.getInstance().logError("FTPService", "Error renaming:" + fileName + " reply code:" + reply);
return false;
}
someSiteCommand = "RNFR " + eas_file_prefix_val + dt_tm_siz + ".tmp"; //rename from
reply = client.sendCommand(someSiteCommand);
someSiteCommand = "RNTO " + eas_file_prefix_val + dt_tm_siz + ".csv"; //rename to
reply = client.sendCommand(someSiteCommand);
if(!FTPReply.isPositiveCompletion(reply)) {
ENTADJRuntime.getInstance().logError("FTPService", "Error renaming:" + eas_file_prefix_val + dt_tm_siz + ".tmp" + " reply code:" + reply);
return false;
}
client.logout();
clientUser.logout();
Like the server initiated an FTP session on the client machine, is it possible for SFTP as well? here is the client code:
SFTP is a completely different protocol than FTP and you probably cannot reuse any FTP specific code. It might be that you've meant FTPS instead which is FTP extended with TLS. If this is supported depends on the setup of the server, that is it is not enough to only change the client code. As long as the server supports it you can use it with Java, see for example Secure FTP with org.apache.commons.net.ftp.FTPClient

Integrate Paypal in Web Application using Java

I want to integrate paypal in my web application. I am using RESTEasy API for restful requests. I want to know that how to integrate paypal in my application. I have dowonloaded paypal java sdk from their web site but right now I have no good applicaion which will help me to integrate paypal in my app. Can anybody suggest any site which shows step by step inegration of paypal in website or simple to understand ?
Paypal offers a few examples and even a wizard that generates you some code.
After the previous links gone offline start with this small tutorial: https://developer.paypal.com/docs/checkout/integrate/#
We have to follow the below step for configuring paypal in java web application.Here i have shown the configuration for Paypal to Paypal and CreditCard to Paypal payment.
1.create one sandbox account.
2.create web application.
3.Integrate the following struts2 action with your code.If you want to use with any other then just take methods and use directly.
public class PaypalAction extends ActionSupport implements SessionAware {
private static final long serialVersionUID = 1L;
private String resultString;
private String token;
#SuppressWarnings("rawtypes")
private Map finalMap = new HashMap();
public void paypalPay() {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
Integer payPercent = 10;
Map result = new HashMap();
String data1 = "";
try {
data1 = URLEncoder.encode("USER", "UTF-8") + "="+ URLEncoder.encode("Sandbox UserName","UTF-8");
data1 += "&" + URLEncoder.encode("PWD", "UTF-8") + "="+ URLEncoder.encode("Sandbox Password", "UTF-8");
data1 += "&" + URLEncoder.encode("SIGNATURE", "UTF-8") + "="+ URLEncoder.encode("Sandbox Signature","UTF-8");
data1 += "&" + URLEncoder.encode("METHOD", "UTF-8") + "="+ URLEncoder.encode("SetExpressCheckout", "UTF-8");
data1 += "&" + URLEncoder.encode("RETURNURL", "UTF-8") + "=" + URLEncoder.encode(request.getRequestURL().toString().replaceAll(request.getServletPath(), "") + "/successPage","UTF-8");
data1 += "&" + URLEncoder.encode("CANCELURL", "UTF-8") + "="+ URLEncoder.encode(request.getRequestURL().toString().replaceAll(request.getServletPath(), "") + "/failurePage", "UTF-8");
data1 += "&" + URLEncoder.encode("VERSION", "UTF-8") + "="+ URLEncoder.encode("104.0", "UTF-8");
data1 += "&" + URLEncoder.encode("AMT", "UTF-8")+ "=" + URLEncoder.encode("10", "UTF-8");
data1 += "&" + URLEncoder.encode("CURRENCYCODE", "UTF-8") + "=" + URLEncoder.encode("USD", "UTF-8");
data1 += "&" + URLEncoder.encode("L_NAME0", "UTF-8") + "=" + URLEncoder.encode("Sample Test", "UTF-8");
data1 += "&" + URLEncoder.encode("L_AMT0", "UTF-8") + "=" + URLEncoder.encode("10", "UTF-8");
data1 += "&" + URLEncoder.encode("CUSTOM", "UTF-8") + "="+ URLEncoder.encode("Thank You For business","UTF-8");
data1 += "&" + URLEncoder.encode("DESC", "UTF-8") + "=" + URLEncoder.encode("Product Details", "UTF-8");
data1 += "&" + URLEncoder.encode("NOSHIPPING", "UTF-8") + "="+ URLEncoder.encode("1", "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
result = post(data1);
Iterator<?> iter = result.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mEntry = (Map.Entry) iter.next();
}
if(result!=null){
token = (String) result.get("TOKEN");
String url = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express"+ "-" + "checkout&token=" + (String) result.get("TOKEN");
try {
response.sendRedirect(url);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String successPage() {
HttpServletRequest request = ServletActionContext.getRequest();
String payerID = request.getParameter("PayerID");
String token=request.getParameter("token");
doPaypalPayment(payerID,token);
return "success";
}
public String failurePage()
{
return "failurePage";
}
public void doPaypalPayment(String payerID, String token2) {
Map result = new HashMap();
String data = "";
try {
data1 = URLEncoder.encode("USER", "UTF-8") + "="+ URLEncoder.encode("Sandbox UserName","UTF-8");
data1 += "&" + URLEncoder.encode("PWD", "UTF-8") + "="+ URLEncoder.encode("Sandbox Password", "UTF-8");
data1 += "&" + URLEncoder.encode("SIGNATURE", "UTF-8") + "="+ URLEncoder.encode("Sandbox Signature","UTF-8");
data += "&" + URLEncoder.encode("METHOD", "UTF-8") + "="+ URLEncoder.encode("DoExpressCheckoutPayment", "UTF-8");
data += "&" + URLEncoder.encode("PAYERID", "UTF-8") + "="+ URLEncoder.encode(payerID, "UTF-8");
data += "&" + URLEncoder.encode("PAYMENTACTION", "UTF-8") + "="+ URLEncoder.encode("Sale", "UTF-8");
data += "&" + URLEncoder.encode("TOKEN", "UTF-8") + "="+ URLEncoder.encode(token2, "UTF-8");
data += "&" + URLEncoder.encode("AMT", "UTF-8") + "="+ URLEncoder.encode("10", "UTF-8");
data += "&" + URLEncoder.encode("VERSION", "UTF-8") + "="+ URLEncoder.encode("104.0", "UTF-8");
data += "&" + URLEncoder.encode("CURRENCYCODE", "UTF-8") + "="+ URLEncoder.encode("USD", "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
result = post(data);
}
public void deformatNVP()
{
try
{
String delims = "[&]";
String equals = "[=]";
String[] tokens = this.resultString.split(delims);
for(int i = 0; i < tokens.length; i++)
{
String[] newTokens = tokens[i].split(equals);
this.finalMap.put(URLDecoder.decode(newTokens[0], "UTF-8"), URLDecoder.decode(newTokens[1], "UTF-8"));
}
} catch (Exception e) {
System.out.println(e.toString());
}
//return finalMap;
}
public Map post(String data)
{
try
{
//Connect to the url
URL url = new URL("https://api-3t.sandbox.paypal.com/nvp");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//Post the data
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
this.resultString = rd.readLine();
deformatNVP();
wr.close();
rd.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return finalMap;
}
#Override
public void setSession(Map<String, Object> arg0) {
// TODO Auto-generated method stub
}
public void doPaypalPaymentWithCreditCard() {
try
{
//Load the caller service
//Create a new map to hold the result
Map result = new HashMap();
// Construct data request string
String data1 = URLEncoder.encode("USER", "UTF-8") + "="+ URLEncoder.encode("Sandbox UserName","UTF-8");
data1 += "&" + URLEncoder.encode("PWD", "UTF-8") + "="+ URLEncoder.encode("Sandbox Password", "UTF-8");
data1 += "&" + URLEncoder.encode("SIGNATURE", "UTF-8") + "="+ URLEncoder.encode("Sandbox Signature","UTF-8"); data += "&" + URLEncoder.encode("METHOD", "UTF-8") + "=" + URLEncoder.encode("DoDirectPayment", "UTF-8");
data += "&" + URLEncoder.encode("AMT", "UTF-8") + "=" + URLEncoder.encode("20.10", "UTF-8");
data += "&" + URLEncoder.encode("VERSION", "UTF-8") + "=" + URLEncoder.encode("80.0", "UTF-8");
data += "&" + URLEncoder.encode("IPADDRESS", "UTF-8") + "=" + URLEncoder.encode("192.168.1.0", "UTF-8");
data += "&" + URLEncoder.encode("PAYMENTACTION", "UTF-8") + "=" + URLEncoder.encode("Sale", "UTF-8");
data += "&" + URLEncoder.encode("CREDITCARDTYPE", "UTF-8") + "=" + URLEncoder.encode("Visa", "UTF-8");
data += "&" + URLEncoder.encode("ACCT", "UTF-8") + "=" + URLEncoder.encode("4532513511140817", "UTF-8");
data += "&" + URLEncoder.encode("EXPDATE", "UTF-8") + "=" + URLEncoder.encode("102014", "UTF-8");
data += "&" + URLEncoder.encode("CVV2", "UTF-8") + "=" + URLEncoder.encode("123", "UTF-8");
data += "&" + URLEncoder.encode("FIRSTNAME", "UTF-8") + "=" + URLEncoder.encode("Jason", "UTF-8");
data += "&" + URLEncoder.encode("LASTNAME", "UTF-8") + "=" + URLEncoder.encode("Michels", "UTF-8");
data += "&" + URLEncoder.encode("STREET", "UTF-8") + "=" + URLEncoder.encode("123", "UTF-8");
data += "&" + URLEncoder.encode("CITY", "UTF-8") + "=" + URLEncoder.encode("Papillion", "UTF-8");
data += "&" + URLEncoder.encode("STATE", "UTF-8") + "=" + URLEncoder.encode("NE", "UTF-8");
data += "&" + URLEncoder.encode("ZIP", "UTF-8") + "=" + URLEncoder.encode("68046", "UTF-8");
data += "&" + URLEncoder.encode("COUNTRYCODE", "UTF-8") + "=" + URLEncoder.encode("US", "UTF-8");
result = post(data);
//This will iterate through the entire response map
Iterator iter = result.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mEntry = (Map.Entry) iter.next();
System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
}
//Now that you have a response check to see if it is a success
String ack = "" + result.get("ACK");
if("Success".equals(ack))
{
System.out.println("Congratulations your transaction was a success");
}
else
{
System.out.println("There was an error with your request.");
}
}
catch (Exception e)
{
System.out.println(e.toString());
}
}//end of main function
}
This is working fine for me.Hope it will help to those who want to configure payment through paypal.

Categories