简体   繁体   中英

Off by ONE Cent using paypal rest payment api

I have developed a PayPal integration for a few clients, one of them, however, is having this problem where the returned amount if off by one cent (short $0.01).

I am using the latest paypal/rest-api-sdk-php composer packages, and the total to pay that shows up during the PayPal payment steps appears correct. I am getting the paid amount using the following code:

$ppPayId = $_REQUEST['paymentId'];
$payment = PP\Payment::get($ppPayId, $this->apiCtx);
$amount = $payment->transactions[0]->amount->getTotal();

I need some advice on how to troubleshoot this issue further. I am unable to reproduce this in my sandbox environment; it only happens on the customer's live account.

You're very likely running into a classic "calculation errors due to floating point binary number approximation" issue that plagues e-commerce development. In other words, despite writing apparently good-looking additions, multiplications and division operations, you're accumulating very minor value drifting due to binary floating point representations of numbers.

There exists many articles/questions/blogs/insights on this problem. Very simple to call up by a search. Ex: Why not use Double or Float to represent currency? (800+ upvotes on this answer)

The traditional solution is to use a "proper" decimal number handling class. Also pray that the class you're picking up is doing all its calculations properly, to a certain degree. One PHP example class is https://github.com/moneyphp/money -- and, I recall a certain "Money/Money" class in PHP having an error with distributing $ into slices (+/- $0.01 happens); and it might actually be that library being linked to here, so please beware of that. I believe only fixed that error privately and not publicly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM