How to capture authorized PayPal payment automatically in paypal standard? - paypal

I want to implement paypal authorization and capture payment automatically. I have used paypal standard account. I have send payment request with authorization parameter.
<form:form commandName="paymentForm" id="paymentForm" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" name="paypal">
<form:input path="cmd" id="cmd" name="cmd" type="hidden" />
<form:input path="business" id="business" name="business" type="hidden" />
<form:input path="password" id="password" name="password" type="hidden" />
<form:input path="custom" id="custom" name="custom" type="hidden" />
<form:input path="item_name" id="item_name" name="item_name" type="hidden" />
<form:input path="amount" id="amount" name="amount" type="hidden" />
<form:input path="currencyCode" type="hidden" name="currency_code" value="EUR" />
<form:input path="rm" id="rm" name="rm" type="hidden" />
<%-- <form:input path="returnUrl" id="return" name="return" type="hidden" /> --%>
<form:input type="hidden" name="return" value="${paymentForm.returnUrl}" />
<form:input type="hidden" name="cancel_return" path="cancel_return" />
<form:input type="hidden" name="cert_id" path="certId" />
<form:input type="hidden" name="paymentaction" path="authorization">
</form:form>
Now I want to capture the payment by using sending Http request to paypal with transaction Id/ authorization Id. How can I do this?
Thanks In Advance
K.Lakshmi Priya

You would need to make an API call to the DoCapture API call.
If you haven't used PayPal's API calls before, I suggest reading the Getting Started guide as well.

The following java code make Capture the authorized payment by using DoCapture API Call
import com.paypal.sdk.core.nvp.NVPDecoder;
import com.paypal.sdk.core.nvp.NVPEncoder;
import com.paypal.sdk.exceptions.PayPalException;
import com.paypal.sdk.profiles.APIProfile;
import com.paypal.sdk.profiles.ProfileFactory;
import com.paypal.sdk.services.NVPCallerServices;
public class DoCapture {
public static final String DO_CAPTURE_METHOD = "DoCapture";
public static void main(String[] args) throws PayPalException {
APIProfile profile;
profile = ProfileFactory.createSignatureAPIProfile();
profile.setAPIUsername("API User Name");
profile.setAPIPassword("PWD");
profile.setSignature("API Signature");
// profile.setEnvironment("sandbox");
// profile.setSubject("");
// profile.setTimeout(timeout);
NVPEncoder encoder = new NVPEncoder();
NVPDecoder decoder = new NVPDecoder();
NVPCallerServices caller = new NVPCallerServices();
caller.setAPIProfile(profile);
encoder.add("METHOD", DO_CAPTURE_METHOD);
encoder.add("AUTHORIZATIONID", "8PR03910DP1572333");
encoder.add("COMPLETETYPE", "Complete");
encoder.add("AMT", "100");
encoder.add("CURRENCYCODE", "EUR");
String NVPRequest = encoder.encode();
String NVPResponse = caller.call(NVPRequest);
decoder.decode(NVPResponse);
System.out.println("PayPal Response :: "+NVPResponse);
}
}
For more detail refer https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/DoCapture_API_Operation_NVP/

In c# you can capture payment using following code.
public ActionResult CaptureAuthorization()
{
APIContext apiContext = Configuration.GetAPIContext();
try
{
Authorization authorization = Authorization.Get(apiContext, "6SY29185GS4409204");//Provide Payment Id returned after authorizing payment.
Capture capture = new Capture();
Amount captureAmount = new Amount();
captureAmount.currency = "USD";
captureAmount.total = "7";
capture.amount = captureAmount;
Capture responseCap = authorization.Capture(apiContext, capture);//Capture Payment
if (responseCap.state.ToLower() != "completed")
{
return View("Failure");
}
return View("Success");
}
catch (Exception ex)
{
return View("Failure");
}
}

Related

Salesforce Web-to-Lead form collecting UTM data after browsing multiple pages

