PayPal REST API v2/checkout/orders does not redirect back after approval - paypal

I've never used PayPal before, it's not really popular here, and I'm confused by how the order and payment works. Can anyone explain it to me? I've read the documentation and I'm still confused.
To complete payer approval, use the approve link to redirect the
payer. The API caller has 3 hours (default setting, this which can be
changed by your account manager to 24/48/72 hours to accommodate your
use case) from the time the order is created, to redirect your payer.
Once redirected, the API caller has 3 hours for the payer to approve
the order and either authorize or capture the order.
I have created a working PHP curl call for this API in sandbox env according to the sample
https://developer.paypal.com/docs/api/orders/v2/#orders_create
The APIs I created before work like this:
Send a request to 3rd party payment
Get a response containing a checkout link
Redirect customer to link
Customer complete payment
3rd party send a request containing order and payment detail to a file/path on my server
My server receives the request and updates the order status/payment in my database
3rd party redirect the customer to my webpage
With PayPal, what I got so far is:
Send request containing order detail to /v2/checkout/orders
Get a response containing various links
Redirect my customer to the rel:approve checkout link
Log in to my sandbox customer account and pay using PayPal balance, click Continue
A popup message is shown: We're sending you back to xxx's Test Store to complete this purchase
The popup message is closed and I'm still at the same payment page with the Continue button as seen in the image

Send request containing order detail to /v2/checkout/orders
Get a response containing links
Redirect my customer to approve link
Step (3) is an old integration method, for websites using an old redirect-based flow. The preferred way to integrate PayPal uses no redirects. At all. Your website remains loaded in the background. Do the following:
Follow the Set up standard payments guide and make 2 routes on your server, one for 'Create Order' and one for 'Capture Order', documented here. Both routes should return only JSON data (no HTML or text). Inside the 2nd route, when the capture API is successful you should 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 sending confirmation emails or reserving product) immediately before forwarding your return JSON to the frontend caller.
Pair those 2 routes with the frontend approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server
If, for some odd and inexplicable reason, you insist on using the legacy flow with a full page redirect instead of what I just described above, you must include a redirect_url in your orders creation request, so that PayPal has somewhere to return to after the order is approved. Immediately when the return happens, capture the order with an API call and show the success/failure result to the customer. If you want an intervening order review step before capture, you can do this, but you must also edit your initial order creation request to change the verbiage of the last button at PayPal from "Pay Now" to "Continue" so that the user is clicking on something that corresponds to what the next step will be. application_context.user_action needs to be continue for this change.
Capturing an order will return a v2/payments object which is the completed transaction with its own ID for accounting and refund purposes. (The order ID is only used during payer approval, and unimportant otherwise)

I had this issue too, and I eventually got a solution from the documentation.
You have to add application_context.return_url to your request.
Attached is an example in PHP:
$postData = [
"intent" => "CAPTURE",
"purchase_units" => $purchase_units,
"application_context" => [
"return_url" => "",
"cancel_url" => "",
],
];
You can make a whole lot of customisations to the PayPal Payment page by adding the Application Context option, For a full list of the possible customisations, you can check up the official documentation Application Context Documentation

Related

PayPal - received cancel but the transaction was succesfull

On an e-commerce site in the payment page I used the new js sdk from paypal.
When the user clicks on paypal button a popup appears and the user performs the transaction in the popup.
When the transaction is over the popup closes and a callback is called to do what is needed.
If the user manually closes the popup, a CANCEL event is emitted and the transaction is considered canceled.
The problem I'm having is that sometimes I see on the logs that I receive the CANCEL event (meaning that the user has closed the popup) but on PayPal account the transaction is succesfull and correctly payed...
Is it possible that the user closes the popup just before paypal sends the confirmation back or something like that? Anyone knows how this can be handled?
Using the JS SDK alone is for very simple use cases. For an ecommerce site of any importance, the JS SDK should be combined with the v2/checkout/orders API. This way orders are always captured from the server and recorded when successful, and things happening on the client side won't be relevant nor interfere with accurate payment tracking.
Your question doesn't give technical details for your current integration, but here's how to go about making a correct one from scratch:
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 one of the (recently deprecated) Checkout-*-SDKs for the routes' API calls to PayPal, or your own HTTPS implementation of first getting an access token and then doing the call. 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)

