Blog

/How to: Calculate PayPal Fees with PHP

How to: Calculate PayPal Fees with PHP

Introduction

Today I am going to cover a topic which will come in super handy for anyone who takes PayPal payment through their website. This script will take a given amount and add the appropriate fees to it. This will allow you to pass on payPals fees to your users.

At the time of this writing, PayPal charges its Canadian customers a standard rate of $0.30 + 2.9% per transaction. This does not seem like very much, however, when a website is doing a fair bit of business through PayPal, these fees will add up and take a chunk out of your profit margins.

The following script is written with the fee amounts I outlines above. I will explain how I came up with the numbers within the code, so that you may modify to your own countries fee structure.

This code is great, as it will allow you to take any input amount, add the appropriate fees, and round up to the nearest $0.01. While this script will calculate the amount on its own, you will need to integrate it into an existing script for full automation.

The Code

<?php
$inputAmount = '100.00';
$fee = ($inputAmount + .3) / .971;
$finalAmount = round($fee , 2);
?>

Line 2 of the above code is fairly strait forward. This is the amount to charge before any fees are applied. To determine this amount, you could capture an amount with a form post, get, or any other multitude of options.

Line 3 is where things get tricky. If you look carefully, you will see that we take $inputAmount ($100 in this case), add .3 ($0.30) to it, and then divide by .971. This number is calculated by taking 100% and subtracting 2.9% (Fee amount!), leaving us with 97.1%. Change this to a mathematical integer, and you end up with .971.

Line 4 takes the amount of $fee, which is currently our $inputAmount with the appropriate fees added to it, and rounds it up to the nearest second decimal place.

Conclusion

I hope you enjoyed & find use in this code snippet. It has come in very handy not only on this very website, but on a number of client projects as well.

By | 2017-02-28T17:18:55+00:00 April 7th, 2014|Web Design & Development|