I have a salesforce web-to-lead form that is set up to collect utm data, and it does.... if I dont leave the page.
Currently, I am not using sf web to lead form. If the user comes to site from an ad, the utm parameters are stored in a cookie and used if the user completes a form. It works perfectly.
I now am required to use sf web to lead forms. If I land directly on the page and never leave, the utm parameters in url are successfully collected in the form. If I leave page and return to form page, I can see the utm parameters stored in the cookie, but the form does not collect.
Please send help!!!!! I need to be able to navigate away from page and use stored cookie to populate the utm hidden form fields.
<form id="salesforceForm" method="POST" action="https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8">
<input name="oid" type="hidden" value="mySFID#">
<input name="retURL" type="hidden" value="myredirectlink.com">
<label for="first_name">First Name*</label> <input id="first_name" maxlength="40" name="first_name" required="" size="20" type="text">
<label for="last_name">Last Name*</label> <input id="last_name" maxlength="80" name="last_name" required="" size="20" type="text">
<label for="email">Email*</label> <input id="email" maxlength="80" name="email" required="" size="20" type="text">
<label for="company">Company*</label> <input id="company" maxlength="40" name="company" required="" size="20" type="text"> <label for="phone">Phone*</label> <input id="phone" maxlength="40" name="phone" required="" size="20" type="text">
<input id="utm_source" name="00N50000003KWmr" type="hidden" value="">
<input id="utm_medium" name="00N50000003KWn6" type="hidden" value="">
<input id="utm_campaign" name="00N50000003KWnB" type="hidden" value="">
<input id="utm_term" name="00N50000003KWnG" type="hidden" value="">
<input id="utm_content" name="00N50000003KWnL" type="hidden" value="">
<input name="btnSubmit" type="submit">
</form>
<script type="text/javascript">
function parseGET(param) {
var searchStr = document.location.search;
try {
var match = searchStr.match('[?&]' + param + '=([^&]+)');
if (match) {
var result = match[1];
result = result.replace(/\+/g, '%20');
result = decodeURIComponent(result);
return result;
} else {
return '';
}
} catch (e) {
return '';
}
}
document.getElementById('utm_source').value = parseGET('utm_source');
document.getElementById('utm_medium').value = parseGET('utm_medium');
document.getElementById('utm_campaign').value = parseGET('utm_campaign');
document.getElementById('utm_term').value = parseGET('utm_term');
document.getElementById('utm_content').value = parseGET('utm_content');
</script>
There's nothing here that actually sets the cookie, right? Or reads from it.
I've never actively used Google Tag Manager and you're saying something sets the cookie already...
My gut feel you need something like if(parseGET('utm_source') == ""), then use functions from https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
This helps?
let utm_source = parseGET('utm_source');
if(!utm_source){
utm_source = document.cookie
.split('; ')
.find(row => row.startsWith('utm_source='))
.split('=')[1];
}
document.getElementById('utm_source').value = utm_source;
?
Untested, you'll have to experiment and put right names of cookies.

PayPal PDT works in sandbox but not live