Paypal PDT integration in .Net with Blazor

We are trying to integrate Paypal subscriptions with .Net web application done in Blazor.
We have created a button that allows the customer to enrol to a subscription defined in paypal business.
The customer can do the "payment" or "enrolment" successfully and it returns back to our web application with the specific URL that we defined.
This return URL contains just one parameter, called "token".
The problem is that we want to be syncronize paypal payments with our own control of payments implemented by us in the application, so we need to receive some other information in this URL like the transactionID or some identifier that we can use later to link with one customer.
We have configured paypal to support PDT.
When the customer finishes the enrolment to the subscription, the token returned to the URL i passed to our backend and with this, we try to get the some extra information.
We do a post to the url "https://www.sandbox.paypal.com/cgi-bin/webscr" passing as parameter the token that we received back from the transaction and our token as merchant in paypal.
Theorically, when doing this call, we should receive a response that contains "SUCCESS" and then, we should be able to extract some parameters configured in the PDT of paypal.
But, unfortunately, we always receive "FAIL"
Do you have any idea why does it happens?
Thank you very much in advance.
PDT returns are not reliable, as a payment can complete and the client return never happen for any number of reasons -- so PDT should never be used for anything important, and thus there is no reason for a well designed integration to bother attempting to verify them. Contents of a PDT is suitable for information purposes (display summary of success) to a customer only -- if you are doing anything else with PDT data, rethink your integration..
If you must continue such a very old checkout method that uses PDT as part of its process, a service such as IPN or Webhooks should be added on to receive a somewhat more reliable, direct post from PayPal with the payment information.
The best solution however, is to do neither of those things -- since adding on asynchronous notifications to an existing very old integration has its own disadvantages. Instead, discard your current integration completely as it's already about 4 generations old / 20 years old, and implement a new, current PayPal Checkout integration from scratch:
Follow the PayPal Checkout integration guide and make 2 routes (url paths) on your server, one for 'Create Order' and one for 'Capture Order'. Both of these routes should return 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 sending confirmation emails or reserving product) immediately before forwarding your 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)

API for completing PayPal one-time payments

I'm looking for ways to make a PayPal payment using PHP. I understand there are deprecated APIs and current one. so I've found several ways to do so. but lots documents lead me into labyrinth. I'm quite confuse de.g. client button rendering, how to call our PHP script/ what is a PayPal-Request-Id and to get it/ what can we do with a token from webscr ==> cmd=_express-checkout&token=EC-7BA65327KY8480517 and etc.
I tried to use a button on my page to submit some few paypal-required parameters using html form. The receiving php file formed payment record as need, then create order. I got the order-id, but what is it for? so I set up a new parameters, conformed the PayPal needs to create a payment. This give me 4 links, one I choose to get redirected for client logging in and continuing. with this one I got to landing page then I executed a payment but each payment on sandbox dashboard says pending.
I am then confused how to get completed payment. Right here there is my data with THB currency
{"id":"PAYID-MAKU2OI7RR56034B9692111L","intent":"sale","state":"created","payer":{"payment_method":"paypal"},"transactions":[{"amount":{"total":"1126.15","currency":"THB","details":{"subtotal":"979.26","tax":"146.89","shipping":"0.00","insurance":"0.00","handling_fee":"0.00","shipping_discount":"0.00"}},"description":"aonang to","custom":"0","invoice_number":"kbv.starlight_12","soft_descriptor":"MFWD","payment_options":{"allowed_payment_method":"INSTANT_FUNDING_SOURCE","recurring_flag":false,"skip_fmf":false},"item_list":{"items":[{"name":"MFWD","sku":"kbv.starlight_12","description":"aonang to ","price":"979.26","currency":"THB","tax":"146.89","quantity":1}]},"related_resources":[]}],"note_to_payer":"Contact us for any questions on your order.","create_time":"2021-01-30T12:12:40Z","links":[{"href":"https://api.sandbox.paypal.com/v1/payments/payment/PAYID-MAKU2OI7RR56034B9692111L","rel":"self","method":"GET"},{"href":"https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-1G552540DR9655320","rel":"approval_url","method":"REDIRECT"},{"href":"https://api.sandbox.paypal.com/v1/payments/payment/PAYID-MAKU2OI7RR56034B9692111L/execute","rel":"execute","method":"POST"}]}
Sandbox account interface screenshot
You mention the classic Express Checkout API and the deprecated v1/payments API, but the right solution is to use the current API, v2/checkout/orders
Create two routes on your server, one for 'Create Order' and one for 'Capture Order', documented here. These routes should return JSON data (and only JSON data) when called by an XHR/fetch.
Pair your two routes with the following approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server

