What is wrong with my paypal process to receive webhook notifications? - paypal

So this is what i did so far and it doesn't work, i will appreciate any help on the matter:
my goal is to post back any webhook event that occur in my paypal sandbox account.
So i have 2 accounts,
one that belongs to the receiver of the money, call it "facilitator",
one that belong to the "buyer",
Now in my account,there is a Sandbox webhooks configuration, so i entered the following:
https://csdieuqkzo.localtunnel.me
goes without saying that this comes from localtunnel.me.
So in my project, i do a simple sale using the api... this is the full create sale process:
$payer = new Payer();
$payer->setPayment_method('paypal');
//dd($payer);
$item = new Item();
$item->setQuantity('1');
$item->setName('benny');
$item->setPrice('7.41');
$item->setCurrency('USD');
$item->setSku('blah');
// //var_dump($item);
$items = new ItemList();
$items->addItem($item);
//var_dump($items);
$amountDetails = new Details();
$amountDetails->setSubtotal('7.41');
$amountDetails->setTax('0.03');
$amountDetails->setShipping('0.03');
$amount = new Amount();
$amount->setCurrency('USD');
$amount->setTotal('7.47');
$amount->setDetails($amountDetails);
$transaction = new Transaction();
$transaction->setAmount($amount);
$transaction->setDescription('This is the payment transaction description.');
$transaction->setItemList($items);
// echo '<pre>';
// print_r($transaction);
$RedirectUrls = new RedirectUrls();
$RedirectUrls ->setReturnUrl('https://csdieuqkzo.localtunnel.me/#/pricing');
$RedirectUrls ->setCancelUrl('https://csdieuqkzo.localtunnel.me/#/');
$payment = new Payment();
$payment->setIntent('sale');
$payment->setPayer($payer);
$payment->setTransactions(array($transaction));
$payment->setRedirectUrls($RedirectUrls);
// echo '<pre>';
// print_r($payment);
// dd();
$response = $payment->create($this->apiContext)->toarray();
Session::put('pay_id',$response['id']);
return Response::json($response);
After this there is a redirect to paypal, approval and when it comes back to my site, it excute with the following:
$payerId = Input::get('payerId');
$payment = Payment::get(Session::get('pay_id'), $this->apiContext);
//return $payerId;
$paymentExecution = new PaymentExecution();
$paymentExecution->setPayer_id($payerId);
$approval = $payment->execute($paymentExecution, $this->apiContext)->toarray();
return Response::json($approval);
Then an object is coming in saying the state of this transaction is approved, super, but i don't see any post to the webhook url i defined earlier...Now how did i test it?
I wrote a simple script to the post method of my root (in laravel):
Route::post('/',function(){
$myfile = fopen("bennyfile.txt", "a") or die("Unable to open file!");
$txt = "\nouterequested";
fwrite($myfile, $txt);
fclose($myfile);
});
Means whenever a post request is coming to the following url (in my case, a post to the root of:https://csdieuqkzo.localtunnel.me
I just want to add a line, that's it...but it doesn't update anything!...
for example if i do a post request from postman to the same place, all is good, but when a sale is approved, or any other action, nothing is happening.
Why?

This is a paypal document which helps you understand how webhooks works.
https://developer.paypal.com/docs/integration/direct/rest-webhooks-overview/
webhooks is http call back mechanism, ideally, you will need a valid url as your webhooks endpoint to test the webhooks notification message posted by PayPal. If you did sale using paypal wallet, you should get PayPal's webhooks notification message in JSON format at your endpoint. webhooks doesn't support direct credit card case yet.
If you want to test your listener script on local, you can use postman tool to post the sample message to your local url and test.

Using "localhost" isn't going to work because when PayPal's servers hits that address they're just hitting themselves. You need to setup DNS to point a domain to a virtual server on your local machine instead so that you can use a fully qualified domain name instead of localhost.

Related

php8 and Paypal IPN setup: Where does db INSERT upon successful handshake go?

Of the three files here- https://github.com/paypal/ipn-code-samples/tree/master/php
I have my Webhook URL set to the stock github version of- PaypalIPN.php (this validates successfully 100% of the time, if I use example_usage.php... Doesn't work. If I use both as Webhooks... Doesn't work).
From the Paypal button side of things I'm able to post my website's active user (call him $MrUser) with this:
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
"custom_id":"<?php echo $MrUser; ?>",
"description":"One hundred Webdollars",
"amount":
{
"currency_code":"USD",
"value":1.99
}
}]
});
},
Here's the SQL I need to run upon successful validation (I change $MrUser to $kitty for clarity's sake):
require 'sqlconfig.php';
$dsn = "mysql:host=$host;dbname=$db;charset=UTF8";
try {
$pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo $e->getMessage();
}
$hashedIP = $_SERVER['REMOTE_ADDR'];
$kitty = $_POST['custom']; // Not sure this is working yet, but this should give me $mrUser;
$sql = "INSERT INTO `Insert_upon_Paypal_success` (`date`,`hashedIP`,`username`,`webdollarAMT`) VALUES (now(),:hashedIP,:kitty,'100')";
$statement = $pdo->prepare($sql);
$statement->bindValue(':hashedIP', $hashedIP);
$statement->bindValue(':kitty', $kitty);
$inserted = $statement->execute();
I'm popping this into the PaypalIPN.php file upon validation, but, it doesn't work. Here's how I have it in there:
// Check if PayPal verifies the IPN data, and if so, return true.
if ($res == self::VALID) {
return true;
// i.e. putting all of the SQL above right here.
} else {
return false;
}
I'm guessing I need to put the SQL in a specific place that I'm missing, as per the layout of the PaypalIPN.php file... Please help!!
There is no reason to use IPN with current PayPal Checkout integrations. It is very old technology (20+ years) and should be deprecated soon.
Webhooks are a successor to IPN. However, even they are unnecessary for normal payment processing -- better used only if you need automated notifications of post-checkout exceptions such as refunds or disputes.
For normal PayPal payments, do not use either.
Instead, use the v2/checkout/orders API and make two routes (url paths) on your server, one for 'Create Order' and one for 'Capture Order'. You could use the (recently deprecated) Checkout-PHP-SDK for the routes' API calls to PayPal, or your own HTTPS implementation of first getting an access token and then doing the call with PHP's curl or similar. Both of these routes should return/output only JSON data (no HTML or text). Inside the 2nd route, when the capture API is successful you should verify the amount was correct and store its resulting payment details in your database (particularly purchase_units[0].payments.captures[0].id, which is the PayPal transaction ID) and perform any necessary business logic (such as reserving product or sending an email) immediately before forwarding return JSON to the frontend caller. In the event of an error forward the JSON details of it as well, since the frontend must handle such cases.
Pair those 2 routes with this frontend approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server . (If you need to send any additional data from the client to the server, such as an items array or selected options, add a body parameter to the fetch with a value that is a JSON string or object)