I am trying to add a Paypal Payments button onto our website. I have Auto Return and Payment Data Transfer turned on.
When I point to sandbox, everything works correctly and it returns to my website with the transaction id in the url.
When I point to production PayPal, no transaction id is returned. Payment does go through.
Here is the form code:
<form action="#VARIABLES.strHostAddress#" method="post" target="_top" id="testform">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="#VARIABLES.strBusinessEmail#">
<input type="hidden" name="item_name" value="#VARIABLES.strGiftDesignation# - #VARIABLES.strGiftDesignation2#">
<input type="hidden" name="amount" value="#VARIABLES.intPayAmt#">
<input type="hidden" name="first_name" value="#VARIABLES.strFirstName#">
<input type="hidden" name="last_name" value="#VARIABLES.strLastName#">
<input type="hidden" name="address1" value="#VARIABLES.strLine1#">
<input type="hidden" name="address2" value="#VARIABLES.strLine2#">
<input type="hidden" name="city" value="#VARIABLES.strCity#">
<input type="hidden" name="state" value="#VARIABLES.strState#">
<input type="hidden" name="zip" value="#VARIABLES.strPostalCode#">
<input type="hidden" name="email" value="#VARIABLES.strEmail#">
<input type="hidden" name="cancel_return" value="#VARIABLES.strCancelPage#">
<input type="hidden" name="return" value="#VARIABLES.strThankYouPage#">
<input type="hidden" name="rm" value="2">
</form>
where #VARIABLES.strHostAddress# is "https://www.paypal.com/cgi-bin/webscr" for live or "https://www.sandbox.paypal.com/cgi-bin/webscr" for sandbox.
Any suggestions or idea why this would happen?
I am including a step by step explanation that PayPal has on their developers website and the important part is that you get the "tx" value, and send it back with the PDT "Identity Token" which you can find on the PayPal account when you login to configure PDT.
The following steps illustrate the basic flow of a PDT transaction.
"A customer submits a payment.
PayPal sends the transaction ID of the payment through HTTP as a GET variable (tx). This information is sent to the Return URL you specified in your PayPal account profile.
Your return URL web page contains an HTML POST form that retrieves the transaction ID and sends the transaction ID and your unique PDT token to PayPal.
PayPal replies with a message indicating SUCCESS or FAIL. The SUCCESS message includes transaction details, one per line, in the = format. This key-value pair string is URL encoded."
Ok, I just found this GitHub link that gives various code versions of how to get the "tx" and use it and the Identity Key to get all the name value pairs and parse them. It has an example in each language. Just click on the file name.
// ASP .NET C#
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Web;
using System.Collections.Generic;
public partial class csPDTSample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// CUSTOMIZE THIS: This is the seller's Payment Data Transfer authorization token.
// Replace this with the PDT token in "Website Payment Preferences" under your account.
string authToken = "Dc7P6f0ZadXW-U1X8oxf8_vUK09EHBMD7_53IiTT-CfTpfzkN0nipFKUPYy";
string txToken = Request.QueryString["tx"];
string query = "cmd=_notify-synch&tx=" + txToken + "&at=" + authToken;
//Post back to either sandbox or live
string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
string strLive = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = query.Length;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(query);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
Dictionary<string,string> results = new Dictionary<string,string>();
if(strResponse != "")
{
StringReader reader = new StringReader(strResponse);
string line=reader.ReadLine();
if(line == "SUCCESS")
{
while ((line = reader.ReadLine()) != null)
{
results.Add(line.Split('=')[0], line.Split('=')[1]);
}
Response.Write("<p><h3>Your order has been received.</h3></p>");
Response.Write("<b>Details</b><br>");
Response.Write("<li>Name: " + results["first_name"] + " " + results["last_name"] + "</li>");
Response.Write("<li>Item: " + results["item_name"] + "</li>");
Response.Write("<li>Amount: " + results["payment_gross"] + "</li>");
Response.Write("<hr>");
}
else if(line == "FAIL")
{
// Log for manual investigation
Response.Write("Unable to retrive transaction detail");
}
}
else
{
//unknown error
Response.Write("ERROR");
}
}
}
PDT-Code-Samples on GitHub

How to Integrate PayUMoney Gate way in Ionic 3?

Actually, I need to implement the PayUMoney with Ionic 3. I know, I don't have proper plugin. But I need to integrate the PayUMoney processing with my Server and send the acknowledgement to ionic 3.Please Guide me to solve this issue.
I'm not sure if you have found the solution already, but this might help others looking for the answer.
So lets assume you have all the required post parameters(You either have it locally somehow or get it from your server).
this.paymentString = `
<html>
<body>
<form action="${this.post_url}" method="post" id="payu_form">
<input type="hidden" name="firstname" value="${this.firstname}"/>
<input type="hidden" name="email" value="${this.email}"/>
<input type="hidden" name="phone" value="${this.phone}"/>
<input type="hidden" name="surl" value="${this.surl}"/>
<input type="hidden" name="curl" value="${this.curl}"/>
<input type="hidden" name="furl" value="${this.furl}"/>
<input type="hidden" name="key" value="${this.key}"/>
<input type="hidden" name="hash" value="${this.hash}"/>
<input type="hidden" name="txnid" value="${this.txnid}"/>
<input type="hidden" name="productinfo" value="${this.productinfo}"/>
<input type="hidden" name="amount" value="${this.amount}"/>
<input type="hidden" name="service_provider" value="${this.service_provider}"/>
<button type="submit" value="submit" #submitBtn></button>
</form>
<script type="text/javascript">document.getElementById("payu_form").submit();</script>
</body>
</html>`;
console.log(this.paymentString);
this.paymentString = 'data:text/html;base64,' + btoa(paymentString);
So basically now you have a base64 html string which you can pass to your InAppBrowser(from ionic native).
Please find how to include InAppBrowser in your project from ionic native docs (PS: Include InAppBrowser in app.modules.ts as well).
constructor(private iab: InAppBrowser) { }
Next step is to open the your base64String inAppBrowser and listen for completion of the transaction.
const browser = this.iab.create(payString, "_self", {
location: 'no',
clearcache: 'yes',
hardwareback: 'no',
});
browser.on('loadstart').subscribe((event: InAppBrowserEvent) => {
if (event.url === this.surl) {
this.paymentSuccess();
} else if (event.url === this.furl) {
this.paymentFailure();
}
});
What you do in functions paymentSuccess and paymentFailure is up to you.
That is it, should work as required.
Read further if you intend to send json data in 'productinfo'
You need to convert it to htmlsafe characters.
So replace this line
<input type="hidden" name="productinfo" value="${this.productinfo}"/>
with
<input type="hidden" name="productinfo" value="${this.htmlEntities(this.productinfo)}"/>
and have a function to convert json data to html safe characters,
private htmlEntities(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}