PayPal payment to issue activation code

I have just created my first PayPal button and it is working correctly within sand box. I would like to know the best way (if possible) to issue a unique activation code on my return url ensuring that the user has definitely paid before they receive the code. I could manually email the code but wondered if the was any way of automating this using some sort of return value? Possibly returning to an aspx page which then reads from my database to get the next activation key and displays it?
Thanks
Garry
As you already know that PayPal doesn't provide such facility for delivering activation instantly but it does offer the Instant Payment Notification API (PayPal IPN) which can be used to build such a platform.
Here is a great article for that purpose only. https://www.codeproject.com/Articles/383207/Selling-software-using-PayPal-IPN-as-an-eCommerceenter link description here
The best way to handle that would be to use Instant Payment Notification (IPN).
Any time a transaction happens on your site (whether it's a payment, refund, cleared pending payment, dispute, etc.) the PayPal server will POST details about that transaction to a script you have sitting on your server.
This script can receive the data and process it accordingly allowing you to automate things like updating a database, generating email notifications, hitting 3rd party web services, delivering e-goods, etc.
If you want the activation code to be visible on the return URL you can look at Payment Data Transfer (PDT), which is just like IPN except that it's made for use with the return URL. It is not recommended to use this, though, for post-transaction processing because there is no guarantee the user will make it back to the return URL, for one, and also it wouldn't handle things like e-checks correctly.

PHP PayPal payment validation

I'm developing a site for a client, and he wants people to be able to buy licenses/support contracts via PayPal. What I'm stumped on is how I can make the payments secure. My current idea is to generate a random string using MD5 or whatever, plug this into a database, and send it along with the rest of the PayPal button code. When the payment is completed, the user is redirected to a PHP page where there is code to update their information in the database. The only thing stopping a hacker giving themselves a license/whatever without paying is the random hash, which can be found out using a sniffer of some sort, and plugged into the POST data returned by the PayPal code.
So. My question is this: How do I execute custom PHP code only on a successful PayPal payment, without leaving any loopholes open for the more evil users of the interwebs?
I think you should use a Payment Gateway such as PayFlow
if you're on the website ready to pay, there maybe a session already with your user logged in?
in this scenario, when the user returns back to the website, you can check you have a particular session variable and if it exists, you do the following
1) check your session, do you have a user logged in? should still be logged in if you just visited paypal a few minutes ago.
2) does the session contain your sale_id?
3) if no, dump the user on the home page, remember to header("Location..."); die("DEAD"). the die() part is important
4) if yes, check the sale_id was paid, the notify url should have caught the POSTED payment data, if valid, allow them to update the data
5) if yes, but not valid, allow them to repay using another method, this means to redirect them to another page to attempt to pay again, but don't let them access the "change details" page, the only way you get there, is by strictly validating the payment was successful.
how does that work for you ?