Retrieving IPP access token and access secret from paypal callback

I have a web app that uses a standard paypal shopping cart. What we want to do is to automatically record payments in QB online using Intuit QB API when paypal notifies our web site that the payment has completed.
The examples I have seen for obtaining the access token and secret are user-initiated. How can I get these inside the context of this paypal callback? I need them to happen automatically, and without a Request context from a user. I have some basic test code here that runs within the paypal callback.
//start a transaction
//start try block
//set our transaction record as paid
Token = ConfigurationManager.AppSettings["appToken"];
string consumerKey = ConfigurationManager.AppSettings["consumerKey"];
string consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
string companyID = ConfigurationManager.AppSettings["companyID"];
string accessToken = "??????";
string accessSecret = "?????";
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessSecret, consumerKey, consumerSecret);
ServiceContext context = new ServiceContext(appToken, companyID, IntuitServicesType.QBO, oauthValidator);
DataService service = new DataService(context);
Customer customer = new Customer();
//just a test example. without missing tokens, i don't get here.
customer.GivenName = "Mary";
customer.Title = "Ms.";
customer.MiddleName = "Jayne";
customer.FamilyName = "Cooper";
Customer resultCustomer = service.Add(customer) as Customer;
//complete transaction
//catch {rollback transaction}
There is no automated way to get access tokens and secret from your application.
You need to generate them for the first time using user interaction(C2QB- Connect to Quickbooks) and then save them for future use. These tokens are valid for a period of 6 months after which you will have to call Reconnect api to renew the tokens or do a C2QB interaction again to get new tokens.
https://developer.intuit.com/docs/0025_quickbooksapi/0010_getting_started/0030_integrate_your_app/disconnecting_from_quickbooks/0050_how_to_reconnect

PayPal SOAP API (.NET) - refund transaction error 10004 The transaction id is not valid

I'm using PayPal SOAP SDK for .NET to make a refund transaction.I try to call RefundTransaction method in SDK using transaction ID from SetExpressCheckout/DoExpressCheckout calls ( they work well ). PayPal API is returning 10004 error "Transaction id is not valid".
Here is my code:
PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
RefundTransactionRequestType refundTransactionRequest = new RefundTransactionRequestType();
refundTransactionRequest.TransactionID = transactionID;
refundTransactionRequest.PayerID = payerID;
refundTransactionRequest.InvoiceID = invoiceNumber;
refundTransactionRequest.RefundType = RefundType.FULL;
refundTransactionRequest.Amount = new BasicAmountType(GetPayPalCurrency(currencyID), amount.ToString("F"));
var request = new RefundTransactionReq() { RefundTransactionRequest = refundTransactionRequest };
RefundTransactionResponseType refundTransactionResponse = service.RefundTransaction(request);
Please help.
Double check to make sure that you processed the DoExpressCheckout transaction as a sale and not an authorization. If it was an authorization, you will not be able to refund it. Also make sure you are using the transaction id that you received as the merchant, and not the transaction id you received as a buyer. The two transaction id's will be different. If you have checked both of these things and it still does not work, if you can provide the API response you are getting back that includes the TIMESTAMP and the CORRELATIONID I can take a look at it on my end.