Paypal gets the wrong amount value via the form

In below code I send via a variable different amounts to Paypal when using this form. All data is correct even the amount is correct when Element inspecting via browser. But when Paypal site is active I always get 1 amount value USD25.00. It should be different for each $pitch->option_value.
Each variable $pitch->option_value is correct filled at my site. But Paypal only sees 25.
What do i do wrong or forget to do?
$i = '1';
foreach($pitches as $pitch) {
if($i == 1) {
$month = __('Month','agent-plugin');
} else {
$month = __('Months','agent-plugin');
}
$content .= '<form id="GotoPaypal" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="charset" value="utf-8">
<input type="hidden" name="return" value="'.get_home_url().'/en/my-account/">
<input type="hidden" name="item_name" value="'.$i.' '.$month.'">
<input type="hidden" name="amount" value="'.$pitch->option_value.'">
<input type="hidden" name="currency_code" value="USD">
<a href="#!" onclick="event.preventDefault();document.getElementById(\'GotoPaypal\').submit();">
</form>';
$i++;
}
return $content;
Because the value for $month will always be the same, no matter what value $i will have...
if($i == 1) { $month="25" } else { $month="25" }
will do the same trick ;)
You definded $i as somekind static value, why?

How to pass undefined number of inputs to a form spring mvc

I'm creating an form which will contain a sort number of hidden inputs and I would like to pass it to my spring MVC server.
The form created will be something like that (not always I will have 3 input types.. I can have more or less than it, the user will set up this value):
<form id="submitCoordenadas" method="post" action="adicionaCorredores">
<button type="submit" id="saveCoordenadas" class="btn" value="Save">Enviar</button>
<input type="hidden" name="corredor" id="linha1" val="[Linha] Inicio: [1;1] Fim: [104;114]">
<input type="hidden" name="corredor" id="linha2" val="[Linha] Inicio: [113;1] Fim: [1;144]">
<input type="hidden" name="corredor" id="linha3" val="[Linha] Inicio: [113;1] Fim: [1;144]">
</form>
What I have tried so far is to create an object which has an List of Strings:
public class Corredores {
List<String> corredor;
........ (getters and setters)
}
and my Spring MVC server:
#RequestMapping("adicionaCorredores")
public String adicionaCorredores(Corredores valores) {
System.out.println("Valores: " + valores.getCorredor().get(0));
return "";
}
I'm not receiving anything on "valores" parameter.
How can I do it? How can I have an undetermined number of inputs in a form and receive it in my Spring MVC server?
I solved my problem..
First of all, I was committing a mistake in my form. Instead of inserting the attribute "value" to it, I was using "val". Now my form looks like this:
<form id="submitCoordenadas" method="post" action="adicionaCorredores">
<button type="submit" id="saveCoordenadas" class="btn" value="Save">Enviar</button>
<input type="hidden" name="corredor" id="linha1" val="[Linha] Inicio: [1;1] Fim: [104;114]">
<input type="hidden" name="corredor" id="linha2" val="[Linha] Inicio: [113;1] Fim: [1;144]">
<input type="hidden" name="corredor" id="linha3" val="[Linha] Inicio: [113;1] Fim: [1;144]">
</form>
Another thing I've done is change my controller to this:
#RequestMapping("adicionaCorredores")
public String adicionaCorredores(#RequestParam("corredor") String[] corredor) {
for(int i=0; i < corredor.length; i++) {
System.out.println("Valores: " + corredor[i]);
}
return "";
}
Instead of receiving an Object "Corredores", I'm just receiving an String array. Note that the name of this String array should be the same of the name given in the form
Hope it helps someone else!