How to pass item_number to IPN when using Adaptive Payment API call to make pay request on Paypal?

I am using adaptive api to make a chained payment. The code looks
ChainedPay chainedPay = new ChainedPay(numberOfReceivers);
//set values (such as return url, cancel url, ipn url etc for the chainedPay object
....
Receiver primaryReceiver = new Receiver();
// set the receiver's value such as amount etc.
...
chainedPay.setPrimaryReceiver(primaryReceiver);
Receiver rec1 = new Receiver();
//set the second receiver's value
...
chainedPay.addToSecondaryReceivers(rec1);
//Make the request
chainedPay.makeRequest(); like this:
I do get the IPN message back when the payment is approved. But I want to be able to send a value such as a transactionId that exists in my system in the pay request, and have the IPN post it back to me, so I can look up the transaction by its id in my ipn listener, and use that information to deliver digital good to the user. I can't figure out where to set that value in the pay request.
Before using adaptive payment api call, if I want to pass the transaction id to the IPN, I would set it in the item_number field in a field in the form of the buy button and that would get passed through. Is there something similar in the adaptive api?
Thanks,
Tim
Try using the trackingid parameter. I am using the XML version and I pass it as follows
sRequest.Append("</trackingId>");
sRequest.Append(trackingID);
sRequest.Append("</trackingId>"); You may get a property as tracking id in PayRequest class.
I am passing the orderId via the trackingId field in the PayRequest
Ex:
PayRequest payRequest = new PayRequest(requestEnvelope, actionType, cancelUrl, currencyCode, receiverList, returnUrl);
payRequest.ipnNotificationUrl = System.Configuration.ConfigurationManager.AppSettings["PaypalNotifyUrl"];
payRequest.trackingId = orderId.ToString();
Then in the IPN handler, I retrieve it from the Request object.

Paypal sandbox IPN return INVALID

I am trying IPN callback, using servlet. The code I am using is provided by paypal for verifying the ipn data. But every time i getting a INVALID response.
Here is the code:
Enumeration en = req.getParameterNames();
String str = "cmd=_notify-validate";
while (en.hasMoreElements()) {
String paramName = (String) en.nextElement();
String paramValue = req.getParameter(paramName);
//str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue,"UTF-8"); // for UTF-8 i set the encode format in my account as UTF-8
//str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue,"ISO-8859-1");// for ISO-8859-1 i set the encode format in my account as ISO-8859-1
str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue); //default as provided by paypal
}
URL u = new URL("http://www.sandbox.paypal.com/cgi-bin/webscr");
URLConnection uc = u.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter pw = new PrintWriter(uc.getOutputStream());
pw.println(str);
pw.close();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String res = in.readLine();
in.close();
if (res.equals("VERIFIED") || !res.equals("VERIFIED")) {
//Update database...
} else if (res.equals("INVALID")) {
//INVALID
}
I have checked all three possibilities provided by paypal in case paypal return INVALID as follow:
1) Missing Parameters - As I am send all the parameters no issue of missing parameters
2) Invalid URL. - I am using sandbox so URL is : http://www.sandbox.paypal.com/cgi-bin/webscr
3) Character encoding. - Tried with character encoding same as paypal account setting parameter encoding.
the request I am sending back to paypal using following parameters:
cmd=_notify-validate&last_name=User&test_ipn=1&address_name=Test+User&txn_type=web_accept&receiver_email=sellr1_1252495907_biz%40gmail.com&residence_country=US&address_city=San+Jose&payment_gross=&payment_date=01%3A55%3A04+Sep+26%2C+2009+PDT&address_zip=95131&payment_status=Completed&address_street=1+Main+St&first_name=Test&payer_email=buyer1_1252495751_per%40gmail.com&protection_eligibility=Eligible&payer_id=BXBKS22JQCUWL&verify_sign=AOMkeg7ofCL7FJfioyWA19uCxD4XAgZirsjiGh8cUy1fd2YAqBwOkkst&payment_type=instant&business=sellr1_1252495907_biz%40gmail.com&address_country_code=US&mc_fee=0.64&address_status=confirmed&transaction_subject=True+Up&quantity=1&notify_version=2.8&mc_currency=EUR&custom=&address_state=CA&payment_fee=&handling_amount=0.00&payer_status=verified&shipping=0.00&item_name=True+Up&tax=0.00&username=hannonj&charset=windows-1252&item_number=567&mc_gross=10.00&txn_id=7F456350BS7942738&receiver_id=MASSU6BSR9SC2&address_country=United+States
Please , can any one direct me to proper direction? I am not getting what is wrong the code or the URL or anything else. I tried all the possibilities. Please help me.
An “INVALID” message is due to the following reasons:
Check that your are posting your response to the correct URL, which is https://www.sandbox.paypal.com/cgi-bin/webscr or https://www.paypal.com/cgi-bin/webscr, depending on whether you are testing in the Sandbox or you are live, respectively.
Verify that your response to the test IPN message contains exactly the same variables and values as the test message and that they are in the same order as in the test message. Finally, verify that the original variables are preceded by a cmd=_notify-validate variable.
Ensure that you are encoding your response string and are using the same character encoding as used by the test IPN message. (for example, I can see that he is using letters with umlaut and other symbols like “/”, etc).
With regard to the last point, the merchant can try to change the encoding language in use in his PayPal account, following the steps below:
Login on you PayPal account
Click on Profile
Click on “My Selling Preferences” tab
Click on “PayPal Button Language Encoding” (at the end of the page)
Click on "Other Options"
Select from the drop down menu: UTF-8
Choose the same charset also for the second option, which is related to IPN
Click “Save”
If the issue persists, we recommend to review the script in use, PayPal has some IPN code samples available at: https://github.com/paypal/ipn-code-samples
For additional information I include the link: https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNTesting/#id091GFE00WY4
I'm pretty sure the URL to send to is just "www.sandbox.paypal.com", see chapter 4 of Sandbox User Guide, and well, this is what I put for my own code (incidentally, for live, it is also just "www.paypal.com", for their sample code)
Thank you guys for your reply.
ohhh I solved it at last.
Actually in notify URL I also added a username parameter. Paypal want the parameter values for IPN same as it return to the servlet.(You can get it as req.getParameterNames()). As I have username parameter extra, which is not known to paypal. Paypal was returning INVALID.
Remember paypal's sandbox has completely different credentials. You must have development account and be logged into development panel to use sandbox.
If you're testing Paypal IPN over SSL, you will have to use ssl://www.sandbox.paypal.com on the port 443
I ran into multiple problems layered on top of each other before I could get Paypal IPN working - it kept returning INVALID but was not specific about which part I was getting wrong, unfortunately.
Things I got wrong:
Sandbox - if you use the Sandbox you need to use the entire Sandbox environment. It requires creating a new, separate account on the Paypal Sandbox website. The Sandbox API credentials it sets up under your regular account are not enough. You then use that separate Paypal account to file fake transactions on the Paypal Sandbox website, and watch them come across IPN on the Sandbox endpoint. The need for this second account is not obvious or clear at all in setting up API access. Also, switching between Sandbox and Live requires more than switching the URL, you need to switch the credentials. So a simple compile flag alternating a string isn't going to cut it.
Live - if you use the Live environment a number of things will get in your way. For us, it took a long time for Paypal to open up "Business" access to us. It wouldn't provide us anything over the API until that was enabled. When we initially applied we were flatly denied with no explanation or timeline to resolve it. A month later ish of taking payments (with no API to keep us up to date with those payments) it seemed to just magically start working.
Code example - the code example provided by Paypal is outdated, and has some clear issues. Here's an example that uses modern TPL/async:
// Send the verification back to Paypal in the format Paypal requested
var verif = (HttpWebRequest)WebRequest.Create(ipnVerifyUrl);
verif.Method = "POST";
verif.ContentType = "application/x-www-form-urlencoded";
var param = req.BinaryRead(req.TotalBytes);
var sRequest = Encoding.ASCII.GetString(param);
sRequest = "cmd=_notify-validate&" + sRequest;
verif.ContentLength = sRequest.Length;
using (var streamOut = new StreamWriter(verif.GetRequestStream(), Encoding.ASCII))
{
await streamOut.WriteAsync(sRequest);
}
// Send it
using (var re = await verif.GetResponseAsync())
{
var s = await HttpWebRequestAsync.GetFullResponseStringAsync((HttpWebResponse)re);
// Log the response (s)
}
Besides this code actually working (This is exactly what we have in Production, with some of our logging library calls stripped out), this code won't freeze a thread while waiting on network.
The awaits allow the thread to step away while the network does its thing, both in writing the verification request to Paypal, and in receiving the response back, both of which could be a long time.